snakes and ladders dice problems(python) - python

fixed it now thanks for the help, just needed to indent everything for my player 2
so i have made a snakes and ladders game and i'm having problems with the dice:
while player1roll != "YES":
player1roll=input("player1 ready to roll??\n").upper
player1roll=random.choice(dice)
print("you rolled a:", player1roll)
after this it just keeps repeating "player1 ready to roll??"
here is the whole of my player1 code:
while selection != "PVP" or "AI":
selection=input("player vs player(PVP) or with AI (AI)??\n").upper()
if selection == "PVP":
while player1pos or player2pos <100:
**while player1roll != "YES":
player1roll=input("player1 ready to roll??\n").upper
player1roll=random.choice(dice)
print("you rolled a:", player1roll)**
player1pos+=player1roll
if board[player1pos] >0: #if the number is bigger than 0 its a ladder
print("you found a ladder")
player1pos+= board[player1pos] #find the position its supposed to be at on the board
print("player1 is at position:",player1pos)
print("")
elif board[player1pos] <0: #if the number is negative then its a snake
print("you found a snake")
player1pos+=board[player1pos]
print("player 1 is at position:",player1pos)
print("")
else: #if its just a 0 they stay at that position
print("player1 is at position:",player1pos)
print("")
if 100<=player1pos: #if the player position is 100 or more they win
print("player1 win")
quit()
if you could suggest any other changes that would help too as i need to try and improve it as much as possible :)

You need to reset player1roll equal to NO inside of that if statement.

if the above is your code it appears there is a typo in your code.
player1roll=input("player1 ready to roll??\n").upper
is missing the ending parenthesis so it should be grabbing the function and not the "YES".
EDIT:
in the following code player1roll is used for both player input and the rolling of dice. This causes the die roll to override the acceptance of his turn. If the die roll supposed to be a part of the while loop, then you should create a new variable.
while player1_input != "YES":
player1_input=input("player1 ready to roll??\n").upper
player1roll=random.choice(dice)
print("you rolled a:", player1roll)

When you say "it just keeps repeating "player1 ready to roll?"" is that literally the only output you are seeing? No other output?
You do realize you are setting player1roll to a random element from the the "dice" sequence, right? Does it make sense to use the same variable for the user input and the roll value?
How about changing your variable names?
Change:
while player1roll != "YES":
player1roll=input("player1 ready to roll??\n").upper
To:
while player1in != "YES":
player1in=input("player1 ready to roll??\n").upper

Related

Python random number guessing game

I'm having issues with this random number guessing game. There are 2 issues: The first issue has to do with the counting of how many tries you have left. it should give you 3 changes but after the 2nd one it goes into my replay_input section where I am asking the user if they want to play again.
import random
# guess the # game
guess = input("Enter in your numerical guess. ")
random_number = random.randint(0, 10)
print(random_number) # used to display the # drawn to check if code works
number_of_guess_left = 3
# this is the main loop where the user gets 3 chances to guess the correct number
while number_of_guess_left > 0:
if guess != random_number:
number_of_guess_left -= 1
print(f"The number {guess} was an incorrect guess. and you have {number_of_guess_left} guesses left ")
guess = input("Enter in your numerical guess. ")
elif number_of_guess_left == 0:
print("You lose! You have no more chances left.")
else:
print("You Win! ")
break
The second part has to do with the replay input, I can't seem to get it to loop back to the beginning to restart the game.
replay_input = input("Yes or No ").lower()
if replay_input == "yes":
guess = input("Enter in your numerical guess. ")
The break statement exits a while loop. The code in the loop executes once, hits break at the end, and moves on to execute the code after the loop.
You can have the player replay the game by wrapping it in a function which I've called play_game below. The while True loop at the end (which is outside of play_game) will loop until it encounters a break statement. The player plays a game once every loop. The looping stops when they enter anything other than "yes" at the replay prompt which will make it hit the break statement.
import random
def play_game():
# guess the # game
guess = input("Enter in your numerical guess. ")
random_number = random.randint(0, 10)
print(random_number) # used to display the # drawn to check if code works
number_of_guess_left = 3
# this is the main loop where the user gets 3 chances to guess the correct number
while number_of_guess_left > 0:
if guess != random_number:
number_of_guess_left -= 1
print(f"The number {guess} was an incorrect guess. and you have {number_of_guess_left} guesses left ")
guess = input("Enter in your numerical guess. ")
elif number_of_guess_left == 0:
print("You lose! You have no more chances left.")
else:
print("You Win! ")
while True:
play_game()
replay_input = input("Yes or No ").lower()
if replay_input != "yes":
break
Please focus on the basics first before posting the questions here. Try to debug with tools like https://thonny.org/. However, I updated your code, just check.
import random
# guess the # game
random_number = random.randint(0, 10)
print(random_number)
# don't forget to convert to int
guess = int(input("Enter in your numerical guess. "))
number_of_guess_left = 3
# this is the main loop where the user gets 3 chances to guess the correct number
while number_of_guess_left > 0:
number_of_guess_left -= 1
if guess == random_number:
print("You Win! ")
break
else:
if number_of_guess_left == 0:
print("You lose! You have no more chances left.")
break
else:
print(f"The number {guess} was an incorrect guess. and you have {number_of_guess_left} guesses left ")
guess = int(input("Enter in your numerical guess. "))

How Can I Give the User 5 Lives for my script?

Title.
I'm currently writing a choose your own adventure python script for my computer science class and need to give the player 5 lives and when they run out have a line of text appear. Any ideas?
(I'm not sure if I need to post the script or not but I can later today if needed.)
script:
# Name: Drew Dilley
**# Date: 12/7/20
# 1 REMOVED IMPORT MATH BECAUSE IT IS NOT NEEDED FOR THIS SCRIPT.
# 2
import random
answer: str = input("Do you want to go on an adventure? (Yes/No)")
# hint: the program should convert player's input to lowercase and get rid of any space player enters
# hint: check out what .upper(), .lower(), .strip() do on a string, reference: https://www.w3schools.com/python/python_ref_string.asp
# 3
if answer.upper().strip() == "yes":
# hint: pay attention to the variable name
# 4
ANSWER= input("You are lost in the forest and the path splits. Do you go left or right? (Left/Right) ").lower().strip()
if answer == "left":
# 5 UNNECESSARY INDENT
answer = input("An evil witch tries to cast a spell on you, do you run or attack? (Run/Attack) ").lower().strip()
if answer == "attack": #(HAD TO FIX UNEXPECTED INDENT)
print("She turned you into a green one-legged chicken, you lost!")
# 6 HAD TO ADD PARENTHESES AND FIX THE SEMICOLON AFTER "ANSWER"
elif answer := "run":
print("Wise choice, you made it away safely.")
answer = input("You see a car and a plane. Which would you like to take? (Car/Plane) ").lower().strip()
if answer == "plane":
print("Unfortunately, there is no pilot. You are stuck!")
elif answer == "car":
print("You found your way home. Congrats, you won!")
# 7 SEMICOLON NEEDED AFTER "ELSE" PLANE/ANSWER + CAR/ANSWER NEEDED TO BE FLIPPED. NO INDENTATION NEEDED FOR "ELSE". == INSTEAD OF !=
elif answer != "plane" or answer != "car":
print("You spent too much time deciding...")
elif "right" != answer:
else:
print("You are frozen and can't talk for 100 years...")
# hint: the program should randomly generate a number in between 1 and 3 (including 1 and 3)
# hint: remember random module? reference: https://www.w3schools.com/python/module_random.asp
# 8 HAD TO IMPORT "RANDOM"
num: int = random.randint(0,3)
# 9
answer = input("Pick a number from 1 to 3: ")
# hint: will the following if statement ever be executed even when the values of answer and num are the same? If not, can you fix the problem?
# hint: the error is not necessarily in the line below.
if answer == num:
print("I'm also thinking about {}".format(num))
print("You woke up from this dream.")
else:
print("You fall into deep sand and get swallowed up. You lost!")
else:
print('You can\'t run away...')
# 10 NEEDED A SEMICOLON FOLLOWING THE ELSE STATEMENT, SO THAT IT KNOWS WHAT TO READ AND PERFORM NEXT IN THE SCRIPT.
else:
print ("That's too bad!")** ```
you can use a for loop with a counter variable which you can decriment at every time player looses and when it goes from 5 to zero you can use break to exit the loop or a print before break to display a message.

Why is an elif statement being ignored [duplicate]

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 2 years ago.
I'm writing a program as an exercise for if-elif-else statements and I could do with some advice as to why an elif statement is not running.
I want to give the option to pick up rocks for the inventory.
That works, but if I say I do NOT want to pick up the rocks, that elif statement seems to be ignored and I pick up the rocks and they are added to my inventory.
I have no actual errors, but cannot see why the elif statement is not being actined. I have used this several times in the same program as part of this exercise and not had this continual problem.
These are the statements I seem to be having issues with:
elif num >=2 and rocks_there == True:
print("""You keep within touching distance of the castle wall.
You come across some rocks. Do you want to pick them up.""")
take = input("> ").lower()
if "yes" or "y" in take:
print("You pick up the rocks.")
inventory.append('Rocks')
rocks_there = False
print("You follow the castle walls around to the front of the castle again.")
grounds()
elif "no" or "n" in take:
inventory = inventory
rocks_there = True
print("You leave the rocks on the path.")
print("You follow the castle walls around to the front of the castle.")
grounds()
Here is the whole of the function:
def fog():
global inventory
global rocks_there
print("You walk along the path to the left of the castle when a thick fog starts swirling around you.")
print("Do you want to CARRY on or go BACK to the courtyard?")
choice = input("> ").lower()
if "back" in choice:
grounds()
elif "carry" in choice:
num = random.randint(0,10)
if num < 2:
print("""The fog envelopes you until you have no idea where you are and can see nothing else.
Suddenly you feel yourself fall as you step over the edge of a towering cliff.
You die, but at least you are not undead.""")
exit(0)
elif num >=2 and rocks_there == True:
print("""You keep within touching distance of the castle wall.
You come across some rocks. Do you want to pick them up.""")
take = input("> ").lower()
if "yes" or "y" in take:
print("You pick up the rocks.")
inventory.append('Rocks')
rocks_there = False
print("You follow the castle walls around to the front of the castle again.")
grounds()
elif "no" or "n" in take:
inventory = inventory
rocks_there = True
print("You leave the rocks on the path.")
print("You follow the castle walls around to the front of the castle.")
grounds()
elif num >= 2 and rocks_there == False:
print("You follow the castle walls around to the front of the castle.")
else:
print("The fog has scrambled your brain and I do not understand you.")
print("I hope you find your way out.")
print("Goodbye!")
exit(0)
If you try this simple code
mylist = []
if "yes" or "y" in mylist:
print("oops")
you'll see that the code is interpreted as
mylist = []
if "yes" or ("y" in mylist):
print("oops")
And since
if "yes":
print("oops")
it will always run through the if-part and never through the elif part. That's because "yes" is considered a truthy value.
What you probably wanted is
if take in ["y", "yes"]:
which is "check if the user input (take) is in the list ([]) of possible answers". And similar for the no-part of the statement.

How can I ask the player if they want to replay my Python3 terminal number guessing game? [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 3 years ago.
I have an almost working code for my number guessing game. It runs completely fine up until the very end when asking the player if they want to play again and they type in "yes"--the Terminal outputs this:
Ha ha. You took too many guesses! I win! ^__^
Would you like to play again? (yes/no) yes
I'm thinking of a number between 1 and 99!
Ha ha. You took too many guesses! I win! ^__^
Would you like to play again? (yes/no)
I thought to just put the entire program in a while loop, but I have a few opening questions in the game that should only be asked the first time they run the program, and not every time they want to replay the game. (e.g Whats your name? Do you want to play?) I am not sure how to rerun the program but starting just after those initial questions. With my current code, I am lost at what to write for when the player types in "yes" at the ending to replay the game.
import random
import sys
guesses_taken = 0
number = random.randint(1, 99)
name = input("\nHello, what's your name? ")
print(f"\nNice to meet you, {name}.")
answer = input("Would you like to play a guessing game? (yes/no) ").lower()
while True:
if answer == "no":
print("\nToo bad, goodbye!\n")
sys.exit()
elif answer == "yes":
print(f"\nOkay, let's play!")
break
else:
print("\nSorry, I didn't get that.")
while True:
print("\nI'm thinking of a number between 1 and 99!")
while guesses_taken < 6:
guess = input("Take a guess: ")
guesses_taken += 1
if int(guess) > number:
print("\nYour guess is too high!\n")
elif int(guess) < number:
print("\nYour guess is too low!\n")
else:
print("\nArgh..you guessed my number! You win! -__-")
break
while guesses_taken >= 6:
print("\nHa ha. You took too many guesses! I win! ^__^")
break
again = input("\nWould you like to play again? (yes/no) ")
if again == "no":
break
sys.exit()
The variables guesses_taken & number will both retain their values when replaying, which makes for a not-very-interesting game. You need to do something to change that, like -
again = input("\nWould you like to play again? (yes/no) ")
if again == "no":
break
else:
guesses_taken = 0
number = random.randint(1, 99)
Functions, etc can make the code cleaner, but this is the minimal change you need to make to get things working.

How to break out of while loop in Python?

I have to make this game for my comp class, and I can't figure out how how break out of this loop. See, I have to play against the "computer," by rolling bigger numbers, and seeing who has the bigger score. But I can't figure out how to "break" from my turn, and transition to the computers turn. I need "Q" (quit) to signal the beginning of the computers turn, but I don't know how to do it.
ans=(R)
while True:
print('Your score is so far '+str(myScore)+'.')
print("Would you like to roll or quit?")
ans=input("Roll...")
if ans=='R':
R=random.randint(1, 8)
print("You rolled a "+str(R)+".")
myScore=R+myScore
if ans=='Q':
print("Now I'll see if I can break your score...")
break
A couple of changes mean that only an R or r will roll. Any other character will quit
import random
while True:
print('Your score so far is {}.'.format(myScore))
print("Would you like to roll or quit?")
ans = input("Roll...")
if ans.lower() == 'r':
R = np.random.randint(1, 8)
print("You rolled a {}.".format(R))
myScore = R + myScore
else:
print("Now I'll see if I can break your score...")
break
What I would do is run the loop until the ans is Q
ans=(R)
while not ans=='Q':
print('Your score is so far '+str(myScore)+'.')
print("Would you like to roll or quit?")
ans=input("Roll...")
if ans=='R':
R=random.randint(1, 8)
print("You rolled a "+str(R)+".")
myScore=R+myScore
Don't use while True and break statements. It's bad programming.
Imagine you come to debug someone else's code and you see a while True on line 1 and then have to trawl your way through another 200 lines of code with 15 break statements in it, having to read umpteen lines of code for each one to work out what actually causes it to get to the break. You'd want to kill them...a lot.
The condition that causes a while loop to stop iterating should always be clear from the while loop line of code itself without having to look elsewhere.
Phil has the "correct" solution, as it has a clear end condition right there in the while loop statement itself.
ans=(R)
while True:
print('Your score is so far '+str(myScore)+'.')
print("Would you like to roll or quit?")
ans=input("Roll...")
if ans=='R':
R=random.randint(1, 8)
print("You rolled a "+str(R)+".")
myScore=R+myScore
else:
print("Now I'll see if I can break your score...")
ans = False
break
Walrus operator (assignment expressions added to python 3.8) and while-loop-else-clause can do it more pythonic:
myScore = 0
while ans := input("Roll...").lower() == "r":
# ... do something
else:
print("Now I'll see if I can break your score...")

Categories