How to either restart or end a game - python

I am trying to insert code at the end of my game to either restart or end the game. I'm not quite sure what I'm missing here.
This is where I'm at:
print("NIM: The Python Game")
print("Hello! My name is AI (the clever computer). \nIn this game, 2 other players will play against me and each other. \nThe player to go first will randomly choose between 30 and 50 stones in a pile to start the game.")
print("She\He will also be the first to remove the first stones. \nPlayers will then take turns at removing between 1 and 3 stones from the pile until a player removes the final stone. \nThe player to remove the final stone is the winner.")
player1=str(input("\nPlayer 1, what is your name and MIT ID? "))
print("Hello, " + player1.capitalize())
player2=str(input("\nPlayer 2, what is your name and MIT ID? "))
print("Hello, " + player2.capitalize())
player3="The computer"
howMany=0
stonesNumber=0
while True:
stonesNumber=int(input("\nNEW GAME \nHow many stones do you want to start with (between 30 and 50), " + player1.capitalize() + "? "))
if stonesNumber <30:
print("The number must be between 30 and 50!")
elif stonesNumber >50:
print("The number must be between 30 and 50!")
else:
print("The number of stones is ", stonesNumber)
while True:
print("\nIt's your turn, ",player1.capitalize())
while True:
howMany=int(input("How many stones do you want to remove?(from 1 to 3) "))
if howMany in [1,2,3]:
break
print("Enter a number between 1 and 3.")
while howMany>stonesNumber:
print("The entered number is greater than a number of stones remaining.")
howMany=int(input("How many stones do you want to remove?"))
stonesNumber=stonesNumber-(howMany)
print("Numbers of stones left: " + str(stonesNumber))
if stonesNumber==0:
print(player1.capitalize()," wins.")
break
print("\nIt's your turn, ",player2.capitalize())
while True:
howMany=int(input("How many stones do you want to remove?(from 1 to 3) "))
if howMany in [1,2,3]:
break
print("Enter a number between 1 and 3.")
while howMany>stonesNumber:
print("The entered number is greater than a number of stones remaining.")
howMany=int(input("How many stones do you want to remove?"))
stonesNumber=stonesNumber-(howMany)
if stonesNumber==0:
print(player2.capitalize()," wins.")
break
print("Numbers of stones left: " + str(stonesNumber))
print("\nIt's my turn!")
if stonesNumber % 3==0:
howMany=2
else:
howMany=1
stonesNumber=stonesNumber-(howMany)
if howMany == 1:
print("The computer has taken 1 counter")
if howMany == 2:
print("The computer has taken 2 counters")
if stonesNumber==0:
print(player3," wins.")
break
print("Numbers of stones left: " + str(stonesNumber))
print("\nThe game is over!")
answer=str(input("\nDo you want to play again?(y/n)"))
if answer == "y" or "yes":
print("\nRestarting the game")
else:
break
print("\nThanks for playing the game!")

The condition if answer == "y" or "yes": does NOT check if answer equals "y" or equals "yes". Due to semantics of OR-Operator it "transposes" to a piece of code like if "yes":, which is always true. Therefore it will always restart your game.
You will need to change it to that:
if answer == "y" or answer == "yes":

I am assuming the problem you are having now is that you cannot escape the loop regardless of what you answer at the end of the game.
The reason your game can never escape the while loop is because of this line
if answer == "y" or "yes":
Your above if statement is made up of two parts:
if answer == "y" (Evaluates to true or false depending on answer)
if "yes" (Evaluates to true every time)
Since its an OR case, where either the result will be true/false OR true, you will always end up with if answer == "y" or "yes" as true.
Therefore, you will always be stuck in the loop.
As per felix's answer, your solution would be to evaluate if answer == "y" OR answer == "yes" instead

Related

Players are unable to win in my python game, keeps saying value is higher

I have a guessing game where one player sets the number for the other person to guess, and then the other player tries to guess what the number is, and the game says if the number is higher, or lower than their current guess. My code is pretty messy, and overcomplicated since I am new to Python. But it just recently broke, not letting the player wins. When the player should win, it says that the number is higher. Here's my code:
from random import randint
import getpass
# Allows the user to select the range
guessamount = input("How large do you want the range of numbers to pick be?(Limit is 420): ")
if int(guessamount) >= int(420):
guessamount = 420
# Allows player 1 to select the answer for player 2 to guess
answer = getpass.getpass("Player 1 select the answer (The answer will not show up while typing):")
if int(answer) >= int(guessamount):
answer = guessamount
attempts = 5
while attempts != 0:
guess = input("Guess a number between 1-" + str(guessamount) + ": ")
if answer == int(guess):
attempts = 0
else:
attempts -= 1
if int(guess) > int(answer):
print ("You suck at this game. The answer is lower than " + str(guess))
else:
print ("You suck at this game. The answer is higher than " + str(guess))
if answer == int(guess):
print("You won the game! The answer was " + str(answer))
else:
print("You ran out of attempts. The number was " + str(answer))
I fixed it! I changed it so the player inserts the answer instead of it being random. And I forgot to change the numbers to int.
Thanks #jarmod for helping.

Problem with simple dice game using python

I'm new to python so I decided to make a simple dice game using a while loop just to do a simple test of myself. In the game, I use the module random and the method random.randint(1, 6) to print a random integer of any value from "1 to 6", which is evidently how a dice works in real life. But to make this a game, if the integer that is printed is even (random.randint(1, 6) % 2 ==0) then 'you win' is printed. If the integer is odd, then 'you lose' is printed. After this, the console asks if you want to roll the dice again, and if you say yes (not case sensitive hence .lower()) then it rolls again and the loop continues, but if you say anything else the loop breaks.
I thought this is was how it would work, but every now and then, when an even number is rolled, 'you lose' is printed, and the opposite for odd numbers, which is not what I thought I had coded my loop to do. Obviously I'm doing something wrong. Can anyone help?
This is my code:
import random
min = 1
max = 6
roll_again = True
while roll_again:
print(random.randint(min, max))
if random.randint(min, max) % 2 == 0:
print('you win')
else:
print('you lose')
again = input('roll the dice? ').lower()
if again == ('yes'):
continue
else:
print('ok')
break
print(random.randint(min, max))
if random.randint(min, max) % 2 == 0:
print('you win')
Those are two separate calls to randint(), likely producing two different numbers.
Instead, call randint() once and save the result, then use that one result in both places:
roll = random.randint(min, max)
print(roll)
if roll % 2 == 0:
print('you win')
You are generating a random number twice, the number printed isn't the same the number as the one you are checking in the if condition.
You can save the number generated in a variable like this to check if your code is working fine :
import random
min = 1
max = 6
roll_again = True
while roll_again:
number = random.randint(min, max)
print(number)
if number % 2 == 0:
print('you win')
else:
print('you lose')
again = input('roll the dice? ').lower()
if again == ('yes'):
continue
else:
print('ok')
break
You need to assign random number to a variable, right now printed and the other one are different numbers.
import random
min = 1
max = 6
dice = 0
while True:
dice = random.randint(min, max)
print(dice)
if dice % 2 == 0:
print('you win')
else:
print('you lose')
again = input('roll the dice? ').lower()
if again == ('yes'):
continue
else:
print('ok')
break
random.randint(min,max) returns different value every time it is executed. So, the best thing you can do is store the value at the very first execution and check on that stored value for Win or Loss.
You can try this version of code:
import random
while(True):
value = random.randint(1,6)
print(value)
if(value % 2 == 0):
print("You Win!")
else:
print("You Lose!")
again = input("Want to roll Again? Type 'Yes' or 'No'")
if(again.lower() != 'yes'):
break

My while loop won't stop after a condition

I made a dice game and you have 3 goes and, if you don't guess it with the 3 goes, it will show you the number and say you lost but for me it only shows it if you don't guess it in 4 goes.
import random
import time
guess=3
print ("Welcome to the dice game :) ")
print ("You have 3 guess's all together!")
time.sleep(1)
dice=random.randint(1, 6)
option=int(input("Enter a number between 1 and 6: "))
while option != dice and guess > 0:
option=int(input("Wrong try again you still have " + str(guess) + " chances remaining: "))
guess=guess-1
if guess == 0:
print ("You lost")
print ("The number was " + str(dice))
if option == dice:
print ("You win and got it with " + str(guess) + " guess remaining")
and the result is:
Welcome to the dice game :)
You have 3 guess's all together!
Enter a number between 1 and 6: 4
Wrong try again you still have 3 chances remaining: 4
Wrong try again you still have 2 chances remaining: 4
Wrong try again you still have 1 chances remaining: 4
You lost
The number was 2
A cleaner way to write this would be
import random
import time
guesses = 3
print("Welcome to the dice game :) ")
print("You have 3 guesses all together!")
time.sleep(1)
dice = random.randint(1, 6)
while guesses > 0:
option = int(input("Enter a number between 1 and 6: "))
guesses -= 1
if option == dice:
print(f"You win and got it with {guesses} guess(es) remaining")
break
if guesses > 0:
print("Wrong try again you still have {guesses} guess(es) remaining")
else:
print("You lost")
print(f"The number was {dice}")
The loop condition only tracks the number of guesses remaining. If you guess correctly, use an explicit break to exit the loop. The else clause on the loop, then, is only executed if you don't use an explicit break.
You're giving the user an extra chance with this line: option=int(input("Enter a number between 1 and 6: ")). Try declaring guess=2 instead.
Your code clearly grants the initial guess (before the loop), and then three more (within the loop). If you want it to be 3 guesses, then simply reduce your guess counter by 1.

What can I do to fix my simple computer-player game code? Syntax Error

I'm new to Python and I wanted to practice doing loops because I’ve been having the most trouble with them. I decided to make a game where the user will pick a number from 0-100 to see if they can win against the computer.
What I have going right now is only the beginning. The code isn’t finished. But trying out the code I got a Syntax error where the arrow pointed at the colon on the elif function.
How do I fix this? What can I do?
I accept any other additional comments on my code to make it better.
Here’s my code:
import random
min = 0
max = 100
roll_again = "yes"
quit = "no"
players_choice = input()
computer = random.randint
while roll_again == "yes":
print("Pick a number between 1-100: ")
print(players_choice)
if players_choice >= 0:
print("Your number of choice was: ")
print(players_choice)
print("Your number is high.")
if computer >= 0:
print("Computers number is: ")
print(computer)
print("Computers number is high.")
if computer >= players_choice:
print("Computer wins.")
print("You lose.")
print("Would you like to play again? ", +roll_again)
elif:
print(quit)
end
Goal:
Fix computer-player game while learning more about python. Providing additional documentation on where to start would be helpful.
The reason you are getting an error pointing to elif is because elif needs a condition to check. You need to use if elif and else like this:
if a == b:
print('A equals B!')
elif a == c:
print('A equals C!')
else:
print('A equals nothing...')
Also, Python relies on indentation to determine what belongs to what, so make sure you are paying attention to your indents (there is no end).
Your code has more errors after you fix the if statements and indentation, but you should be able to look up help to fix those.
There are a lot of problems with your code. Here is a working version, hope it helps you understand some of the concepts.
If not, feel free to ask
import random
# min and max are names for functions in python. It is better to avoid using
# them for variables
min_value = 0
max_value = 100
# This will loop forever uless something 'breaks' the loop
while True:
# input will print the question, wait for an anwer and put it in the
# 'player' variable (as a string, not a number)
player = input("Pick a number between 1-100: ")
# convert input to a number so we can compare it to the computer's value
player = int(player)
# randint is a function (it needs parentheses to work)
computer = random.randint(min_value, max_value)
# print what player and computer chose
print("Your choice: ", player)
print("Computer's choice: ", computer)
# display the results
if computer >= player:
print("Computer wins. You loose")
else:
print("you win.")
# Determine if user wants to continue playing
choice = raw_input("Would you like to play again? (yes/No) ")
if choice != 'yes':
# if not
break
There are a lot of indentiation issues and the if and elif statements are used incorrectly. Also take a look at how while loops work.
Based on the code you provided here is a working solution, but there are many other ways to implement this.
Here is some helpful tutorials for you on if/else statements as well as other beginner topics:
Python IF...ELIF...ELSE Statements
import random
minval = 0
maxval = 100
roll_again = "yes"
quit_string = "no"
while True:
players_choice = int(input("Pick a number between 1-100:\n"))
computer = random.randint(minval,maxval)
#checks if players choice is between 0 and 100
if players_choice >= 0 and players_choice <= 100:
print("Your number of choice was: ")
print(players_choice)
#otherwise it is out of range
else:
print("Number out of range")
#check if computers random number is in range from 0 to 100
if computer >= 0 and computer <= 100:
print("Computers number is: ")
print(computer)
# if computer's number is greater than players number, computer wins
if computer > players_choice:
print("Computer wins.")
print("You lose.")
#otherwise if players number is higher than computers, you win
elif computer < players_choice:
print("You won.")
#if neither condition is true, it is a tie game
else:
print("Tied game")
#ask user if they want to continue
play_choice = input("Would you like to play again? Type yes or no\n")
#checks text for yes or no use lower method to make sure if they type uppercase it matches string from roll_again or quit_string
if play_choice.lower() == roll_again:
#restarts loop
continue
elif play_choice.lower() == quit_string:
#breaks out of loop-game over
break

Loop never seems to actually loop

print("Welcome to my dice game.")
print("First enter how many sides you would like your dice to have, 4, 6 or 12")
print("Then this program will randomly roll the dice and show a number")
#Introduction explaing what the game will do. Test 1 to see if it worked.
while True:
#starts a while loop so the user can roll the dice as many times as they find necessary
import random
#Imports the random function so the code will be able to randomly select a number
dice = int(input("Enter which dice you would to use,4, 6, or 12? "))
#set a variable for the amount of dice number
if dice == 12:
x = random.randint(1,12)
print("You picked a 12 sided dice. You rolled a " + str(x) + " well done")
#Test 2 see if it does pick a random number for a 12 sided di
elif dice == 6:
x = random.randint(1,6)
print("You picked a 6 sided dice. You rolled a " + str(x) + " well done")
#Test 3 see if it does pick a random number for a 6 sided di
elif dice == 4:
x = random.randint(1,4)
print("You picked a 4 sided dice. You rolled a " + str(x) + " well done")
#Test 4 see if it does pick a random number for a 4 sided di
else:
print("Sorry, pick either 12, 6 or 4")
#Test 5 tells the user that they can only pick 4, 6 or 12 if anything else is entered this error shows
rollAgain = input ("Roll Again? ")
if rollAgain == "no":
rollAgain = False
if rollAgain == "yes":
rollAgain = True
break
print ("Thank you for playing")
#if the user enters anything apart from yes y or Yes. The code ends here.
That is the code i have so far. However the code will never actually go to the beginning of the loop, no matter what i enter the code just displays "Thanks for playing" and ends. Can anyone please tell me where i have went wrong?
First, you should be using raw_input to get the user's selection. (assuming python 2) If you're using python 3 then input is fine and keep reading.
Anyway, it'll still quit when you type yes because you break out of the loop! You should move the break statement into the "no" case so it breaks out when you say you do not want to roll again.
rollAgain = raw_input ("Roll Again? ")
if rollAgain == "no":
break
You don't need to set rollAgain to true or false at all. With the above code, anything other than "no" is assumed to be "yes" but you can add checks for that easily.
The problem is that you break your loop when the user wants to roll the dice again. The loop should break when the player doesn't want to play again so you have to do :
http://pastebin.com/hzC1UwDM

Categories

Resources