I am a beginner programmer. I want to create a game where user input affects the course of the game. I am kind of stuck on the very beginning.
def displayIntro():
print("You wake up in your bed and realize today is the day your are going to your friends house.")
print("You realize you can go back to sleep still and make it ontime.")
def wakeUp():
sleepLimit = 0
choice = input("Do you 1: Go back to sleep or 2: Get up ")
for i in range(3):
if choice == '1':
sleepLimit += 1
print("sleep")
print(sleepLimit)
if sleepLimit == 3:
print("Now you are gonna be late, get up!")
print("After your shower you take the direct route to your friends house.")
elif choice == '2':
print("Woke")
whichWay()
else:
print("Invalid")
def whichWay():
print("After your shower, you decide to plan your route.")
print("Do you take 1: The scenic route or 2: The quick route")
choice = input()
if choice == 1:
print("scenic route")
if choice == 2:
print("quick route")
displayIntro()
wakeUp()
i have a few bugs and I've tried to work them out on my own but I'm struggling.
1) I only want the player to be able to go back to sleep 3 times and on the third i want a message to appear and another function to run (havent made yet).
2) if the player decides to wake up i want whichWay() to run and it does but instead of exiting that for loop it goes right back to that loop and asks if the player wants to wake up again i have no idea how to fix this.
3) is there a better way i can go about making a game like this?
Thank you for your time and hopefully your answers.
The code below should work.
1. I moved the line 'choice = input("Do you 1: Go back to sleep or 2: Get up ")' into the for loop.
2. I added a break statement at the end of the elif block.
def wakeUp():
sleepLimit = 0
for i in range(3):
choice = input("Do you 1: Go back to sleep or 2: Get up ")
if choice == '1':
sleepLimit += 1
print("sleep")
print(sleepLimit)
if sleepLimit == 3:
print("Now you are gonna be late, get up!")
print("After your shower you take the direct route to your friends house.")
elif choice == '2':
print("Woke")
whichWay()
break
else:
print("Invalid")
Related
Wondering why its printing my else statement twice in this scenario. In theory it should just execute it once after an incorrect key is read, and loop back.
the out put I am getting after pressing a non 'enter' key How can I avoid this?
import random
import keyboard
#Constant values to assign as a win or loss
_WIN = 1
_LOSE = 0
#Create and store game hand choices
handChoice = ['Spock', 'Lizard', 'Rock', 'Paper', 'Scissors']
print('\nThis is advanced Rock, Paper, Scissors! Press ENTER to start the automated game->')
while True:
if keyboard.read_key() == 'enter':
break
else:
print('Please press ENTER!')
#Hand choices randomly assigned to player 1
player1 = random.choice(handChoice)
print('Player 1 uses ' + player1 + '!\n')
Looking true the docs you could use this:
keyboard.wait('enter')
It will also use less cpu. But you would need the async library with timeout to also give output.
you could also use this:
while True:
if keyboard.read_key() == 'enter':
break
elif event.event_type == keyboard.KEY_DOWN:
print('Please press ENTER!')
I am trying to set up a fighting game where it prints a question and you have to answer the question correctly to win the fight. But I a finding that I can't find a way to get the code t read the random question to be read thus meaning I can't get it to read the answer as correct.
I've tried making the random be separated into multiple variables but that didn't work. I haven't had much time to try anything else either.
import random
fights=("I run but never walk, I have a bed but never sleep", "What time
of day is the same fowards as it is backwards?", "3+2")
FIGHTS=random.choice(fights)
print(FIGHTS)
ans1="river"
ans2="noon"
ans3="5"
que1=input("What shall you say?\n")
if ans1=="I run but never walk, I have a bed but never sleep":
print("You won!")
elif ans2=="What time of day is the same fowards as it is backwards?":
print("You won!")
elif ans3=="3+2":
print("You won!")
else:
print("You lost...")
If you answer correctly it displays "You won!" and if you answer wrongly it displays "You lost..." but it can't read what is printed so it always displays "You lost..."
A good approach would be to store the questions and answers in a dictionary and use good variable names.
import random
fights = {"I have a bed but never sleep": "river",
"What time of day is the same fowards as it is backwards?": "noon",
"3+2": "5"}
question = random.choice(tuple(fights.keys()))
print(question )
answer = input("What shall you say?\n")
if answer == fights[question]:
print("correct")
else:
print("wrong")
If you are not going to use this dictionary again, you can use fights.popitem() instead. Keep in mind that if using Python >= 3.7 popitem will always return the same key-value pair:
fights = {"I have a bed but never sleep": "river",
"What time of day is the same fowards as it is backwards?": "noon",
"3+2": "5"}
question, correct_answer = fights.popitem()
print(question)
user_answer = input("What shall you say?\n")
if user_answer == correct_answer:
print("correct")
else:
print("wrong")
I'm making a guessing game or computer science in school where the number to guess is seven. I have tried using while loops and if elif else statements but it doesn't seem to want to make a conditional loop My code is as follows:
guess=int(input("Guess a number!"))
var=1
while var==1:
if guess !=7:
print("Try again")
else:
print("Well done")
Any help would be appreciated thanks. I need it in about a week and a half's time.
If you're trying to allow your player to continuously guess the input needs to be at the top of the while loop, before the conditional-branch
while(True):
guess = input("Make a guess: ")
if(guess == 7):
print(guess,"was correct!")
break
else:
print("Nope. Guess again.")
Of course, you could make it more interesting in a variety of ways.
guess=int(input("Guess a number!"))
var=1
while var==1:
if guess !=7:
print("Try again")
guess=int(input("Guess a number!"))
else:
print("Well done")
var=0 #set var to 0, to exit the loop
Try this. You need to exit the loop, and to do that, var needs to be set to 0.
Thanks in advance for your answer(s). So, I just started learning Python, and was faced with a challenge that now is mind bugging. Here is the challenge:
Objective was to write a program that simulates a fortune cookie. The program should display one of five unique fortunes, at random, each time it's runs.
My solution:
# Program simulates fortune cookie.
# Displays one of five unique fortunes at random
"""
Fortunes:
* You will meet someone that will change your life today.
* Invest in lottery this week because you will win big.
* You will get a call from someone with great influence this week.
* Purchase chinese food as you will read a fortune that will come to pass.
* Good news about an inheritance will come shortly.
"""
# Steps:
# Display a Welcome message explaining what the Fortune cookie program is about, and how users can use it.
# Import random module to randomize the messages.
# Employ loop to repeat.
#Welcome
print("\t\t\n<<<Welcome to Your Fortune Cookie.>>>")
print("\t*To see what the Fortune Cookie Ginie has in store for you.")
print("\t*Ok, here we go...\n")
print(input("Press Enter to Reveal your Fortune: "))
#random module
import random
fortune1 = random.randint(1, 6)
#loop body
fortune1 < 1
while True:
print("You will meet someone that will change your life today.")
print(input(">>Press Enter again to Reveal another Fortune: "))
if fortune1 == 2:
print("Fortune: Invest in lottery this week because you will win big.")
print(input(">>Press Enter again to Reveal another Fortune: "))
elif fortune1 == 3:
print("Fortune: You will get a call from someone of great influence this week.")
print(input(">>Press Enter again to Reveal another Fortune: "))
elif fortune1 == 4:
print("Fortune: Purchase chinese food as you will read a fortune that will come to pass.")
print(input(">>Press Enter again to Reveal another Fortune: "))
elif fortune1 == 4:
print("Fortune: Good news! An inheritance will come shortly.")
print(input(">>Press Enter again to Reveal another Fortune: "))
elif fortune1 == 5:
print("Fortune: Aha! You will win something this weekend")
print(input(">>Press Enter again to Reveal another Fortune: "))
else:
print("Let's check again...")
fortune1 += 1
print("That's all your fortune")
Although I want to run it differently, but the program sort of ran. I guess my question is: is there another way i could've done this? Thanks again for your responses.
Another way to do it is have a list of the outputs, then randomly choose one output from the list with random.choice(list). Example:
import random
fortunes = ['fortune1', 'fortune2', 'fortune3']
while True:
input("Press enter to receive a fortune. ")
print(random.choice(fortunes))
I'm trying to write a MasterMind game using classes and objects and I'm currently stuck around some of my loops.
while True:
# create a combination
# test the combination
while game_won == False:
print(scoreboard)
# player input combination
# combination is tested then added to scoreboard
tries_left = tries_left+1
if game_won == True:
print(You Won!)
input = Play Again? Y/N
if tries_left == 10:
print(You Lost!)
input = Play Again? Y/N
How do I do to go back to my while True -> create combination from my last if statement? (if tries_left == 10:)
What's wrong
Your first while True doesn't have anything in it, You need to indent code under it if you want it to be inside the loop.
There is a few typos, missing comment characters, and quotation marks.
What needs to happen
When the nested while loop while game_won == True exits, the code will return looping the parent loop while True, which will replay the game, if the user wishes.
Your code fixed (with a few improvements)
Following is how you can loop the game forever (given the user wishes it).
# Assume user wants to play when the program runs
user_wants_to_play = True
ans = ""
# loop the entire game while the user wishes to play
while user_wants_to_play:
# Create the combination
# Test the combination
# Game isn't done when started
game_done = False
tries_left = 10 # Arbitrary number I chose
while not game_done:
# Play the game
print("Scoreboard")
# Subtract one to tries left
tries_left -= 1
if game_done:
print("You won!")
elif tries_left == 0:
print("You lost!")
game_done = True
# if users answer was 'n'
ans = input("Play again? Y/N \n")
if ans.strip().upper() == 'N':
user_wants_to_play = False
Improvements
Boolean logic is more pythonic using not instead of myBool == False
while True: changed to while user_wants_to_play:
User input is scrubbed to ignore white-space and lower case
Changed game_won to game_done
Made tries_left count down instead