Hy guys i have the following problem - Write a program to play the following simple game. The player starts with $100. On each
turn a coin is flipped and the player has to guess heads or tails. The player wins $9 for each
correct guess and loses $10 for each incorrect guess. The game ends either when the player
runs out of money or gets to $200.
My program is actually running. However when players points go bellow zero my program still runs and that is not what i expected. I need to know if there is something that i can do in my if sentences or if there is an easier way to make statements when i have to much conditions.
import random
list=['heads','tails']
def game():
p1=100
p2=100
while (p1>0 or p2>0)and(p1<200 or p2<200):
x=random.choice(list)
x1=input('digit your guess player1 - ')
x2=input('digit your guess player2 - ')
if x1==x:
p1+=30
else:
p1=p1-40
if x2==x:
p2+=30
else:
p2=p2-40
return p1,p2
print(game())
I expect the program to return the scores and end if any player points goes above 200 or bellow 0
If I consider your original problem, the problem is that you are returning whatever current value the player has, instead you should remember the last score and if the condition you want the game to stop on happens, return the last score. This will ensure only valid scores are returned
import random
list=['heads','tails']
def game():
player=100
last_score = 0
#Conditions to break while loop
while player > 0 and player < 200:
#Keep track of last score
last_score = player
#Get choice from player, and increase/decrease score
x=random.choice(list)
x1=input('digit your guess player1 - ')
if x1 == x:
player += 9
else:
player -= 10
#Return last score
return last_score
print(game())
Extending this idea to the 2 player game will solve your issue as well!
import random
list=['heads','tails']
def game():
p1=100
p2=100
last_scores = 0,0
# Conditions to break while loop
while (0<p1<200) and(0<p2<200):
# Keep track of last score
last_scores = p1,p2
# Get choice from player, and increase/decrease score
x=random.choice(list)
x1=input('digit your guess player1 - ')
x2=input('digit your guess player2 - ')
if x1==x:
p1+=30
else:
p1=p1-40
if x2==x:
p2+=30
else:
p2=p2-40
return last_scores
print(game())
Change the while condition to:
while p1>0 and p2>0 and p1<200 and p2<200
but it is more readable if:
while 0<p1<200 and 0<p2<200
Despite importing the variable 'health' from a different module, the function below provides the error shown in the title. 'Health' is also globalised and I have removed both the globalisation and the importation of the variable and I still receive the same error.
Below is the function that is causing the issue.
def combat():
enemy_health = (random.choice(random_enemy_Health))
enemy_attack = (random.choice(random_enemy_Attack))
print("\nYou are fighting a" ,random.choice(enemies), "with an attack amount of" ,enemy_attack, "and a health amount of" ,enemy_health,".")
while health > 0 and enemy_health > 0:
if turn == 1:
while loop == False:
response=input()
try:
move = response("Do you want to attack or flee? Type '1' to attack and '2' to flee.")
move = int(move)
if move == 1:
enemy_health = enemy_health - attack
print("You attacked!")
loop = True
elif move == 2:
hub_travel()
print("You fled the battle, come back once you are stronger!")
loop = True
else:
print("Invalid number, try again")
continue
except:
print("Invalid number, try again")
continue
turn = 2
if turn == 2:
AImove = randint(1,2)
if AImove == 1:
print ("Enemy attacked!")
health = health - enemy_attack
turn = 1
continue
print ("game over!")
if enemy_health == 0:
print("The enemy has been defeated!")
gold += random.choice(gold_dropped)
The error occurs on this line in particular:
while health > 0 and enemy_health > 0:
If I were you, instead of relying on globals, I would use parameters. This advice may help you to track some errors.
Globals variables is a possibility in programs that have a few lines of code. But, when you application grows, it is a bit hard to track the current value of some variable, because it can be used in several functions or methods (probably, you need a mental mapping to find out the current value). So, this is one of the reasons why you must prefer to use local variables or parameters instead of globals.
This change would allow your function to work the way you want:
def combat(health):
...
Of course, you'd have to find the places where you call the function and pass in the value for health. I don't know if the code at that point has access to that information.
This is probably the simplest fix that could possibly address this issue. It is certainly not the best fix, but this is not a good place for an architecture tutorial.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
In my evergrowing quest for knowledge I would like to know if there is any way I can reduce the line count or make the code more efficient. Its for a game I have made and I have challenged myself to make it as short as I can, (in the original it was about twice as long as this :D)
import random
gameLives,hints,wonGame,levels,awardedLives,levelRange=3,6,0,[1,2,3,4,5,6,7,8,9,10],[1,3,5,7,10,12,15,20,0,0],[5,10,20,50,100,200,250,300,400,500]
def is_valid(guess):
try:
guess=int(guess)
return True,guess
except:
print("Try again, not a number")
repeat=1
def GameLevel(Range,gameLives,level,hints):
lives,hints,targetnumber,repeat=gameLives,hints,random.randint(1,1),1
print("LEVEL {}\nThinking...".format(level))
if level>1:
print("You now have {} lives remaining".format(gameLives))
if level==10:
print("Welcome to the hardest level\nNo bonus lives are awarded for the final level")
print("This number is between 1 and "+str(Range))
while repeat==1:
guess=input("What is your guess? ")
guess,repeat,targetnumber=guess.lower(),0,str(targetnumber)
if guess=="hint":
if level>=3:
if hints!=1:
targetnumber=int(targetnumber)
print("Number is between {} and {}".format((targetnumber // 10) * 10, (targetnumber // 10 + 1) * 10))
repeat,hints=1,hints-1
else:
print("Sorry you have ran out of hints :(")
repeat=1
else:
print("Hints are not available until level 3")
repeat=1
elif guess==targetnumber:
print("Well done, You have guessed my number!")
return lives,hints
elif guess!=targetnumber:
if is_valid(guess)==True:
print("Sorry that is not my number, you have lost a life. :(")
targetnumber,lives,repeat=int(targetnumber),lives-1,1
if lives<=0:
print("You have lost all your lives, so this means I win\nThe program will now end")
input("")
exit()
if guess<targetnumber:
print("The target number is higher")
else:
print("The target number is lower")
else:
repeat=1
print("Welcome to my number guessing game!\nI will think of a number between a certain range and you have to guess it.\nEach time you guess my number I will think of a harder one.\nYou will start with {} lives and {} hints, Good Luck!\nTo use your hint you will have to enter the word hint\nExtra lives will be awarded for each completed level".format(gameLives,(hints-1)))
a,b=0,0
for level in levels:
Range=levelRange[a]
gameLives,hints=GameLevel(Range,gameLives,level,hints)
if gameLives>0 and wonGame!=10:
addLives=awardedLives[b]
if addLives!=0:
print("You have gained {} extra lives".format(addLives))
gameLives+=addLives
wonGame+=1
a,b=a+1,b+1
score=gameLives+10*(hints-1)
print("Calculating your score.\nYour score is {} . Well done!".format(score))
This was the smallest that I ever managed to get the program with still working in the same way, in the question the code was 63 lines, I managed to reduce it to 29 lines;
import random; gameLives,hints,wonGame,levels,awardedLives,levelRange=3,6,0,[1,2,3,4,5,6,7,8,9,10],[1,3,5,7,10,12,15,20,0,0],[5,10,20,50,100,200,250,300,400,500]
def is_valid(y):
try:y=int(y);return True
except:print("Try again, not a number")
def GameLevel(Range,gameLives,level,hints):
lives,hints,targetnumber=gameLives,hints,random.randint(1,Range);print("LEVEL {}\nThinking...".format(level))
if level>1:print("You now have {} lives remaining".format(gameLives))
if level==int(levels[-1]):print("Welcome to the hardest level\nNo bonus lives are awarded for the final level")
print("This number is between 1 and "+str(Range))
while True:
guess=input("What is your guess? ");targetnumber=str(targetnumber)
if guess.lower()=="hint":
if level>=3:
if hints!=1:targetnumber,hints=int(targetnumber),hints-1;print("Number is between {} and {}".format((targetnumber // 10) * 10, (targetnumber // 10 + 1) * 10))
else:print("Sorry you have ran out of hints :(")
else:print("Hints are not available until level 3")
elif guess==targetnumber:print("Well done, You have guessed my number!");return lives,hints
elif guess!=targetnumber and is_valid(guess)==True:
print("Sorry that is not my number, you have lost a life. :(");guess,targetnumber,lives=int(guess),int(targetnumber),lives-1
if lives<=0:exit(input("You have lost all your lives, so this means I win\nThe program will now end\n"))
print("The target number is {}".format("higher" if (guess<targetnumber) else "lower"))
print("Welcome to my number guessing game!\nI will think of a number between a certain range and you have to guess it.\nEach time you guess my number I will think of a harder one.\nYou will start with {} lives and {} hints, Good Luck!\nTo use your hint you will have to enter the word hint\nExtra lives will be awarded for each completed level".format(gameLives,(hints-1)));a,b=0,0
for level in levels:
gameLives,hints=GameLevel((levelRange[a]),gameLives,level,hints)
if gameLives>0 and wonGame!=int(levels[-1]):
if awardedLives[b]>0:print("You have gained {} extra lives".format(awardedLives[b]));gameLives+=awardedLives[b]
wonGame+=1
a,b=a+1,b+1
input("Calculating your score.\nYour score is {} . Well done!".format(gameLives+10*(hints-1)))
For my computer science class final, we have been instructed to make our own game in Python.
Requirements:
1. Needs to use both a “while loop” and a “for x in y loop.”
2. Needs to use list to either keep track of information or score
3. Needs to use a function for gameplay, tracking score, both.
4. Display some art either at the beginning, after, or in between turns.
5. Can be multi player or single player.
6. Must carry a complexity commensurate with a final project.
Anyways, I decided to make a game similar to horse in basketball. The object of the game is to find the answer of the math problem before time runs out. If you don't, you get a letter in horse. Once you get all the letters of horse, your game is over.
Here is what I have so far:
import random
import time
from timeit import default_timer
print("welcome to Jared's Math Horse game!")
time.sleep(1)
print("You will have to do some basic geometry and algebra problem,and some brain teasers...")
time.sleep(1)
print("For each you get wrong, you get a letter, and it will spell 'HORSE'. Once you get all letters, you lose. ROUND TO THE NEAREST INTEGER!!!!!!!!")
time.sleep(1)
###BEgin actual stuff
how_long = int(input("How many times(problems) do you want to play? (above or equal 5)"))
score = 0
##Problems
problems = ["A cylinder has a radius of 5. It's height is 6. What is the volume?471","A boy buys two shirts. One costs $15 and he pays $27 for both shirts. How much was the 2nd shirt?12","dat boi costs $12 after a 15% discount. What was the original price?14.12","A square pyramid with a height 12 and a side length 5. What is the volume?20","What is the square root of 36?", "What is the roman numeral for 500? QUICK USE GOOGLE!!!D","On a scale of 100-100 how cool is jared?100" ]
#######End of variables
####Func time
def horse(score,problem,speed):
b = input("You have {} seconds. Press enter to begin. Round answers to nearest integer.".format(speed))
begin = default_timer()
howfast = default_timer() - begin
print(random.problem[0,7])
##Check answer
answer = input("What is your answer?:")
## Give score
##loops
for x in how_long:
while True:
if score !=5:
a = random.randint(0,7)
problem = problems[a]
##Speed
speed = int(input("How fast do you want to play?? 1=slow 2=medium 3=FAST"))
if speed == (1):
speed = random.randint(30,60)
if speed == 2:
speed = random.randint(20,40)
if speed == 3:
print("spicy!")
speed = random.randint(10,30)
score = horse(score,problem,speed)
if score == 0:
print("You have a perfect score. Good work.")
if score == 1:
print("You have an H")
if score == 2:
print("You have Ho")
if score == 3:
print("You have Hor")
if score == 4:
print("You have Hors")
if score == 5:
print("You have Horse. Game over, loser.")
break
horse()
So. I'm not sure how to make it if you type in the correct answer, you won't get a letter, and move on. I tried used a 'if and' statement and that is it. BTW, the answers to the problems are at the end. Help is VERY appreciated. Sorry if I didn't explain this well, I am a noob at this. Haha
That data structure is a disaster. You would be better off doing something like this. Keep a dict of problem : correctAnswer then get a random key, ask for some user input and time it. You still need to implement the horse logic though.
score = 0
maxTime = 3 #how many milliseconds a user has to answer the question to get it right
problems = {
"A cylinder has a radius of 5. It's height is 6. What is the volume?" : "471",
"A boy buys two shirts. One costs $15 and he pays $27 for both shirts. How much was the 2nd shirt?" : "12",
"dat boi costs $12 after a 15% discount. What was the original price?" : "14.12",
"A square pyramid with a height 12 and a side length 5. What is the volume?" : "20",
"What is the square root of 36?" : "6",
"What is the roman numeral for 500? QUICK USE GOOGLE!!!" : "D",
"On a scale of 100-100 how cool is jared?" : "100"
}
for i in range(how_long):
startTime = time.time()
thisProblem = random.choice(list(problems.keys()))
answer = input(thisProblem + ": ")
endTime = time.time()
totalTime = round(endTime - startTime, 2)
correctAnswer = problems[thisProblem]
if answer == correctAnswer and totalTime < maxTime:
print("Correct!, you took", totalTime, "ms to answer")
score += 1
elif answer != correctAnswer:
print("Incorrect!, the correct answer was", correctAnswer)
elif totalTime > maxTime:
print("Correct, but you took", totalTime, "ms to answer but are only allowed", maxTime, "ms")
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I'm trying to loop a battle menu. Although it's not finished yet, I'm having problems looping it. I would like the menu to keep looping until myhp, or hp is lower than 0. so i used "while myhp > 0 or hp > 0:"
it does not work, what am I doing wrong?
def fightmode(name, hp, dmg, gold):
print '\n\n\nYou are in a fight with %s' %name
print '%s has %sHP' %(name, hp)
while myhp > 0 or hp > 0:
hp = hp - mydmg
print '\n\t1. Attack \n\t2. Guard \n\t3. Run away.'
opt1= ''
allowed = ["1", "2", "3"]
while opt1 not in allowed:
opt1 = raw_input("\nWhat will you do? ")
if opt1 == "1":
print "You have inflicted %d damage on %s. %s's HP is %s" %(mydmg, name, name, hp)
if myhp > 0 :
print"myhp"
if hp > 0 :
print"theirhp"
nevermind, I think I got it. I changed "or" to "and" and it seems like it's working.
Was this the right method?
Right now you need myhp OR hp to be true for the while loop to continue going.
So if one of them drops to 0 and thus "goes False" the other one is still going to be true and keep the loop going.
So how can you do something about that?? (You already guessed right... Use and instead!)
So while myhp > 0 or hp > 0: should be while myhp > 0 and hp > 0: (Note that the or is exchanged for and!)
Because while loop lopping until Boolean expression is true and stops after expression get false
So you need to write while myhp < 0 or hp < 0: