Where should I make the modification? - python-3.x

This is a python code for Rock Paper Scissor game, played by the user and computer. The score of the user is the variable and the score of the computer is computer_score which are incremented if the conditions fulfilled. The incrementation is not working as player1_score remains 0 even after winning and computer_score is incrementing every five times the loop runs, even when it is losing.
Here is the whole code:
import random
hand = ["R","P","S"]
def game():
player1_score = 0
computer_score = 0
i=0
while (i<5):
print("Enter R for ROCK \nEnter P for PAPER\nEnter S for SCISOR")
your_hand = input(player1 + " picks: ").upper()
if your_hand not in hand:
continue
computer_hand = random.randint(0,2)
print("Computer picks: ", hand[computer_hand])
if your_hand == "R" and computer_hand == "S":
player1_score += 1
print("Your score: ",str(player1_score) + "\n My score: ", str(computer_score))
elif your_hand == "P" and computer_hand == "R":
player1_score += 1
print("Your score: ",str(player1_score) + "\n My score: ", str(computer_score))
elif your_hand == "S" and computer_hand == "P":
player1_score += 1
print("Your score: ",str(player1_score) + "\n My score: ", str(computer_score))
else:
computer_score += 1
print("Your score: ",str(player1_score) + "\n My score: ", str(computer_score))
i += 1
print("Your score: ",str(player1_score) + "\n My score: ", str(computer_score))
print("\t\t\tWELCOME TO ROCK PAPER SCISORS!")
print("\t\t\tRemember this: \n\t\t\t\t SCISORS KILLS PAPER \n\t\t\t\t PAPER KILLS STONE \n\t\t\t\t STONE KILLS SCISORS")
player1 = input("Player 1 Enter your name: ")
print("Player 2: Hello! " + player1 +". I am your COMPUTER!")
print("SO SHALL WE : \n\t1. PLAY \n\t2. EXIT")
start = int(input("Enter the choice: "))
if start == 1:
game()
else:
exit()
Where should I make the change?

You failed to assign the expected value to computer_hand.
computer_hand = hand[random.randint(0,2)]

If you change both the print statement print("Computer picks: ", hand[computer_hand]) to print("Computer picks: ", computer_hand) and computer_hand = hand[random.randint(0,2)] then it should work.

Related

Number Guessing game Computer Playing

I have created this game. User is giving a number from 1 to 100. Computer is trying to guess it. User is giving hint to computer to go lower or go higher. I am open for any feedback.
Thank you in advance.
import os
import random
os.system('clear')
user = int(input("Please enter a number between 1-100: "))
print("Your Number is: " + str(user))
comp_list = list(range(1,101))
comp_selection = random.choice(comp_list)
count = 0
def game(num, a = 1, b = 100):
global count
print("I have chosen " + str(num) + "\nShould I go Higher or Lower or Correct? ")
user = input("Your Selection: ")
if user == "L":
count = count + 1
low_game(a, num)
elif user == "H":
count = count + 1
high_game(num, b)
else:
print("I have guessed correctly in " + str(count) + " tries")
def low_game(old_low, new_High):
x = new_High
new_comp_list = list(range(old_low, x))
new_comp_selection = random.choice(new_comp_list)
game(new_comp_selection, old_low, x)
def high_game(new_low, old_high):
x = new_low + 1
new_comp_list = list(range(x, old_high))
new_comp_selection = random.choice(new_comp_list)
game(new_comp_selection,x, old_high)
game(comp_selection)
I agree, you have over complicated the game with recursive functons.
Here is a much simplified game with penalties for player who does not answer correctly
or falsifies the answer:)
import sys, random
wins = 0
loss = 0
while 1:
user = input('Please enter a number between 1-100: (return or x = quit) > ' )
if user in [ '', 'x' ]:
break
elif user.isnumeric():
user = int( user )
if user < 1 or user > 100:
sys.stdout.write( 'Number must be between 1 and 100!!\n' )
else:
low, high, count = 1, 100, 0
while 1:
p = random.randint( low, high )
count += 1
while 1:
answer = input( f'Is your number {p}? Y/N > ').upper()
if answer in [ 'Y','N' ]:
break
else:
sys.stderr.write( 'Answer must be Y or N\n' )
if answer == 'N':
if p != user:
if input( f'Is my number (H)igher or (L)ower? > ').upper() == 'H':
if user < p:
high = p - 1
else:
sys.stderr.write( f'Wrong!! Your number was lower. You loss\n' )
loss =+ 1
break
else:
if user > p:
low = p + 1
else:
sys.stderr.write( f'Wrong!! Your number higher. You loss\n' )
loss =+ 1
break
else:
sys.stderr.write( f'Cheat!! Your number is {user}!! You loss\n')
loss =+ 1
break
else:
if user == p:
sys.stdout.write( f'I guessed Correctly in {count} guesses\n' )
wins += 1
else:
sys.stderr.write( f'Cheat!! This is not your number. You loss\n' )
loss =+ 1
break
print( f'Computer won = {wins} : You lost = {loss}' )
Happy coding.
You have really overly complicated the problem. The basic process flow is to have the computer guess a number within a fixed range of possible numbers. If the guess is incorrect, the user tells the computer how to adjust the list by either taking the guessed number as the low end or the high end of the guessing range. So to accomplish this, I would do the following:
from random import randint
# Function to request input and verify input type is valid
def getInput(prompt, respType= None):
while True:
resp = input(prompt)
if respType == str or respType == None:
break
else:
try:
resp = respType(resp)
break
except ValueError:
print('Invalid input, please try again')
return resp
def GuessingGame():
MAX_GUESSES = 10 # Arbritray Fixed Number of Guesses
# The Game Preamble
print('Welcome to the Game\nIn this game you will be asked to provide a number between 1 and 100 inclusive')
print('The Computer will attempt to guess your number in ten or fewer guesses, for each guess you will respond by telling the computer: ')
print('either:\n High - indicating the computer should guess higher\n Low - indicating the computer should guess lower, or')
print(' Yes - indicating the computer guessed correctly.')
# The Game
resp = getInput('Would You Like To Play?, Respond Yes/No ')
while True:
secret_number = None
if resp.lower()[0] == 'n':
return
guess_count = 0
guess_range = [0, 100]
secret_number = getInput('Enter an Integer between 1 and 100 inclusive', respType= int)
print(f'Your secret number is {secret_number}')
while guess_count <= MAX_GUESSES:
guess = randint(guess_range[0], guess_range[1]+1)
guess_count += 1
resp =getInput(f'The computer Guesses {guess} is this correct? (High?Low/Yes) ')
if resp.lower()[0] == 'y':
break
else:
if resp.lower()[0] == 'l':
guess_range[1] = guess - 1
else:
guess_range[0] = guess + 1
if guess == secret_number:
print (f'The Computer has Won by Guessing your secret number {secret_number}')
else:
print(f'The Computer failed to guess your secret number {secret_number}')
resp = getInput('Would You Like To Play Again?, Respond Yes/No ')

Why the "stop" input doesnt stop the hitorstop() and run the code for the condition elif todo == "stop"

import random
class Player:
deck = ["A♣", "2♣", "3♣", "4♣", "5♣", "6♣", "7♣", "8♣", "9♣", "10♣", "J♣", "K♣", "Q♣", "A♦", "2♦", "3♦", "4♦", "5♦",
"6♦", "7♦", "8♦", "9♦", "10♦", "J♦", "K♦", "Q♦", "A♥", "2♥", "3♥", "4♥", "5♥", "6♥", "7♥", "8♥", "9♥",
"10♥", "J♥", "K♥", "Q♥", "A♠", "2♠", "3♠", "4♠", "5♠", "6♠", "7♠", "8♠", "9♠", "10♠", "J♠", "K♠", "Q♠"]
total = 0
run = True
def __init__(self):
self.name = input("Enter your name : ")
self.Bet = inputs.bet(self)
self.Aceval = inputs.Aval(self)
class Dealer:
deck = ["A♣", "2♣", "3♣", "4♣", "5♣", "6♣", "7♣", "8♣", "9♣", "10♣", "J♣", "K♣", "Q♣", "A♦", "2♦", "3♦", "4♦", "5♦",
"6♦", "7♦", "8♦", "9♦", "10♦", "J♦", "K♦", "Q♦", "A♥", "2♥", "3♥", "4♥", "5♥", "6♥", "7♥", "8♥", "9♥",
"10♥", "J♥", "K♥", "Q♥", "A♠", "2♠", "3♠", "4♠", "5♠", "6♠", "7♠", "8♠", "9♠", "10♠", "J♠", "K♠", "Q♠"]
total = 0
class inputs:
def bet(self):
"""
takes in the bet from the user and stores it in the player class
:return: output
"""
self.bet = input("Enter the amount for your bet : ")
output = self.bet
if self.bet.isnumeric() == False:
print("Use your monke brains and enter correct input")
return inputs.bet(self)
else:
return int(output)
def Aval(self):
"""
Takes the value for ace and stores it in the player class
:return: output
"""
self.aval = input("Enter the value for ACE (1 or 10) : ")
output = self.aval
if self.aval.isnumeric() == False:
print("Use your monke brains and enter correct input")
return inputs.Aval(self)
elif self.aval.isnumeric() == True:
if self.aval in ["1", "10"]:
return int(output)
else:
print("I understand you suffer braincell deficiency but I need you to fire up those 2 braincells you have and enter the proper number")
return inputs.Aval(self)
def valcalc(card):
"""
takes the card for player.deck and returns the value of that card
:return: card value
"""
if card[0] in ("K", "Q", "J"):
return 10
elif card[0] == "A":
return p.Aceval
else:
if len(card) > 2:
return int(card[0:2])
else:
return int(card[0])
def hitorstop(todo):
if todo.lower() == ("hit" or "stop"):
if todo.lower() == "hit":
pcard = random.choice(Player.deck)
dcard = random.choice(Dealer.deck)
print("\nYour card is : ", pcard)
Player.deck.remove(pcard)
Dealer.deck.remove(dcard)
p.total += inputs.valcalc(pcard)
d.total += inputs.valcalc(dcard)
print("Your total is : ", p.total)
if p.total > 21:
print("You lost lol")
return
elif d.total > 21:
print("You won , sheeesh")
return
elif (p.total == d.total) == 21:
print("Its a tie")
return
else:
hitorstop(input("\n\nDo you want to hit or stop : "))
else:
if todo.lower() == "stop":
pnum = 21 - p.total
dnum = 21 - d.total
if dnum > pnum:
print(p.name, "wins")
return
elif pnum > dnum:
print("You lost against a dealer bot , such a shame")
return
else:
print("Its a tie , you didnt win shit , lol")
return
else:
hitorstop(input("\n\nDo you want to hit or stop : "))
else:
hitorstop(input("\n\nDo you want to hit or stop : "))
p = Player()
d = Dealer()
pcard = random.choice(Player.deck)
dcard = random.choice(Dealer.deck)
print("\nYour card is : ", pcard)
print("Dealer's card is :" + str(dcard) + "+")
Player.deck.remove(pcard)
Dealer.deck.remove(dcard)
p.total += inputs.valcalc(pcard)
d.total += inputs.valcalc(dcard)
print("Your total is : ", p.total)
hitorstop(input("Do you want to hit or stop : "))
Why does the code below todo == "stop" run when i put in stop as input , it just keeps looping asking for the input again and again if i put "stop" for hitorstop() function
.................................................................................................................................................................................................................................................................................................................................................
You need to replace the line todo.lower() == ("hit" or "stop"): with todo.lower() in ("hit", "stop"): to make it work.
However, this entire condition is redundant in the first place and you can remove it.
You don't need it since you compare the input with "hit" and "stop" later, so it is useless to compare twice.
Here is the replace:
def hitorstop(todo):
if todo.lower() == "hit":
pcard = random.choice(Player.deck)
dcard = random.choice(Dealer.deck)
print("\nYour card is : ", pcard)
Player.deck.remove(pcard)
Dealer.deck.remove(dcard)
p.total += inputs.valcalc(pcard)
d.total += inputs.valcalc(dcard)
print("Your total is : ", p.total)
if p.total > 21:
print("You lost lol")
return
elif d.total > 21:
print("You won , sheeesh")
return
elif (p.total == d.total) == 21:
print("Its a tie")
return
else:
hitorstop(input("\n\nDo you want to hit or stop : "))
elif todo.lower() == "stop":
pnum = 21 - p.total
dnum = 21 - d.total
if dnum > pnum:
print(p.name, "wins")
return
elif pnum > dnum:
print("You lost against a dealer bot , such a shame")
return
else:
print("Its a tie , you didnt win shit , lol")
else:
hitorstop(input("\n\nDo you want to hit or stop : "))

Python 3 number guessing game

I created a simple number guessing game, but every time I don't type in a number the system crashes. Can someone please help!
import random
randNum = random.randint(1, 100)
guesses = 0
for i in range(1, 8):
guesses = guesses + 1
print("hi human guess a number 1-100! \n")
guess = input()
guess = int(guess)
if guess > randNum:
print("your guess is too high")
elif guess < randNum:
print("your guess is too low")
elif guess == randNum:
print("duuude you're a genius \n")
print("you needed " + str(guesses) + " guesses")
I took a quick look at your code and one thing which stands out is that on Line 10, you cast the input to an int without checking if the input is indeed an int.
The system crashes because Python cannot typecast characters to integers when you type cast them. You should explicitly write a condition to check for characters i.e. if the input string is anything except numbers, your code should print something like "Try Again" or "Invalid Input".
import random
randNum = random.randint(1, 100)
guesses = 0
for i in range(1, 8):
guesses = guesses + 1
print("hi human guess a number 1-100! \n")
guess = input()
if guess.isdigit():
if int(guess) > randNum:
print("your guess is too high \n")
elif int(guess) < randNum:
print("your guess is too low \n")
elif int(guess) == randNum:
print("duuude you're a genius \n")
print("you needed " + str(guesses) + " guesses")
else:
print("Invalid Input! Try a number. \n")
Try this code. I hope it helps. And from next time try to upload code instead of images. ;-)
import random
def game():
computer = random.randint(1, 10)
# print(computer)
user = int(input("Please guess a number between 1-10: "))
count = 0
while count < 5:
if computer > user:
count += 1
print("You guessed too low!")
print("You have used " + str(count) + "/5 guesses")
user = int(input("Please guess a number another number!: "))
elif computer < user:
count += 1
print("You guessed too high!")
print("You have used " + str(count) + "/5 guesses")
user = int(input("Please guess a number another number: "))
else:
print("YOU WON!!")
again = input("Would you like to play again?")
if again in["n", "No", "N", "no"]:
break
elif again in["y", "Yes", "Y", "yes"]:
pass
game()
if count == 5:
print("Bummer, nice try...the number was actually " + str(computer) + "!")
again = input("Would you like to play again?")
if again in["n", "No", "N", "no"]:
break
elif again in["y", "Yes", "Y", "yes"]:
pass
game()
else:
print("I'm sorry that's an invalid entry! Restart the game to try again!")
game()

How to stop this while loop?

I'm a beginner in coding and I'm making a simple rpg. I'm currently making a floor with only 4 rooms. I want the game to loop infinitely. I also want the game to prompt the player to enter a valid command when they enter an invalid command, but the while loop repeats infinitely. Can someone give me a fix that a beginner can understand, and maybe some pointers? The while loop is
while foo(move) == False:.
def foo(m):
"""
"""
if m.lower == 'l' or m.lower == 'r' or m.lower == 'help' or m.lower == 'pokemon':
return True
else:
return False
print() #Put storyline here
print("You may input 'help' to display the commands.")
print()
gamePlay = True
floor4 = ['floor 4 room 4', 'floor 4 room 3', 'floor 4 room 2', 'floor 4 room 1']
floor4feature = ['nothing here', 'nothing here', 'stairs going down', 'a Squirtle']
currentRoom = 0
pokemonGot = ['Bulbasaur']
while gamePlay == True:
print("You are on " + floor4[currentRoom] + ". You find " + floor4feature[currentRoom] + ".")
move = input("What would you like to do? ")
while foo(move) == False:
move = input("There's a time and place for everything, but not now! What would you like to do? ")
if move.lower() == 'l':
if currentRoom > 0:
currentRoom = currentRoom - 1
print("Moved to " + floor4[currentRoom] + ".")
else:
print("*Bumping noise* Looks like you can't go that way...")
elif move.lower() == 'r':
if currentRoom < len(floor4) - 1:
currentRoom = currentRoom + 1
print("Moved to " + floor4[currentRoom] + ".")
else:
print("*Bumping noise* Looks like you can't go that way...")
elif move.lower() == 'help':
print("Input 'r' to move right. Input 'l' to move left. Input 'pokemon' to see what Pokemon are on your team. Input 'help' to see the commands again.")
elif move.lower() == 'pokemon':
print("The Pokemon on your team are: " + str(pokemonGot) + ".")
print()
In foo you are comparing a function definition, m.lower, to a character. Try m.lower () to call the function.

Python camel game trouble

I just started learning python using tutorials on a website. One lab had me create this camel game which I know is still incomplete. Right now I am trying to figure out how to print the miles the natives are behind without the number being negative (since this makes no sense). I know there are probably other errors in the code but right now I am focusing on this problem.
Thanks in advance! Here is the code:
import random
print("Welcome to Camel!")
print("You have stolen a camel to make your way across the great Mobi desert.")
print("The natives want their camel back and are chasing you down! Survive your \n"
"desert trek and out run the natives.")
print()
done = False
# VARIABLES
miles_traveled = 0
thirst = 0
tiredness = 0
natives_travel = -20
canteen = 5
forward_natives = random.randrange(0, 10)
full_speed = random.randrange(10, 20)
moderate_speed = random.randrange(5, 12)
oasis = random.randrange(0, 21)
# MAIN PROGRAM LOOP
while not done:
print("A. Drink from your canteen.")
print("B. Ahead moderate speed.")
print("C. Ahead full speed.")
print("D. Stop for the night.")
print("E. Status check.")
print("Q. Quit.")
choice = input("Your choice? ")
print()
if choice.upper() == "Q":
done = True
print("You quit!")
# STATUS CHECK
elif choice.upper() == "E":
print("Miles traveled: ", miles_traveled)
print("Drinks in canteen: ", canteen)
print("The natives are", (natives_travel + 20), "miles behind you.")
print()
# STOP FOR THE NIGHT
elif choice.upper() == "D":
tiredness = 0
print("The camel is happy")
natives_travel = natives_travel + forward_natives
print("The natives are", natives_travel, "miles behind you.")
print()
# FULL SPEED AHEAD
elif choice.upper() == "C":
if oasis == 1:
print("Wow you found an oasis")
canteen = 5
thirst = 0
tiredness = 0
else:
miles_traveled = miles_traveled + full_speed
print("You walked", full_speed, "miles.")
thirst += 1
tiredness = tiredness + random.randrange(1, 4)
natives_travel = natives_travel + forward_natives
print(forward_natives)
print("The natives are", natives_travel, "miles behind you.")
print()
# MODERATE SPEED
elif choice.upper() == "B":
if oasis == 1:
print("Wow you found an oasis")
canteen = 5
thirst = 0
tiredness = 0
else:
miles_traveled = miles_traveled + moderate_speed
print("You walked", moderate_speed, "miles")
thirst += 1
tiredness = tiredness + random.randrange(1, 3)
natives_travel = natives_travel + forward_natives
print("The natives are", natives_travel, "miles behind you.")
print()
# DRINK FROM CANTEEN
elif choice.upper() == "A":
if canteen >= 1:
canteen -= 1
thirst = 0
if canteen == 0:
print("You have no drinks in the canteen!")
print()
if miles_traveled >= 200:
print("You have won!")
done = True
if not done and thirst >= 6:
print("You died of thirst!")
done = True
print()
if not done and thirst >= 4:
print("You are thirsty.")
print()
if not done and tiredness >= 8:
print("Your camel is dead")
done = True
print()
if not done and tiredness >= 5:
print("Your camel is getting tired.")
print()
if natives_travel >= miles_traveled:
print("The natives have caught you!")
done = True
print()
elif natives_travel <= 15:
print("The natives are getting close!")
print()
Use the function abs() for absolute value. Or, if this distance is always negative, just... use a minus sign?

Resources