diamondCave = random.randint(1, 3)
goldCave = random.randint(1, 3)
while diamondCave == goldCave:
goldCave = random.randint(1, 3)
if chosenCave == str(diamondCave):
pygame.mixer.init()
pygame.mixer.music.load("test.wav")
pygame.mixer.music.play()
while pygame.mixer.music.get_busy() == True:
continue
print('full of diamonds!')
elif: chosenCave == str(goldCave):
print('full of gold!')
else:
print('hungry and gobbles you down in one bite!')
playAgain = 'yes'
while playAgain == 'yes' or playAgain == 'y':
displayIntro ()
caveNumber = chooseCave()
checkCave(caveNumber)
print('Do you want to play again? (yes or no)')
playAgain = input()
else:
pygame.mixer.init()
pygame.mixer.music.load("test.wav")
pygame.mixer.music.play()
while pygame.mixer.music.get_busy() == True:
continue
I want to make the code so that each time a chest is picked, it plays a sound. When a diamond gets picked it makes a cool sound, when gold is picked, a different sound is played, and when the chest eats you, it should make a game over sound. Every time I use the code of the sound, it says that the elif statement is invalid syntax. What did I do wrong?
The problem is that elif: is a syntax error.
The whole point of elif is that it means else if. Just like you can't write if: without a condition, you can't write elif: without a condition.
Meanwhile, the statement after the : is clearly supposed to be the condition expression, not a statement. So you almost certainly wanted this:
elif chosenCave == str(goldCave):
Remove the ":" after the elif
elif: chosenCave == str(goldCave):
Like this:
elif chosenCave == str(goldCave):
Related
I am making a fighting system for a text-based game I am working on, and one option is to flee.
however, I want to make it so that you can only attempt to flee once. I made it so that after 1 failed attempt, the variable fleeing_attempted is set from false to true. However, python is ignoring this and letting me attempt to flee as many times as I want.
edit: I made fixes, but the result hasn't changed. here are the modifications.
fleeing_attempted = False #the first time the variable is defined
def battle():
print("What will you do?")
print("1. attack")
print("2. flee")
action = input()
if action == "1":
print("test")
elif action == "2":
fleeing = randint(1, 100)
if fleeing in range(1, 50):
print("You got away!")
elif fleeing in range(51,100):
callable(fleeing_attempted)
print("The enemy caught up!")
battle()
elif action == 2 and fleeing_attempted:
print("You already tried that!")
battle()
Take a look at the following two lines of code:
fleeing_attempted = False
if fleeing_attempted == True:
There is no chance for fleeing_attempted to ever be True at that if statement, since it is being set to False on the line above.
Without seeing the rest of your code, it is hard to tell where the fleeing_attempted=False should go but it should probably be somewhere in initialization.
elif action == "2":
fleeing = randint(1, 100)
fleeing_attempted = False < --- Your problem is here.
if fleeing_attempted == True:
You set it to False before you do the if check, so it will never be True.
You can also do:
if fleeing_attempted:
to test if it's true.
You can also clean up your code with and
elif action == "2" and fleeing_attempted :
# rest of code
Cleaned Code:
def have_battle():
action = input("What will you do?")
print("1. Attack")
print("2.Flee")
if action == "1":
print("You choose to attack")
elif action == "2":
# do your random check
fleeing = random.randint(0, 100)
print("fleeing variable: {0}", fleeing)
if fleeing in range (1,50):
print("You choose to flee")
You had some major problems, but I cleaned up some it and you should be able to work off it.
I am trying to import games into a 'hub' which allows you to both play the games as much as you want, and allows you to choose a new game after finishing. The code is working up to the play again, and I can't figure out why.
I have tried different types of loops, and different ways to import the games, but it is not working. I do not get an error, but it does not run the game again. instead, the code runs the loop, but acts like the game code is not there after the first run. It also will not let you pick a game again after you've played it once.
while True:
print("What game would you like to play?")
print("")
print("(please only type in a number)")
Ghoice = int(input("We have: \n 1. Rock Paper Scissors \n 2. Hangman \n 3. Guess the number \n 4. Two player Tic Tac Toe"))
if Ghoice == 1:
import ROCK_PAPER_SCISSORS
while True:
ROCK_PAPER_SCISSORS.RPS
if input("Play again? (type y or n)") != "y" or "Y":
break
if input("Do you want to play another game? (type y or n)") in ["n", "N"]:
break
Note: I have more code after the first choice, but it is the same type of code as the if statement, so I didn't think it was important to show.
Here's the code for the game I'm referencing:
from random import randint
def RPS():
player = input("Rock (r), Paper (p), or Scissors (s)?")
chosen = randint(1,3)
if chosen == 1:
comp = 'r'
elif chosen == 2:
comp = 'p'
else:
comp = 's'
print(player , 'vs.' , comp)
if player == comp:
print('DRAW!')
elif player == 'r' and comp == 's':
print('Player wins!')
elif player == 'p' and comp == 'r':
print('Player Wins!')
elif player == 'r' and comp == 'p':
print('Computer Wins!')
elif player == 'p' and comp == 's':
print('Computer Wins!')
elif player == 's' and comp == 'p':
print('Player Wins!')
elif player == 's' and comp == 'r':
print('Computer Wins!')
else:
print('You either typed a capital version of one of the letters,')
print('Or an incorrect choice. either way, you gotta try again.')
RPS()
Well, first off, again isn't defined when you test it at the bottom.
Second, this line:
if input("Play again? (type y or n)") != "y" or "Y":
Will not do what you think it does. It isn't checking if the input is equal to "y", or if it's equal to "Y". Rather it checks if the input is equal to "y", and if it isn't, it evaluates "Y", which is truthy. You probably want something like this:
while True:
print("What game would you like to play?")
print("")
print("(please only type in a number)")
Ghoice = int(input("We have: \n 1. Rock Paper Scissors \n 2. Hangman \n 3. Guess the number \n 4. Two player Tic Tac Toe"))
if Ghoice == 1:
import ROCK_PAPER_SCISSORS
while True:
ROCK_PAPER_SCISSORS.RPS
if input("Play again? (type y or n)") not in ["y", "Y"]:
break
# Code for other choices
if input("Do you want to play another game? (type y or n)") in ["n", "N"]:
break
Now, you are relying on the game code to run at module load time--but that will only happen once, regardless of how many times the import statement is executed. To fix that, you'll want to replace the last line of your game code with
if __name__ == "__main__":
RPS()
That will ensure that nothing runs automatically when the module is loaded, but you will be able to run the game as a separate program if you want. Then, you'll want to replace
...
while True:
ROCK_PAPER_SCISSORS.RPS
...
with
...
while True:
ROCK_PAPER_SCISSORS.RPS()
...
to actually run the game code on each iteration of the while loop.
I'm quite new to Python, kind of new to programming and I'm having trouble creating a proper "loop".
def gameLoop():
print('1')
if ageInt == 2:
gamePlay = '{}'.format(input("Would you like to play a game?\n"))
else:
sys.exit(0)
time.sleep(1)
if any([gamePlay == 'yes', gamePlay == 'sure']):
print('you are playing a game')
elif gamePlay == 'maybe':
gamePlay = '{}'.format(input("C'mon, let,'s play...\n"))
time.sleep(1)
gameLoop()
I realize a lot of this code may be sloppy, but I'm trying to call gameLoop, so if they answer "maybe" it returns to gameLoop. Why doesn't the last line of the code return to the first line?
Edit to include full code:
import time
import sys
name = input('What is your name?\n')
print('Hello, %s!' % name)
age = int (input('how old are you?\n'))
print('Your age is: %s' % age, ' and your name is: %s' % name)
ageInt = int (1)
def gameLoop():
print('gameloopworks')
if ageInt == 2:
gamePlay = '{}'.format(input("Would you like to play a game?\n"))
else:sys.exit(0)
time.sleep(1)
if any([gamePlay == 'yes', gamePlay == 'sure']):
print('you are playing a game')
elif gamePlay == 'maybe':
gamePlay = '{}'.format(input("C'mon, let,'s play...\n"))
time.sleep(1)
print('elif works')
gameLoop()
if age < 18:
print(name, 'sorry you\'re too young')
ageInt = 1
else:
print(name, 'you are totally blankable')
ageInt = 2
gameLoop()
Your code works. A recursive call gameLoop() is in progress. Or I
didn't understand the question.
What is your name?
Vladmir
Hello, Vladmir!
how old are you?
45
Your age is: 45 and your name is: Vladmir
Vladmir you are totally blankable
gameloopworks
Would you like to play a game?
maybe
C'mon, let,'s play...
OK
elif works
gameloopworks
Would you like to play a game?
maybe
C'mon, let,'s play...
OK
elif works
gameloopworks
Would you like to play a game?
maybe
C'mon, let,'s play...
ys
elif works
gameloopworks
Would you like to play a game?
yes
you are playing a game
Process finished with exit code 0
You are doing recursion instead of a loop; you are basically calling the same function each time, but the values of each call will not persist into the next because of variable scoping (a little more advanced than what you want right now, but just in case).
Try using a while loop and that should work much better for your purpose.
keep_playing = True
while keep_playing:
if <condition to stop>:
keep_playing = False
else:
# keep game
I think your code should be this
def gameLoop():
while True:
if ageInt == 2:
gamePlay = '{}'.format(input("Would you like to play a game?\n"))
else:
sys.exit(0)
if any([gamePlay == 'yes', gamePlay == 'sure']):
print('you are playing a game')
elif gamePlay == 'maybe':
gamePlay = '{}'.format(input("C'mon, let,'s play...\n"))
if __name__ == '__main__':
gameLoop()
I made the beginning of a basic text adventure game, and I want it to loop whenever you die, but any examples of code I see aren't working, and thorugh research i still cant find something that could work.
print("A tale of time version 0.0.1. by Tylan Merriam")
print("you awaken, the room is dark and you cannot see. the sheets on your
bed are damp, and you hear a faint dripping sound.")
ch0pg1 = input('>: ')
if ch0pg1 == 'turn on light':
print("you flip the light on, it turns out the dripping was from a leaky
pipe above you. you see a dresser(outisde of bed) a chair with something
glinting on it(outside of bed) and a window(outisde of bed)")
ch1p1 = input('>: ')
if ch1p1 == 'stand':
print('you stand up, the game isnt finished so this is all there is,
try saying stand at the first choice or anything else')
else:
print('sorry, but i have no fricking clue what that means')
elif ch0pg1 == 'stand':
print('since you cannot see, you bump your head on a brick and collapse.
as you think of your last words you realize the only thing that comes to
mind is wushtub.')
diemessage = input('>: ')
if diemessage == 'lol':
print('i agree, now shut up, your dead')
else:
print('shut it, your dead')
else:
print('I have no clue what that means,')
You can try embedding a while loop within a while loop kind of like this.
while(1):
while(1):
# some code
# also some code
diemessage = input('>: ')
if diemessage == 'lol':
print('i agree, now shut up, your dead')
chc = input("play again? (y,n): ")
if chc == "y":
break # break this while loop which just starts again
elif chc == "n":
exit() # exit the game entirely
else:
# You can set this bit to your liking.
print("thats no answer, bye")
exit()
else:
print('shut it, your dead')
chc = input("play again? (y,n): ")
if chc == "y":
break # break this while loop which just starts again
elif chc == "n":
exit() # exit the game entirely
else:
# You can set this bit to your liking.
print("thats no answer, bye")
exit()
It simply creates a while loop for the game inside of a while loop. Break breaks out of the while loop while being ran, so it just exits and starts again. If the user chooses to quit, it stops the whole program.
You would think that we could create a function to make it easier, but when I tried breaking with a function it won't break, so you are going to have to keep pasting this in as of what I know. :P
Could do:
while (true)
{
//print statements
//whenever you die:
continue;
}
Well, you first need to define what you want to loop. Make a function called game() with your included code. Then this would work:
if diemessage == "lol":
print("something")
else:
print("Shut it, your dead")
game()
Right now I am doing the tutorial "Dragon Realm" from this site http://inventwithpython.com/chapter6.html
I understand what it's all doing slightly but that is not my problem. At the end I'm wanting to add a bit of code that if the player says no, it says, as I currently have it, "too bad *!" and move back up to the beginning of the program. I've gotten it to do that, but once it goes through the second time and i get to the input of whether you want to try again whether or not you type yes or no it just ends the program. I've tried multiple combinations of while, if/else, while True, while False and I am not getting the results I am wanting. I don't understand how you just keep it to keep going? It's probably really simple but I can't figure it out.
this is the code for the program.
import random
import time
def displayIntro():
print('You are in a land full of dragons. In front of you,')
print('you see two caves. In one cave, the dragon is friendly')
print('and will share his treasure with you. The other dragon')
print('is greedy and hungry, and will eat you on sight.')
print()
def chooseCave():
cave = ''
while cave != '1' and cave != '2':
print('Which cave will you go into? (1 or 2)')
cave = input()
return cave
def checkCave(chosenCave):
print('You approach the cave...')
time.sleep(2)
print('It is dark and spooky...')
time.sleep(2)
print('A large dragon jumps out in front of you! He opens his jaws and...')
print()
time.sleep(2)
friendlyCave = random.randint(1, 2)
if chosenCave == str(friendlyCave):
print('Gives you his treasure!')
else:
print('Gobbles you down in one bite!')
playAgain = 'yes'
while playAgain == 'yes' or playAgain == 'y':
displayIntro()
caveNumber = chooseCave()
checkCave(caveNumber)
print('Do you want to play again? (yes or no)')
playAgain = input()
You could add simply,
if 'n' in playAgain:
print "too bad"
playAgain = 'yes'
At the end (inside your while loop)
By the way, these two lines can be combined:
print('Do you want to play again? (yes or no)')
playAgain = input()
as simply:
playAgain = input('Do you want to play again? (yes or no)')
Because input will display the string argument when asking for input.