Rock Paper Scissors In Python
Solution 1:
There's so much wrong with this, it's hard to know where to start (but don't get discouraged)...
First of all, it looks like (mostly from your use of input
vs. raw_input
and your parens with your print statements) you're using Python 3, which already is going to limit the amount of help you get. Most people are still using Python 2.6 or 2.7. But with that out of the way...
The main remaining issues addressing your question are:
First: you're using strings for player input (e.g. '1', '2', '3'), and numbers for computer choice (e.g. 1, 2, 3). So you need to compare them as such. In other words, instead of:
ifcomputer== 1andplay== 2:
You would need to say:
ifcomputer== 1andplay== '2':
Second: you're trying to reference one function's variables in another one, and that won't work. If you want your computer_wins
, etc. variables to be global, you need to initialize them at the global scope, e.g. right after your "#constants" are declared and before you get into main
. Then in any function that uses them, you must say e.g. global computer_wins
to indicate they are global and not local.
Once you get these issues addressed, it should work a bit better, but you'll still need to do a lot of cleanup and keep working on it!
Keep at it, and soon it will be natural for you.
Solution 2:
I answered your question separately, but just for fun here's a little working Rock, Paper, Scissors game to look at. This one is for Python 2.x and probably won't work in Python 3, but it might be helpful for you or somebody in the future searching for this.
# "Rock, Paper, Scissors" demo for Python 2.x# by Dan Kaminsimport random
ROCK = 1
PAPER = 2
SCISSORS = 3
NAMES = { ROCK: 'Rock', PAPER: 'Paper', SCISSORS: 'Scissors' }
WHAT_BEATS_WHAT = { ROCK: SCISSORS, PAPER: ROCK, SCISSORS: PAPER }
WIN_ACTIONS = { ROCK: 'crushes', PAPER: 'smothers', SCISSORS: 'cuts' }
score_player = 0
score_computer = 0
score_ties = 0defmain():
intro()
while main_loop():
pass
summary()
defintro():
print"Welcome to Rock, Paper, Scissors!"defmain_loop():
player = get_player_input()
computer = random.randint(1, 3)
check_result(player, computer)
return ask_play_again()
defcheck_result(player, computer):
global score_player, score_computer, score_ties
if player == computer:
print"Tie! Computer also chose {0}.".format(NAMES[computer])
score_ties += 1else:
if WHAT_BEATS_WHAT[player] == computer:
print"Your massive {0} {1} the computer's {2}!".format(
NAMES[player], WIN_ACTIONS[player], NAMES[computer])
score_player += 1else:
print"The computer's {0} {1} your pathetic {2}!".format(
NAMES[computer], WIN_ACTIONS[computer], NAMES[player])
score_computer += 1defask_play_again():
again = raw_input("Enter Y to play again: ")
return again in ('y', 'Y')
defget_player_input():
whileTrue:
print
player = raw_input("Enter 1 for Rock 2 for paper or 3 for Scissors: ")
try:
player = int(player)
if player in (1,2,3):
return player
except ValueError:
passprint"Please enter a number from 1 to 3."defsummary():
global score_player, score_computer, score_ties
print"Thanks for playing."print"Player won: ", score_player
print"Computer won: ", score_computer
print"Ties: ", score_ties
if __name__ == '__main__':
main()
Solution 3:
A couple quick notes from quickly skimming the code:
In get_score()
you could add an else clause to handle any ties that happen and you wouldn't have to check for it explicitly in play_game()
Move the import random
to the top of the file. imports are generally always found at the top of the file. Also, there's no need to re-import every time you want a random number.
Not sure if this is a typo, cause play
seems to always hold an integer, but you have play == True
and play == False
inside play_game()
. If you want to make play
contain either True
or False
, you need to be using a single equals sign, eg, play = True
. But this doesn't seem to make sense because you're comparing play
to computer
as if they're integers.
Also, what are you trying to accomplish with the score
variable in the get_score()
method?
Ah, if you made the get_score()
method return something so you know who won the match it would be helpful. You can't access computer_wins
or player_wins
inside the get_score()
method because they were defined inside main()
. A simple way to do this is return an int from get_score()
. here is a rather C-style way of handling it (returning -1/0/1). something like (pseudo code):
defget_score():
score = 0if computer wins:
score = -1elif player wins:
score = 1return score
winner = get_score()
if winner == 0:
print'tie game'elif winner == 1print'the player won'else:
print'the computer won'
Solution 4:
Here's another variant that works both in Python 2.x and 3.x:
try: input = raw_input
except NameError: input = input# py3kimport random
import sys
import textwrap
from collections import namedtuple
ROCK, PAPER, SCISSORS = ROCK_PAPER_SCISSORS = range(1, 4)
NAME = dict(zip(ROCK_PAPER_SCISSORS, "Rock Paper Scissors".split()))
Score = namedtuple('Score', 'win verb')
GAME_MATRIX = { # who wins and who does what
(PAPER, ROCK): Score(win=True, verb='covers'),
(SCISSORS, PAPER): Score(win=True, verb='cut'),
(ROCK, SCISSORS): Score(win=True, verb='smashes'),
}
GAME_MATRIX.update(dict(((second, first), Score(not win, verb))
for (first,second), (win,verb) in GAME_MATRIX.items()))
defmain():
# keep scores: how many times computer, player win and number of ties
scores = dict(zip("computer player tie".split(), [0]*3))
display_welcome_message()
# set control loop
keep_going = 'Y'while keep_going.upper() == 'Y':
try: play_game(scores)
except Exception as e:
print("Error: %s" % (e,))
sys.exit(1)
# prompt player to keep going
keep_going = input('Would you like to play again? (Y for Yes): ')
print('\nThe computer won {computer} times\n''The player won {player} times\n''There were {tie} tie scores'.format(**scores))
defplay_game(scores):
# get players choices for this round
computer_choice = random.choice(ROCK_PAPER_SCISSORS)
player_choice = get_player_input()
# print choicesfor player, choice in [('computer', computer_choice),
('player', player_choice)]:
print('The {0} chose: {1} ({2})'.format(player, NAME[choice], choice))
# update scores; print who winsif player_choice == computer_choice:
scores['tie'] += 1print('Tie Score, Please try again')
else:
score = GAME_MATRIX[computer_choice, player_choice]
if score.win: # computer wins
scores['computer'] += 1
template = '{first} {verb} {second}, Computer wins'else: # player wins
scores['player'] += 1
template = '{second} {verb} {first}, Player wins'print(template.format(first=NAME[computer_choice],
second=NAME[player_choice], verb=score.verb))
defdisplay_welcome_message():
print(textwrap.fill(textwrap.dedent("""
Welcome to Rock Paper Scissors, a game of chance to see who
will outsmart the other. This game is Man VS Computer. The
program will select a random integer and then ask you to input
%s for Rock %s for Paper or %s for Scissors. The program will
then tell you who won the game. GOOD LUCK!
""" % tuple(ROCK_PAPER_SCISSORS))))
defget_player_input(ntries=10):
for _ inrange(ntries):
try:
choice = int(input('\nSelect %s for Rock, %s for Paper, or ''%s for Scissors: ' % tuple(ROCK_PAPER_SCISSORS)))
except ValueError:
passelse:
if choice in ROCK_PAPER_SCISSORS:
return choice # successprint('Error: your choice must be one of: %s' % (
', '.join(map(str, ROCK_PAPER_SCISSORS))))
raise RuntimeError('failed to get player choice in %d tries' % ntries)
if __name__=="__main__":
main()
Solution 5:
This code might be a good reference for you. :) Good Luck ! Note that this is Py2.x code
# Author: Niklas Rosenstein# Created: 2011/10/23import sys
import random
PAPER = 0
ROCK = 1
SCISSOR = 2
WIN = 10
LOSS = 11
TIE = 12
TABLE = {
PAPER: 'Paper',
ROCK: 'Rock',
SCISSOR: 'Scissor',
}
if'expand TABLE':
# just for overvieability# expands the TABLE conveniently
tableExpand = [
(PAPER,('paper', 'p', '0')),
(ROCK, ('rock', 'r', 'stone', '1')),
(SCISSOR, ('scissor', 's', '2'))
]
exp = None
key = Nonefor exp in tableExpand:
for key in exp[1]:
TABLE[key] = exp[0]
del tableExpand, exp, key
classGame(object):
wins = 0
losses = 0
ties = 0defevaluateInput(self, inp):
# evaluate the input# raises ValueError if input is invalid# lowercase the string
inp = inp.strip()
inp = inp.lower()
# comparison tabletry:
return TABLE[inp]
except KeyError:
raise ValueError, 'Input is invalid.'defchoose(self, choice):
# make a choice and compare it with# the computers choice# check if the choice is correctif choice notin [ROCK, PAPER, SCISSOR]:
raise ValueError, 'Expected Id of either ROCK, PAPER or SCISSOR'# generate a choice for the computer
com = random.choice([ROCK, PAPER, SCISSOR])
result = choice - com
if result == 0:
self.ties += 1return TIE, com
elif result < 0:
self.wins += 1return WIN, com
else:
self.losses += 1return LOSS, com
TEXT_CHOOSE = 'Choose (or "quit" to quit): '
TEXT_PLAYER_CHOOSE = "You've choosen: "
TEXT_COMPUTER_CHOOSE = 'The computer choosed: '
TEXT_CHOICE_INVALID = 'You choice is invalid.\n'
TEXT_WIN = "You've won this match."
TEXT_LOSS = "You've lost this match."
TEXT_TIE = "This match was tie."
TEXT_GOODBYE = "Thanks for playing."
TEXT_WELCOME = "Welcome to Rock-Paper-Scissor !\n" \
"This game is all about guessing. Try to choose the\n" \
"thing that beats the computers choice. Thereby, the\n" \
"following rules are importan:\n" \
" Paper beats Rock.\n" \
" Rock beats Scissor.\n" \
" Scissor beats Paper.\n" \
"\n" \
"Valid inputs are:\n\n" \
" | for Paper: | p | paper | - | 0 |\n" \
" | for Rock: | r | rock | stone | 1 |\n" \
" | for Scissor: | s | scissor | - | 2 |\n" \
" | To quit the game: | q | quit | - | - |\n" \
"\n" \
"Much fun whishes you: Niklas Rosenstein (2011)\n" \
+ ("-" * 50) + "\n"defprintScores(g):
print"Scores:"print" Wins: %s" % g.wins
print" Losses: %s" % g.losses
print" Ties: %s" % g.ties
defmain():
g = Game()
# play the game ;-)print TEXT_WELCOME
whileTrue:
inp = raw_input(TEXT_CHOOSE)
if inp.lower() in ('q', 'quit'):
breaktry:
inp = g.evaluateInput(inp)
except ValueError:
print TEXT_CHOICE_INVALID
continue
t, com = g.choose(inp)
inp = TABLE[inp]
com = TABLE[com]
print TEXT_PLAYER_CHOOSE, inp
print TEXT_COMPUTER_CHOOSE, com
printif t == WIN:
print inp, "beats", com + ".",
print TEXT_WIN
elif t == LOSS:
print com, "beats", inp + ".",
print TEXT_LOSS
else:
print inp, "euqals", com + ".",
print TEXT_TIE
print
printScores(g)
print"-" * 50printprint TEXT_GOODBYE
printScores(g)
printprint"Press any key to exit."
sys.stdin.read(1)
main()
Post a Comment for "Rock Paper Scissors In Python"