New to python and having problems with whiles and ifs - python

My Problem(s):
The problem now is that whenever I enter a number of times to play, it just ignores it and plays forever. It is also not updating the score even though I have global variables and I am adding to them every time there is a win or loss.
Also, I do not want to ask the player(s) for their names every time they play (only when using the "out of a certain number of points function of the game). Any suggestions/help would be greatly appreciated!
My code is below for reference:
from random import randint
import sys
print("Lets play a game!")
dotheywantotplay = input("Do you want to play Rock-Paper-Scissors? (y or n) ")
bestOutOf = int(input("Best out of: (Enter a number 1-10) "))
player1score = 0
player2score = 0
computerscore = 0
class PlayWithFriend:
def __init__(self, player1, player2, name1, name2, player1score, player2score):
self.player1 = player1
self.player2 = player2
self.name1 = name1
self.name2 = name2
self.player1score = player1score
self.player2score = player2score
if player1 == player2:
print("Tie!")
elif player1 == "Rock":
if player2 == "Paper":
print("You Win", name2,"!")
print(player2, "covers", player1)
player2score += 1
print("The score is --> %d: %s vs %d: %s" %(player1score, name1, player2score, name2))
else:
print("You Win", name1,"!")
print(player1, "smashes", player2)
player1score += 1
print("The score is --> %d: %s vs %d: %s" %(player1score, name1, player2score, name2))
elif player1 == "Paper":
if player2 == "Scissors":
print("You Win", name2,"!")
print(player2, "cut", player1)
player2score += 1
print("The score is --> %d: %s vs %d: %s" %(player1score, name1, player2score, name2))
else:
print("You Win", name1,"!")
print(player1, "covers", player2)
player1score += 1
print("The score is --> %d: %s vs %d: %s" %(player1score, name1, player2score, name2))
elif player1 == "Scissors":
if player2 == "Rock":
print("You Win", name2,"!")
print(player2, "smashes", player1)
player2score += 1
print("The score is --> %d: %s vs %d: %s" %(player1score, name1, player2score, name2))
else:
print("You Win", name1,"!")
print(player1, "cut", player2)
player1score += 1
print("The score is --> %d: %s vs %d: %s" %(player1score, name1, player2score, name2))
else:
print("That's not a valid play. Check your spelling!")
class PlayWithComputer:
def __init__(self, player, name, player1score, computerscore):
self.player = player
self.player1score = player1score
self.computerscore = computerscore
self.name = name
t = ["Rock", "Paper", "Scissors"]
computer = t[randint(0,2)]
if player == computer:
print("Tie!")
print("The score is --> %d: %s vs %d: computer" %(player1score, name, player2score))
elif player == "Rock":
if computer == "Paper":
print("You lose!", computer, "covers", player)
computerscore += 1
print("The score is --> %d: %s vs %d: computer" %(player1score, name, player2score))
else:
print("You win!", player, "smashes", computer)
player1score += 1
print("The score is --> %d: %s vs %d: computer" %(player1score, name, player2score))
elif player == "Paper":
if computer == "Scissors":
print("You lose!", computer, "cut", player)
computerscore += 1
print("The score is --> %d: %s vs %d: computer" %(player1score, name, player2score))
else:
print("You win!", player, "covers", computer)
player1score += 1
print("The score is --> %d: %s vs %d: computer" %(player1score, name, player2score))
elif player == "Scissors":
if computer == "Rock":
print("You lose...", computer, "smashes", player)
computerscore += 1
print("The score is --> %d: %s vs %d: computer" %(player1score, name, player2score))
else:
print("You win!", player, "cut", computer)
player1score += 1
print("The score is --> %d: %s vs %d: computer" %(player1score, name, player2score))
else:
print("That's not a valid play. Check your spelling!")
if dotheywantotplay == "y":
PlayWith = input("Do you want to play Rock-Paper-Scissors with computer or a friend? (computer, friend, exit) ")
while PlayWith in ('computer', 'friend', 'exit'):
if PlayWith == "friend":
player1 = input('Enter first players name: ')
player2 = input('Enter second players name: ')
while player1score + player2score < bestOutOf:
personchoice1 = input("First player... Rock, Paper or Scissors? ")
personchoice2 = input("Second player... Rock, Paper or Scissors? ")
PlayWithFriend(personchoice1, personchoice2, player1, player2, player1score, player2score)
elif PlayWith == "computer":
player = input('Enter first players name: ')
while player1score + computerscore < bestOutOf:
personchoice = input("Rock, Paper, Scissors? ")
PlayWithComputer(personchoice, player, player1score, computerscore)
elif PlayWith == "exit":
sys.exit()
else:
print("That's not a valid play. Check your spelling!")
else:
print("I am sad now :-(")
sys.exit()

I went over your code and cleaned it up. I made the formatting, variable names, and processes much more pythonic. You will find it is much easier to use python when you use these best practices, so I recommend you at least look over the code and see what I did. For me, I know this would've been helpful when I started learning python.
from random import choice
def get_result(choice1, choice2):
return {
('paper', 'rock'): dict(win='player 1', action='covers'),
('rock', 'paper'): dict(win='player 2', action='covers'),
('rock', 'scissors'): dict(win='player 1', action='smashes'),
('scissors', 'rock'): dict(win='player 2', action='smashes'),
('scissors', 'paper'): dict(win='player 1', action='cuts'),
('paper', 'scissors'): dict(win='player 2', action='cuts'),
}[(choice1, choice2)] # index this dictionary
def main():
print('Lets play a game!')
if input('Do you want to play Rock-Paper-Scissors? (y or n) ') != 'y':
quit()
num_games = int(input('Best out of: (Enter a number 1-10) '))
num_games = max(min(num_games, 10), 1) # clamp num_games between 1-10
while True: # infinite loop, we can break out or quit when we need
inp = input('Do you want to play Rock-Paper-Scissors with computer or a friend? (computer, friend, exit) ')
if inp == 'exit':
quit()
play_with_computer = inp == 'computer'
name1 = input('Enter first players name: ')
name2 = 'computer' if play_with_computer else input('Enter second players name: ')
score = {name1: 0, name2: 0}
for game_number in range(num_games):
choice1 = input(f'{name1}... rock, paper or scissors? ')
choice2 = choice(['rock', 'paper', 'scissors']) if play_with_computer else input(f'{name2}... rock, paper or scissors? ')
if choice1 == choice2:
print('Tie!')
continue
result = get_result(choice1, choice2)
win_name = name1 if result['win'] == 'player 1' else name2
lose_name = name2 if result['win'] == 'player 1' else name1
score[win_name] += 1
print(f'{win_name} {result["action"]} {lose_name}')
print(f'Game {game_number+1}, the score is {score[name1]} {name1}, {score[name2]} {name2}')
print(name1 if score[name1] > score[name2] else name2, 'wins!')
if __name__ == '__main__': # this just means if the file is run
main()
The main thing I did was get rid of your rock paper scissors logic, (which you repeated twice which is never best practice in programming), and replaced it with a get_result function which returns the winner and action of the moves. I also replaced your if statements that test if the game is against the computer, with a bool play_with_computer. This can be used when getting player 2 name and the second choice, which is all that is really different when playing with a computer. The last thing is your game loop while. Since you never really need to execute any code after this (only reason to exit is to quit), I find it to be cleaner to have an infinite loop while True, and just call quit() if the input is 'exit'.

Okay so the mistake is:
while PlayWith != "computer" or "friend" or "exit":
try this thing:
while PlayWith != "computer" or PlayWith != "friend" or PlayWith != "exit":
And sorry if this does not work

which while loops and if statements are you having trouble with?
Upon first glance, the while statement below will never break the moment a player enters a value besides "computer", "friend" or "exit".
Instead, what you can do is put the process of the game within a function, that is continuously called back when the player enters a value besides the ones aforementioned.
while PlayWith != "computer" or "friend" or "exit":
if PlayWith == "friend":
player1 = input('Enter first players name: ')
player2 = input('Enter second players name: ')
personchoice1 = input("First player... Rock, Paper or Scissors? ")
personchoice2 = input("Second player... Rock, Paper or Scissors? ")
i = 0
while i in range(0, bestOutOf):
if i >= bestOutOf:
sys.exit()
if bestOutOf >= 1 and bestOutOf <= 10:
PlayWithFriend(personchoice1, personchoice2, player1, player2, player1score, player2score)
i += 1
else:
print("Setting default game to: \"best out of three\"")
PlayWithFriend(personchoice1, personchoice2, player1, player2, player1score, player2score)
i = bestOutOf - 3
if PlayWith == "computer":
i = 0
while i in range(0, bestOutOf - 1):
if i >= bestOutOf:
sys.exit()
else:
player = input('Enter first players name: ')
if bestOutOf >= 1 and bestOutOf <= 10:
personchoice = input("Rock, Paper, Scissors? ")
PlayWithComputer(personchoice, player, player1score, computerscore)
else:
personchoice = input("Rock, Paper, Scissors? ")
print("Setting default game to: \"best out of three\"")
PlayWithComputer(personchoice, player, player1score, computerscore)
if PlayWith == "exit":
sys.exit()
elif PlayWith != "exit" or "computer" or "friend":
print("That's not a valid play. Check your spelling!")

Related

How to keep score for player and computer?

This is a rock,paper,scissors game.
import random
options = ("rock", "paper", "scissors") # three options
running = True
score = 0
while running: # continuing the game
player = "" # storing the player's choices
computer = random.choice(options) # computer will choose a random choice from the options
while player not in options: # the player has to choose one of the options, if not, it will still keep on looping
player = input("Enter a choice (rock, paper, scissors): ")
print("Player: " + player) # player(user) vs. computer
print("Computer: " + computer)
if player == computer:
score = 0
print("It's a tie!")
elif player == "rock" and computer == "scissors":
score += 1
print("You win!")
elif player == "paper" and computer == "rock":
score += 1
print("You win!")
elif player == "scissors" and computer == "paper":
score += 1
print("You win!")
else:
score += 1
print("You lose!")
print(score, "for computer")
print(score)
play_again = input("Play again? (y/n): ").lower()
if play_again == "y":
running = True
print("Yes sir!")
else:
running = False
print("Thanks for playing! ")
My goal was trying to keep score for player and computer. If the user wins, they get a point. If the computer wins, they get a point. If its a tie, neither of them gets a point.
The following code shows you three rounds of three games of a simulated user input game with its result. It is your code only slightly changed to count properly the results:
import random
lst_user_input = [
"list faking user input:"
,"scissors"
,"paper"
,"rock"
,"y"
,"scissors"
,"paper"
,"rock"
,"y"
,"scissors"
,"paper"
,"rock"
,"n"
]
options = ("rock", "paper", "scissors") # three options
running = True
computer_score = 0
player_score = 0
round_no = 0
while running: # continuing the game
#player = "" # storing the player's choices
round_no += 1
computer = random.choice(options) # computer will choose a random choice from the options
#while player not in options: # the player has to choose one of the options, if not, it will still keep on looping
# player = input("Enter a choice (rock, paper, scissors): ")
print(round_no)
player = lst_user_input[round_no]
print("Player : " + player) # player(user) vs. computer
print("Computer: " + computer)
if player == computer:
print("It's a tie!")
elif player == "rock" and computer == "scissors":
player_score += 1
print("You win!")
elif player == "paper" and computer == "rock":
player_score += 1
print("You win!")
elif player == "scissors" and computer == "paper":
player_score += 1
print("You win!")
else:
computer_score += 1
print("You lose!")
print("Player score:", player_score)
print("Computer score:", computer_score)
if not round_no % 3: # ask only each 3 rounds
#play_again = input("Play next 3-rounds? (y/n): ").lower()
round_no +=1
play_again = lst_user_input[round_no]
if play_again == "y":
running = True
print("Yes sir!")
else:
running = False
print("Thanks for playing! ")
Here an example of printed output:
1
Player : scissors
Computer: paper
You win!
Player score: 1
Computer score: 0
2
Player : paper
Computer: scissors
You lose!
Player score: 1
Computer score: 1
3
Player : rock
Computer: paper
You lose!
Player score: 1
Computer score: 2
Yes sir!
5
Player : scissors
Computer: paper
You win!
Player score: 2
Computer score: 2
6
Player : paper
Computer: rock
You win!
Player score: 3
Computer score: 2
Thanks for playing!

Issue with keeping the score with loops in rock paper scissors python game

I want to code a rock paper scissors game with a scoring system that allows the user to wish to play again and the score adds on and not restarting to 0.
My code is here: https://pastebin.com/eRqEuwtY (It's also attached on this message)
Your help is appreciated.
import random
score1 = int(0)
score2 = int(0)
def main():
while True:
player = input('What do you choose to play (R, P, S)? ')
computer = random.choice(["R", "P", "S"])
print("You chose", (player), "and the computer chose", (computer))
if computer == player:
print("It's a tie")
print("Score: You =", score1, "Computer =", score2)
if computer == "R" and player == "S":
print("Computer wins")
print("Score: You =", score1, "Computer =", score2 + 1)
if computer == "P" and player == "R":
print("Computer wins")
print("Score: You =", score1, "Computer =", score2 + 1)
if computer == "S" and player == "P":
print("Computer wins")
print("Score: You =", score1, "Computer =", score2 + 1)
if computer == "S" and player == "R":
print("You won")
print("Score: You =", score1 + 1, "Computer =", score2)
if computer == "R" and player == "P":
print("You won")
print("Score: You =", score1 + 1, "Computer =", score2)
if computer == "P" and player == "S":
print("You won")
print("Score: You =", score1 + 1, "Computer =", score2)
play_again = input("Would you like to play again? Y/N ")
if play_again == "Y":
main()
else:
print("You scored", score1, "and the computer scored", score2)
exit()
main()
Your problem is that you print the score + 1 if you win. This does not save the new score to the variable!
Example:
print("You won")
score += 1
print("Score: You =", score1, "Computer =", score2)
Another problem in your code is that you call the main function again every time the user wants to play again. This is endless recursion and will result in an error if you hit the recursion limit. It's better to do it like this:
def main():
play_again = "Y"
while play_again == "Y":
#code...
play_again = input("Would you like to play again? Y/N ")
print("You scored", score1, "and the computer scored", score2)
main()
As Jasper pointed out, you need to save the new score to the respective variable. Here is a rework of your code, including some improvements:
import random
def main():
SYMBOLS = ["R", "P", "S"]
INPUTS_YES = ["Y", "YES", "I LOVE THIS GAME SO MUCH"]
INPUTS_NO = ["N", "NO", "PLZ STOP THIS"]
INPUTS_ALL = INPUTS_YES + INPUTS_NO
keep_playing = True
score_player = 0
score_computer = 0
while keep_playing:
symbol_player = input("What do you choose to play? (R, P, S)").upper()
while not symbol_player in SYMBOLS:
print("invalid input")
symbol_player = input("What do you choose to play? (R, P, S)").upper()
symbol_computer = random.choice(SYMBOLS)
print("You chose ", symbol_player, " and the computer chose ", symbol_computer)
difference = (SYMBOLS.index(symbol_player) - SYMBOLS.index(symbol_computer)) % 3
if difference == 0:
print("It's a tie")
if difference == 1:
score_player += 1
print("You won")
if difference == 2:
score_computer += 1
print("Computer won")
print("Score: You = ", score_player, ", Computer = ", score_computer)
play_again = input("Would you like to play again? Y/N").upper()
while not play_again in INPUTS_ALL:
print("invalid input")
play_again = input("Would you like to play again? Y/N").upper()
if play_again in INPUTS_NO:
keep_playing = False
print("You scored", score_player, "and the computer scored", score_computer)
if __name__ == "__main__":
main()

How to create a Rock, Paper, Scissors program

I'm very new to python and am taking an online class. I'm not very familiar with many functions in python so if you could keep it somewhat basic for me to keep track of, I would really appreciate it. I am trying to make a program that runs Rock, Paper, Scissors with a user but the num_games is not being accepted in the "for i in range". Also, I have run it and found that Scissors can beat Rock (THIS IS ANARCHY!). Can anyone assist me? Thanks in advance!
import random
def comp_turn():
comp_move = random.randint(1,3)
if comp_move == 1:
return "Rock!"
elif comp_move == 2:
return "Paper!"
else:
return "Scissors!"
def main():
num_games = int(input("Enter how many games you would like to play: "))
print "You are going to play " + str(num_games) + " games! Here we go!"
num_wins = 0
for i in range(num_games):
user_move = input("Choose either Rock, Paper or Scissors and enter it: ")
cpu_turn = comp_turn()
print "The computer went with: " + cpu_turn
if user_move == 'Rock' and cpu_turn == 'Scissors':
print "You won! Nice job!"
num_wins +=1
elif user_move == 'Paper' and cpu_turn == 'Rock':
print "You won! Nice job!"
num_wins +=1
elif user_move == 'Scissors' and cpu_turn == 'Paper':
print "You won! Nice job!"
num_wins +=1
elif user_move == cpu_turn:
print "Oh! You tied"
else:
print "Whoops! You lost!"
return num_wins
print main()
This should be what you want:
import random
def comp_turn():
return random.choice(['Rock','Paper','Scissors'])
def main():
num_games = int(input("Enter how many games you would like to play: "))
print("You are going to play " + str(num_games) + " games! Here we go!")
num_wins = 0
for i in range(num_games):
user_move = input("Choose either Rock, Paper or Scissors and enter it: ")
cpu_turn = comp_turn()
print("The computer went with: " + cpu_turn)
if user_move == 'Rock' and cpu_turn == 'Scissors': print("You won! Nice job!"); num_wins +=1
elif user_move == 'Paper' and cpu_turn == 'Rock': print("You won! Nice job!"); num_wins +=1
elif user_move == 'Scissors' and cpu_turn == 'Paper': print("You won! Nice job!"); num_wins +=1
elif user_move == cpu_turn: print("Oh! You tied")
else: print("Whoops! You lost!");
return num_wins
print(main())
Or even Better:
import random
def comp_turn():
return random.choice(['Rock','Paper','Scissors'])
def main():
num_games = int(input("Enter how many games you would like to play: "))
print("You are going to play " + str(num_games) + " games! Here we go!")
num_wins = 0
winning=[('Rock','Scissors'),('Paper','Rock'),('Scissors','Paper')]
for i in range(num_games):
user_move = input("Choose either Rock, Paper or Scissors and enter it: ")
cpu_turn = comp_turn()
print("The computer went with: " + cpu_turn)
if (user_move,cpu_turn) in winning:
print('You won!')
num_wins+=1
elif user_move == cpu_turn:
print('Same')
else:
print('You lost!')
return num_wins
print(main())
And another option that's also good:
import random
def comp_turn():
return random.choice(['Rock','Paper','Scissors'])
def main():
num_games = int(input("Enter how many games you would like to play: "))
print("You are going to play " + str(num_games) + " games! Here we go!")
num_wins = 0
d={}.fromkeys([('Rock','Scissors'),('Paper','Rock'),('Scissors','Paper')],'You Won')
for i in range(num_games):
user_move = input("Choose either Rock, Paper or Scissors and enter it: ")
cpu_turn = comp_turn()
print("The computer went with: " + cpu_turn)
if not user_move == cpu_turn:
print(d.get((user_move,cpu_turn),'You lost!'))
else:
print('Same')
return num_wins
print(main())
Here's what you want:
import random
outcome = random.choice(['Rock', 'Paper', 'Scissors'])
print(outcome)
Have you tried removing the '!' in the comp_turn function? It seems like cpu_turn variable will contain either 'Rock!', 'Scissors!' or 'Paper!' while your if-else condition is looking for either 'Rock', 'Scissors' or 'Paper' without the '!'. So, no matter what the player or cpu chooses, it will go into 'else' in the 'for' loop and the player loses.
This is the edited code:
import random
def comp_turn():
comp_move = random.randint(1,3)
if comp_move == 1: return "Rock"
elif comp_move == 2: return "Paper"
else: return "Scissors"
def main():
num_games = int(input("Enter how many games you would like to play: "))
print("You are going to play " + str(num_games) + " games! Here we go!")
num_wins = 0
for i in range(num_games):
user_move = input("Choose either Rock, Paper or Scissors and enter it: ")
cpu_turn = comp_turn()
print("The computer went with: " + cpu_turn)
if user_move == 'Rock' and cpu_turn == 'Scissors':
print("You won! Nice job!")
num_wins +=1
elif user_move == 'Paper' and cpu_turn == 'Rock':
print("You won! Nice job!")
num_wins +=1
elif user_move == 'Scissors' and cpu_turn == 'Paper':
print("You won! Nice job!")
num_wins +=1
elif user_move == cpu_turn:
print("Oh! You tied")
else: print("Whoops! You lost!")
return num_wins
print(main())
Do note that the player's input is case sensitive too. Hope this helps!

Broken code, need help fixing

This code runs through properly once and then brings the error
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
paper
NameError: name 'paper' is not defined
I need the code to be able to run a game of rock, paper, lizard, spock to run 10 times showing a tally of the scores (as it goes and) at the end of the 10 (or the number of chosen) games.
Here is the code:
import random
numberofgames = raw_input("How many games do you want to play? ")
print "Please choose rock , paper , scissors , lizard, or spock (in lower case please)"
choice = raw_input("What do you choose? ")
player_choice = str(choice)
def name_to_number(name):
if name == "rock":
name = 0
return name
elif name == "spock":
name = 1
return name
elif name == "paper":
name = 2
return name
elif name == "lizard":
name = 3
return name
elif name == "scissors":
name = 4
return name
def number_to_name(number):
if number == 0:
number = "rock"
return number
elif number == 1:
number = "spock"
return number
elif number == 2:
number = "paper"
return number
elif number == 3:
number = "lizard"
return number
elif number == 4:
number = "scissors"
return number
try:
computer_choice = random.randrange(5)
player_number = name_to_number(player_choice)
print "Player choice is: " + player_choice
print "Computer choice is: " + number_to_name(computer_choice)
difference = (int(player_number) - computer_choice) % 5
draws = 0
playerwins = 0
computerwins = 0
if difference in [1, 2]:
print "Player wins!"
playerwins = playerwins + 1
elif difference == 0:
print "Player and computer tie!"
draws = draws + 1
else:
print "Computer wins!"
computerwins = computerwins + 1
print "Wins: " + str(playerwins) + "\n" + "Draws: " + str(draws) + "\n" + "Losses " + str(computerwins)
while playerwins + draws + computerwins <= numberofgames:
name_to_number()
except TypeError:
print "Sorry, please read the directions and type rock, paper, scissors, spock, or lizard in lowercase."
The code you posted raises TypeError: name_to_number() takes exactly 1 argument (0 given) because you call your name_to_number function without an argument.
Btw, here's a simpler version of that function:
name_to_number_dict = dict(rock=0, spock=1, paper=2,lizard=3,scissors=4)
def name_to_number(name):
if name not in name_to_number_dict:
raise ValueError("illegal name")
return name_to_number_dict[name]
Edit:
In fact you don't need such a function at all. A simpler approach might be the following:
import random
data = "rock", "spock", "paper", "lizard", "scissors"
def playgames():
tally = dict(win=0, draw=0, loss=0)
numberofgames = raw_input("How many games do you want to play? ")
numberofgames = int(numberofgames)
for _ in range(numberofgames):
outcome = playgame()
tally[outcome] += 1
print """
Wins: {win}
Draws: {draw}
Losses: {loss}
""".format(**tally)
def playgame():
choice = ""
while (choice not in data):
choice = raw_input("Enter choice (choose rock , paper , scissors , lizard, or spock):")
choice = choice.lower()
print "Player choice is:{}".format(choice)
player_number = data.index(choice)
computer_number = random.randrange(5)
print "Computer choice is: {}".format(data[computer_number])
difference = (player_number - computer_number) % 5
if difference in [1, 2]:
print "Player wins!"
outcome = "win"
elif difference == 0:
print "Player and computer tie!"
outcome = "draw"
else:
print "Computer wins!"
outcome = "win"
return outcome
playgames()

How do I keep score in a rock paper scissors game?

I'm just starting Python and writing a simple rock paper scissors game. Here's what I have so far. I can play a game with another player perfectly. What I want to know is how to keep score of the wins, so if Player 1 wins the first game it would say:
Player 1 = 1
Player 2 = 0
And so on. Also if there's any tips to make my code more efficient (with a nice explanation), that would be nice.
Thanks!
Consider this pseudo-code for suggestions (some parts need to be implemented):
# a Player class. it should have a Name and a Score
class Player():
def __init__(name):
self.name = name
self.score = 0
# displays a prompt and reads in the players name returning a string
def getPlayerName():
# needs code here, see next function for idea of what
pass
# ask the player to make a choice, takes a Player object
# and returns a string
def getPlayerAttack(player):
print "%s, what do you choose?" % player.name
return raw_input("> ")
# determines who wins and updates score accordingly
# takes in the player objects and their attack choices
def attack(player1, choice1, player2, choice2):
if choice1 == choice2:
print "Its's a tie."
elif choice1 == "1" and choice2 == "2":
print "%s wins." % player2
player2.score = player2.score + 1
elif ... # other attacks
# display the scores of the two players
def displayScores(player1, player2):
print "%s vs %s" % (player1.score, player2.score)
player1 = Player(getPlayerName())
player2 = Player(getPlayerName())
while true:
choice1 = getPlayerAttack(player1)
choice2 = getPlayerAttack(player2)
attack(player1, choice1, player2, choice2)
displayScores(player1, player2)
This will need some work, and it's not super-optimal, but it should be a start and should show some more concepts. Use Ctrl-C to stop or add a stop condition (e.g. either player enters "0") -- bugs included for free. :)
Happy coding.
Try this:
player1 = raw_input("Player 1 name: ")
player2 = raw_input("Player 2 name: ")
while(1)
player1score = 0
player2score = 0
print "%s, what do you choose?" % player1
print "1. Rock"
print "2. Paper"
print "3. Scissors"
choice1 = raw_input("> ")
print "%s, what do you choose?" % player2
print "1. Rock"
print "2. Paper"
print "3. Scissors"
choice2 = raw_input("> ")
if choice1 == "1" and choice2 == "1":
print "Its's a tie."
if choice1 == "1" and choice2 == "2":
print "%s wins." % player2
player2score=player2score+1
if choice1 == "2" and choice2 == "1":
print "Player 1 wins." % player1
player1score=player1score+1
if choice1 == "1" and choice2 == "3":
print "Player 1 wins." % player1
player1score=player1score+1
if choice1 == "3" and choice2 == "1":
print "%s2 wins." % player2
player2score=player2score+1
if choice1 == "2" and choice2 == "3":
print "%s wins." % player2
player2score=player2score+1
if choice1 == "3" and choice2 == "2":
print "Player 1 wins." % player1
player1score=player1score+1
print "Player1: %s" % player1score
print "Player2: %s" % player2score
Well there are several ways to make it more efficient, but I have to ask how you are going to play Rock Paper Scissors if you have to type them in one at a time :-P
The scoring could be boiled down to this:
if choice1 == choice2 :
print "Its's a tie."
elif choice1 - choice2 == 1 or choice2 - choice1 == 2 :
print "%s wins." % player1
else:
print "%s wins." % player2
If you want to do multiple games, just put the whole thing inside a while(1): loop, and add a variable for each score. Then it would become:
score1 = 0
score2 = 0
while(1):
<lines 6-18>
if choice1 == choice2 :
print "Its's a tie."
elif choice1 - choice2 == 1 or choice2 - choice1 == 2 :
print "%s wins." % player1
score1 = score1 + 1
else:
print "%s wins." % player2
score2 = score2 + 1
print "%s: %d points. %s: %d points." % (player1, score1, player2, score2)

Categories