so the ultimate goal is to run best 2 out of 3 games of rock, paper, scissors, lizard, spock. i haven't added a loop yet or anything like that i'm trying to get the game itself running first but I'm coming across a NameError, it's saying the 'result' variable is undefined.
I've tried returning it but that doesn't appear to be working, but I also maybe don't know what I'm doing?
def number_to_name(number):
if number == 1:
return 'scissors'
elif number == 2:
return 'rock'
elif number == 3:
return 'paper'
elif number == 4:
return 'lizard'
elif number == 5:
return 'spock'
else:
print ("Error: Invalid number")
def name_to_number(name):
if name == 'scissors':
return 1
elif name == 'rock':
return 2
elif name == 'paper':
return 3
elif name == 'lizard':
return 4
elif name == 'spock':
return 5
else:
print ("Error: Invalid number")
def rpsls(name):
player_score, computer_score = (0, 0)
player_input = name_to_number(name)
computer_input = random.randint(1,5)
result = (player_input - computer_input) % 5
if result == 1 or result == 2:
print("player wins")
player_score += 1
print("Player {}, Computer {}". format(player_score, computer_score))
elif result == 3 or result == 4:
game = "computer wins"
computer_score += 1
print("Player {}, Computer {}". format(player_score, computer_score))
elif result == 0:
game = "it's a tie"
print("Player {}, Computer {}". format(player_score, computer_score))
else:
print("error")
rpsls("rock")
rpsls("spock")
rpsls("paper")
rpsls("lizard")
rpsls("scissors")
Your conditions should be inside the rpsls function.Because you result variable is local variable. You can't fetch this variable globally.
> def rpsls(name):
> player_score, computer_score = (0, 0)
> player_input = name_to_number(name)
> computer_input = random.randint(1, 5)
> result = (player_input - computer_input) % 5
>
>
> if result == 1 or result == 2:
> print("player wins")
> player_score += 1
> print("Player {}, Computer {}".format(player_score, computer_score))
>
> elif result == 3 or result == 4:
> game = "computer wins"
> computer_score += 1
> print("Player {}, Computer {}".format(player_score, computer_score))
>
> elif result == 0:
> game = "it's a tie"
> print("Player {}, Computer {}".format(player_score, computer_score))
>
> else:
> print("error")
Your variable result is inside the function rpsls. So the scope of result lies to the function only.
A easy solution would be assign a 0 value to result before the function 'rpsls'
This way your updating a globally defined variable inside the function.
result = 0
def rpsls(name):
#Your code
The best way would be to write a class, have a class level variable result, and put all this code into the class.
First of all, since result is only defined in the function, it is only accessable inside that specific function, unless you choose to use the global method, which I wouldn't recommend.
Second, since you called result before you called the function that actually defines result, even if you use global, it will still not be defined for that specific line.
Related
im new to this python program and was tasked to generate a game or scissors paper stone game in python without the use of a list. i have the function here as:
def getRandomShape():
Shape = random.randint(1, 3)
if Shape == 1:
print('Scissors'.upper())
elif Shape == 2:
print('Stone'.upper())
else:
print('Paper'.upper())
getRandomShape()
but whenever i call for the function, it says its not defined.
the error occurse at the possibleHands section where im unable to call for the function but able to at the bottom for the checkForWinner function call
here's the full program.
import random
print('welcome to scissors paper stone')
cpuScore = 0
playerScore = 0
tieScore = 0
possibleHands = getRandomShape(computerHand)
def getRandomShape(computerHand):
Shape = random.randint(1, 3)
if Shape == 1:
print('Scissors'.upper())
elif Shape == 2:
print('Stone'.upper())
else:
print('Paper'.upper())
def checkForWinner(playerHand, computerHand):
if(playerHand == 'Stone' and computerHand == 'Paper'):
print('you lost')
return 'cpu'
elif(playerHand == 'Stone' and computerHand == 'Scissors'):
print('you won')
return 'player'
elif(playerHand == 'Scissors' and computerHand == 'Paper'):
print('you won')
return 'player'
elif(playerHand == 'Scissors' and computerHand == 'Stone'):
print('you lost')
return 'cpu'
elif(playerHand == 'Paper' and computerHand == 'Scissors'):
print('you lost')
return 'cpu'
elif(playerHand == 'Paper' and computerHand == 'Stone'):
print('you won')
return 'player'
else:
print('its a tie. play again')
return 'tie'
while(playerScore != 3 and cpuScore != 3):
name = input('Please enter your name: ')
while True:
playerHand = (input('Round 1: '+str(name)+ ', please choose a shape:'))
if(playerHand == 'Scissors' or playerHand == 'Paper' or playerHand == 'Stone'):
break
else:
print('invalid input, case sensitive. Try again')
computerHand = random.choice(possibleHands)
print('your Hand: ', playerHand)
print('cpu Hand: ', computerHand)
results = checkForWinner(playerHand, computerHand)
if(results == 'player'):
playerScore += 1
elif(results == 'cpu'):
cpuScore += 1
else:
tieScore += 1
print('your score: ', playerScore, 'CPU: ', cpuScore, 'Ties: ', tieScore)
print('gg game over')
got this from a youtube tutorial
You must declare the function before its usage. On line 8 getRandomShape is called before its definition, so a NameError would occur.
What you can do is to put all the code that is not in a function, other than the import statements inside a main() function. And at the end you add:
if __name__ == ‘__main__’:
main()
When the program is called it would execute the main() function, and it would not matter if you put the function before or after others. The only thing that matters is you only call functions after they are already defined.
You can learn more about it here.
There are many more problems with this code, and this only fixes the NameError
that you are currently facing.
Something is wrong with this code, even though no error has been reported. The program simply skips both while loops. Can someone help me?
def play_game():
#print(logo)
user_cards = []
computer_cards = []
is_game_over = False
for _ in range(2):
user_cards.append(deal_card()) #deal_card() is predifined function
computer_cards.append(deal_card())
user_score = calculate_score(user_cards)
computer_score = calculate_score(computer_cards) #calculate score is predefined function
print(f" Your cards: {user_cards}, current score: {user_score}")
print(f" Computer's first card: {computer_cards[0]}")
if user_score == 0 or computer_score == 0 or user_score > 21:
is_game_over = True
else:
while is_game_over:
user_should_deal = input("Type 'y' to get another card, type 'n' to pass: ")
if user_should_deal == "y":
user_cards.append(deal_card())
else:
is_game_over = True
while computer_score != 0 and computer_score < 17:
computer_cards.append(deal_card())
computer_score = calculate_score(computer_cards)
print(f" Your final hand: {user_cards}, final score: {user_score}")
print(f" Computer's final hand: {computer_cards}, final score: {computer_score}")
print(compare(user_score, computer_score))
while input("Do you want to play a game of Blackjack? Type 'y' or 'n': ") == "y":
clear()
play_game()
You should add a not keyword before your while condition as it's now stating that it will keep running while it's game over, and your variable starts as false so it won't even enter once right now.
Fixed while loop:
while not is_game_over:
user_should_deal = input("Type 'y' to get another card, type 'n' to pass: ")
if user_should_deal == "y":
user_cards.append(deal_card())
else:
is_game_over = True
while computer_score != 0 and computer_score < 17:
computer_cards.append(deal_card())
computer_score = calculate_score(computer_cards)
So I'm currently having some trouble with working out how to basically create a "count" function work within my Rock, Paper, Scissors game. I'm new to Python and this is my first foray into the use of multiple functions to execute game logic. Here's my code...
import random
from random import choice
cpu_score = 0
player_score = 0
# dictionary from which gestures are pulled
gestures = ["rock","paper","scissors"]
n_rounds = int(input("How many rounds would you like to play? "))
while n_rounds % 2 == 0 or n_rounds <= -1:
print("Number of rounds must be an odd number! Select an odd number!")
n_rounds = input("How many rounds?")
break
print("Lets play",n_rounds,"rounds!")
rounds_to_win = ((n_rounds + 1)//2)
rounds_to_win = round(rounds_to_win)
print("You must win",rounds_to_win,"rounds to beat the game!")
def computer_choice():
"""Movement made by the computer"""
comp = random.choice(gestures)
return comp
def player_gesture():
"""Movement by player"""
player = input("Please select, rock, paper or scissors")
if player not in gestures:
print("That's not an option! Please try again.")
player = input("Please select, rock, paper or scissors")
return player
def who_won_round(comp, player):
'''Who is the winner of the round.'''
winner = 0
if ((player == "rock") and (comp == "paper")) or \
((player == "paper") and (comp == "scissors")) or \
((player == "scissors") and (comp == "rock")):
winner = 1
elif ((comp == "rock") and (player == "paper")) or \
((comp == "paper") and (player == "scissors")) or \
((comp == "scissors") and (player == "rock")):
winner = 2
else:
winner = 0
return winner
def win_counter(winner, cpu_score,player_score):
rounds = 1
if winner == 1:
player_score += 1
print("This is round",rounds)
rounds += 1
return player_score
if winner == 2:
cpu_score += 1
print("This is round",rounds)
rounds += 1
return cpu_score
def count_round(winner, player, comp, cpu_score, player_score):
if winner == 0:
print("It's a tie!")
elif winner == 1:
print("The player chose",player)
print("The computer chose",comp)
print("The computer won the round!")
print("The computer has won",cpu_score,"rounds!")
elif winner == 2:
print("The player chose",player)
print("The computer chose",comp)
print("The player won the round!")
print("The player has won",player_score,"rounds!")
def game_structure():
while rounds_to_win < n_rounds:
comp = computer_choice()
player = player_gesture()
winner = who_won_round(comp,player)
win_count = win_counter(winner, cpu_score,player_score)
count = count_round(winner, player, comp, cpu_score, player_score)
game_structure()
Basically I'm having issues returning the variables in order to keep count of the scores of the "number of rounds" and "cpu_score" and "player_score". I prefer to not declare global variables as I realise they can be messy to use, but I'm not quite sure how to avoid this.
If you must avoid the use of global variables, you should take an object oriented approach. That way you can store the variables in the object.
So basically you do something like this:
newgame = mytictactoe()
while True #infinite loop
input("wanna play?")
if input == yes:
newgame.start
else:
break
From what I see, the cpu_score and player_score are never updated. You only have the newest result in win_count, that is not assigned to cpu_score or player_score at anytime. It could be something like:
win_count = win_counter(winner, cpu_score,player_score)
if winner == 1:
cpu_score = win_count
if winner == 2:
player_score = win_count
rounds_to_win = max(player_score, cpu_score)
count_round(winner, player, comp, cpu_score, player_score)
I did not run it, but this modifications should do the trick. There are better ways of doing it; maybe using a list to keep the scores and use winner as the index, or an object approach as someone else said, but I do not want to change too much the code.
Also, bear in mind that the round variable in win_counter does nothing.
as my homework (using codeskulptor.org) I put together a simple Rock-Paper-Scissors-Lizard-Spock 'game' in Python, where hard coded player's guesses were running the programme. Translation from name to number and other way round, random computer choice and printing... everything worked fine.
Then I tried to introduce input so that player gets to type their guess. However, the console prints only the log about wrong input but doesn't launch the rest of the programme if the input is actually correct... Tried various modifications, but I'm stuck... am I missing something obvious? Thanks!
import simplegui
import random
def get_guess(guess):
if guess == "rock":
return 0
elif guess == "Spock":
return 1
elif guess == "paper":
return 2
elif guess == "lizard":
return 3
elif guess == "scissors":
return 4
else:
print "Error guess_to_number:", guess, "is not a rpsls-element"
return
def number_to_name(number):
if number == 0:
return "rock"
elif number == 1:
return "Spock"
elif number == 2:
return "paper"
elif number == 3:
return "lizard"
elif number == 4:
return "scissors"
else:
print "Error number_to_name:", number, "is not in [0, 4]"
return
def rpsls(guess):
print
print "Player chooses", guess
player_number = get_guess(guess)
computer_number = random.randrange(5)
computer_choice = number_to_name(computer_number)
print "Computer chooses", computer_choice
diff_mod = (player_number - computer_number) % 5
if diff_mod == 0:
print "Player and computer tie!"
elif diff_mod == 1 or diff_mod == 2:
print "Player wins!"
else:
print "Computer wins!"
frame = simplegui.create_frame("GUI-based RPSLS", 200, 200)
frame.add_input("Enter guess for RPSLS", get_guess, 200)
frame.start()
I am trying to create a rock paper scissors game that keeps score but when I run this program the score resets each time. What do I need to change so that I can properly keep score?
import random
def rockPaperScissors():
playerScore = 0
computerScore = 0
print ""
p = raw_input("Type 'r' for rock, 'p' for paper or 's' for scissors: ")
choices = ['r', 'p', 's']
c = random.choice(choices)
print ""
print "Your move:", p
print "Computer's move:", c
print ""
if p == c:
print "Tie"
elif p == 'r' and c == 's':
playerScore += 1
print "You win"
elif p == 'p' and c == 'r':
playerScore += 1
print "You win"
elif p == 's' and c == 'p':
playerScore += 1
print "You win"
elif c == 'r' and p == 's':
computerScore += 1
print "You lose"
elif c == 'p' and p == 'r':
computerScore += 1
print "You lose"
elif c == 's' and p == 'p':
computerScore += 1
print "You lose"
else:
print "Try again"
print ""
print "Your score:", str(playerScore)+ ", Computer score:", str(computerScore)
while True:
rockPaperScissors()
You're calling the function in a loop. The first thing the function does is create a local variable for the score. When the function ends, that score is thrown away. It doesn't persist through multiple calls. You should return the new score and assign the new values to counters:
import random
def rockPaperScissors():
playerScore = 0
computerScore = 0
...
return playerScore, computerScore
player = 0
computer = 0
while True:
p, c = rockPaperScissors()
player += p
computer += c
print "Your score:", str(player)+ ", Computer score:", computer
Each time you run the function, you are resetting the scores. Define computerScore and playerScore outside of the function, then it will keep the values even when running the function multiple times. Use global to "import" the global variable into the function scope.
playerScore = 0
computerScore = 0
def rockPaperScissors ():
global playerScore
global computerScore
OTHER CODE