initial_p = input("Enter the initial point")
def game():
x = 1
guess = input("Guess value")
if guess == 1:
initial_p += 2
else:
initial_p -= 2
game()
replay = raw_input("Do you want to try it again? Y/N")
if replay == 'Y':
game()
each game needs 2 points
I made it really simple just to explain this stuff easily
So to play each game, it requires you to have at least 2 points otherwise it becomes game over
if you guess right, you earn 2 points
if not, you lose 2 points.
with the outcome(points), you can either play again or quit
if you play again, you pay two points
HOWEVER, when you play for the second time or more, that line
initial_p += 2 and initial_p -= 2 still have points that you typed in the very beginning
The quick and dirty response is to change to the following.
def game(initial_p):
#Your Code
return initial_p
initial_p = game(initial_p)
Basically, you're placing the global variable as a local variable and reassigning the global.
This should also happen at the very bottom as well.
Also, you can just ask for the input inside of the function, and have a default argument of initial_p.
For example,
def game(first_time=True)
#Ask for input with if first_time:
return initial_p
And modify some global point value or something from the return.
Sorry if this is sloppy, was written on my mobile.
Related
I am a beginner to coding in general and am trying to learn python and so I have been learning how to make a few basic games to figure things out and practice my basics... I have made a game to guess the number that is generate at a random interval of 0-100 and give feedback on if you guessed higher or lower to narrow it into your results. I managed to make the game work and I started trying to add a replayability framework so when you guess correct the game restarts automatically and a new number is generated to guess, however I am not able to make a new number generate. Originally I made the number generate outside the loop and made a loop that seemed effective but the number stayed the same, added it into the loop and it changed with every guess. so I tried adding a secondary def and pointing to it and making the number regenerate there but it doesnt seem to be making a new number still, and if I remove the generation outside of def replay def game no longer sees num as a valid variable. I am unsure how to accomplish this, any advise would be helpful....
import random
num = random.randint(0,100)
def Game():
print("Guess the Number: ")
guess = input()
guess = int(guess)
if guess==num:
print ("CORRECT!!!!!")
Replay()
elif guess>num:
print ("Sorry to high... Try again")
Game()
elif guess<num:
print ("Sorry to low... Try Again")
Game()
def Replay():
num = random.randint(0,100)
Game()
Replay()
This is a example of your code written more correctly according to me:
from random import *
def Game():
replay = 0
while replay == 0:
num = randint(0, 100) # if you want the number to revert every time you make a mistake, leave the line as it is otherwise put this assignment before the loop.
guess = int(input("Choose a integer number from 0 to 100: "))
if guess == num:
print(f"{guess} is mysterious number")
replay = 1
elif guess > num:
print(f"Sorry but {guess} is high, the number was {num}, try again if you want (0=yes, 1=no)")
replay = int(input())
elif guess < num:
print (f"Sorry but {guess} is low, the number was {num}, try again if you want (0=yes, 1=no)")
replay = int(input())
Game()
I'm trying to make a simple text-based Python game around blackjack. The game knows the variable 'hand' and 'd_hand' which are your hand and the dealer's hand, but won't update it after each new card is drawn. hand and d_hand are assigned to a random integer between 1 and 11 plus your current hand before it added the random number, which in theory should mean that your hand updates itself every time a new card is drawn.
Here's the code:
def draw(hand, d_hand):
x = randint(1, 11)
card = x
hand = x + hand
print("You drew...")
print(card)
y = randint(1, 11)
d_card = y
d_hand = y + d_hand
print("Dealer drew...")
print(d_card)
print("Your hand: ")
print(hand)
print("Dealer's hand: ")
print(d_hand)
ask()
And here's the output of everything:
(Note: I only am showing one function here, the game is obviously more than just this one function I'm showing.)
Press enter to begin:
You drew...
1
Dealer drew...
5
Your hand:
1
Dealer's hand:
5
Hit or stay? (h/s): h
You drew...
10
Dealer drew...
8
Your hand:
10
Dealer's hand:
8
Hit or stay? (h/s): '''
I'm not really sure what the issue is here...
By the way, I'm new to this site so I can't like any comments, so thank you to everyone who answered!
If hand and d_hand are lists (or mutable objets),
you may want to update the object itself by replacing hand = x + hand with hand.append(x).
Otherwise, your code will just create a new local list hand that will be lost when the function ends.
From the code you posted it looks like you aren't returning the new hands. So when the function returns the hands will revert to whatever value they were before the call. You can return tulples in python like return (hand,d_hand) and then do something like hand,d_hand = draw(hand,d_hand)
Generate a random number between 1 and 9 (including 1 and 9). Ask the user to guess the number, then tell them whether they guessed too low, too high, or exactly right. (_Hint: remember to use the user input lessons from the very first exercise
Extras:
Keep the game going until the user types “exit”
Keep track of how many guesses the user has taken, and when the game ends, print this out.
I actually cant figure out why my program is not printing the prints in the if clauses. Did i call wrong the first fucntions in my while loop?
import random
def cpu_guess():
cpu_number=random.randint(1,9)
return cpu_number
print(cpu_guess())
def player_guess():
player_number=input('Digit a number between 1 and 9\n')
return player_number
def game():
r_guesses=0
w_guesses=0
while player_guess()!='exit':
if int(player_guess())>int(cpu_guess()):
print('Higher value than generated')
w_guesses+=1
elif int(player_guess())<int(cpu_guess()):
print('Lower value than generated')
else:
print('You have entered the right value')
r_guesses+=1
return r_guesses,w_guesses
print(game())
I am not sure i can do this while player_guess()!='exit': Do i need to creat a variable like this
guess=player_guess() and write while guess!='exit'
You're calling player_guess over and over, and each time you call it, it will stop and wait for input. It's getting stuck waiting for input potentially three times per loop. Call the function once and save the result in a variable:
def game():
r_guesses = 0
w_guesses = 0
guess = None # Save it here
while guess != 'exit':
guess = player_guess()
if guess > int(cpu_guess()):
print('Higher value than generated')
w_guesses+=1
elif guess < int(cpu_guess()):
print('Lower value than generated')
else:
print('You have entered the right value')
r_guesses += 1
return r_guesses, w_guesses
print(game())
And then, as noted in the comments, do something similar for the computer's guess. The computers turn is changing constantly, so you may get through all the checks and get unexpected results for that reason. Think about what happens when those functions are called.
You keep changing the values in the middle of the loop; this is chaos, not a logic game.
# Get a player guess and see whether it's "exit"
while player_guess()!='exit':
# Get a new guess; also make a new target number.
if int(player_guess())>int(cpu_guess()):
print('Higher value than generated')
w_guesses+=1
# Get a new guess; also make a new target number.
elif int(player_guess())<int(cpu_guess()):
print('Lower value than generated')
else:
print('You have entered the right value')
r_guesses+=1
Instead, you need to make one target number the player is trying to guess. Do not change it during the game. Within the loop, have the player guess once: do not ask for more input until you've properly evaluated that guess and responded.
# Get a player guess and see whether it's "exit"
target = int(cpu_guess())
player_input = player_guess()
while player_input != 'exit':
guessed_num = int(player_input)
if guessed_num > target:
print('Higher value than generated')
w_guesses+=1
elif ...
See how that works? Don't go back to your input routine until you're done with the current guess. Don't go back to the target generation routine until the player is done guessing the previous number.
This question already has answers here:
Loop until a specific user input is received in Python [duplicate]
(3 answers)
Closed 4 years ago.
This is code I wrote, it runs perfectly and so does the function this code is from except for one part, when it comes to the part where I ask the user if they want to try again, if they select no then it stops which is what is suppose to happen. On the other hand, if they say yes ‘y’ they will get another exact same prompt 'Would you like to try again? (y/n) '. You can say y 100 times and nothing will happen, my goal is for the code to go back and call the function from the start. I have tried a break if the user says ‘y’ to try and get out of the loop etc but it did not work and I now have no idea…
Additionally, as you can see, I have correct digits which compares to see if the user guessed number is in the generated list, that part I have no problem with. Now with the correct locations, I am not sure how to do that, the goal is to check is both the number and location is the name in both lists.
import random
play = True
turnsleft = 1
#this is a function that is in charge of generating a random password
def generatePassword():
generatePassword = [] #create an empty list
for i in range(1,6):
generatePassword.append(random.randint(1,9))
return generatePassword
'''this is a function that prompts the userfor their guess
the input will be comprimised of 5 different variables to store
the different numbers which will then all be added to the list of user number'''
def getUserGuess():
getUserGuess = [] #create an empty list
v1,v2,v3,v4,v5 = input("Please take a guess of the password by entering 5 numbers(comma between each): ").split(",")
v1,v2,v3,v4,v5 = int(v1), int(v2), int(v3), int(v4), int(v5)
for i in(v1,v2,v3,v4,v5):
getUserGuess.append(i)
return getUserGuess
#this function will compare the cpu generated password to the user inputed numbers list
def reportResult(generatePassword,getUserGuess):
correctdigits = 0
correctlocations = 0
global turnsleft #use the play variable initiated outside the funtion
global play #use the play variable initiated outside the funtion
while play is True:
if getUserGuess == generatePassword:
print("Congradulations! You have guessed the right password.")
elif turnsleft == 0:
print("You will never guess my password! It was " +str(generatePassword()))
playagain = input("Would you like to play again? (y/n) ")
if playagain == 'n':
play = False
else:
turnsleft-= 1
for e in getUserGuess():
if e in generatePassword():
correctdigits+= 1
for e in getUserGuess():
if e in generatePassword():
correctlocations+= 1
print(str(turnsleft) +" guesses left.")
print(str(correctdigits) +" of 5 correct digits.")
print(str(correctlocations) +" of 5 correct locations.")
return reportResult
while play is True:
reportResult(generatePassword,getUserGuess)
I believe you simply need to set 'turnsleft' to some value greater than 0 in when 'turnsleft' is 0.
For example:
elif turnsleft == 0:
print("You will never guess my password! It was " +str(generatePassword()))
turnsleft = 2 #<-- Reset turns here!
playagain = input("Would you like to play again? (y/n) ")
if playagain == 'n':
play = False
This will allow you to 'start a new game' with the turns set to some value. But it also introduces new problems. Perhaps you should write a resetGame() that will edit all the variables it needs to to truly start from scratch.
I'm trying to create a function that simulates a fight. So far I have a list and something that picks at random one of them that I found in another post. I can't seem to make an if statement that prints out “Hit!” or “Dodge!” or “Critical Hit!” when it chooses the respective word because it gives a syntax error for whatever reason. Can anyone help me? What do I do so I can make the if statement?
Health = 10
dodge = 1
dmg = 1
hit = dmg + 1
crhit = hit * 2
def fight():
while 1 == 1:
global Health
global dodge
global hit
global dmg
chances = [hit, hit, dodge, crhit, hit]
from random import choice
fight()
You have only imported the function choice, you still have to call it:
from random import choice # This makes it so we can use the function in the script.
Health = 10
dodge = 1
dmg = 1
hit = dmg + 1
crhit = hit * 2
def fight():
while 1:
mychoice = choice(chances) # We call the function. It gets a random value from the list
if mychoice == hit: # Create an if/elif for each possible outcome
dostuff()
elif ...
fight()
Then you can use an if/elif structure to do stuff with each option
Also, those global statements are not needed, as you actually aren't modifying the variables themselves (Unless you plan on doing this later).
while 1 == 1 can simply be written as while 1, as that can also be considered True.
I'm not gonna give away the entire answer, since you should work at that, but doing random.choice(testList) returns a random element from the list, you can use these to get one from hit, dodge and crhit. You can just write three if-elif statements to check for each. Short examples (you should get your answer from here),
>>> varOne = 2
>>> varTwo = 3
>>> varThree = 4
>>> from random import choice
>>> testVar = choice([varOne, varTwo, varThree])
>>> if testVar == varOne:
print 'abc'
elif testVar == varTwo:
print 'def'
else:
print 'ghi'
abc