#python-3.x
#python-3.x
Вопрос:
Мой код не сравнивает два значения для получения правильного результата в игре камень-ножницы-бумага. похоже, что что-то не так со словарем или с тем, как я сравниваю выбор проигрывателя и компьютера. Например, иногда игрок выбирает бумагу, а компьютер выбирает камень, и это дает ничью.
Это мой код на python 3
#Game:
#The player must choose his weapon and 'fight' against the computer
#following the rules above.
#The player can choose between the following: Rock, Scissors, Fire,
#Pencil and Paper.
#Rules: The rock beats the scissors, the scissors beat the fire, the fire
#beats the pencil, the pencil beats the paper and the paper beats the
#rock
#Player1 is the human player
#Player2 is the computer
import random
#The game keeps how many times the player1 has won, lost or tied with the
computer in the variables bellow.
wins = 0
losses = 0
ties = 0
#The game welcomes the player.
print("Welcome to the Rock-Paper-Scissors-Fire-Pencil game!")
#The hierarchy of which weapon beats another is added in a dictionary and
#the choices of the player in a table.
rules = {'rock': {'scissors', 'pencil', 'fire'}, 'scissors': {'paper',
'pencil'}, 'fire': {'pencil', 'paper', 'scissors'}, 'pencil': 'paper',
'paper': 'rock'}
choices = ['rock', 'scissors', 'fire', 'pencil', 'paper']
#The player can play as many times as he/she wants until he/she type
#anything else except yes in the "Do you want to play again?" question.
play_again = "yes"
while play_again == "yes":
player1 = None
while player1 not in choices:
#The player must choose his/her 'weapon'
player1 = input("n PLAYER 1 - Please make a choice
(rock/paper/scissors/fire/pencil):")
#The computer chooses it's 'weapon'.
random_number = random.randint(0,4)
player2 = choises[random_number]
#The game shows the choices of the players.
print (f"nPlayer 1 has chosen {player1}")
print (f"nPlayer 2 has chosen {player2}")
#The game compares the choices of the players and announces if the human
#player won, lost or tied with the computer.
#Then it adds the win, the lost or the tie to the summary of wins, losses
#or ties.
if rules[player2] == player1:
print('Player1 wins the round!')
wins = 1
elif rules[player1] == player2:
print('Player2 wins the round!')
losses = 1
else:
print('The round is a tie!')
ties = 1
#The game asks the player if he/she wants to play again.
play_again = input("nDo you want to play again?:")
#If the player doesn't want to play again, the game prints the results of
#all the rounds of the game and closes.
else:
print(f"The player1 won {wins} times")
print(f"The player1 lost {losses} times")
print(f"The player1 tied {ties} times")
print("n Good Bye")
Ответ №1:
Пара вещей:
1) Сделайте отступ в своих комментариях к коду.
2) rules[player1]
возвращает a set
, почему set
совпадение должно соответствовать отдельному str
человеку?
3) random
можно выбрать случайный элемент для вас.
Смотрите мой код ниже. Я пытался поставить a ##########
перед всеми моими изменениями.
import random
wins, losses, ties = 0, 0, 0
print("Wellcome to the Rock-Paper-Scissors-Fire-Pencil game!")
rules = {'rock': {'scissors', 'pencil', 'fire'}, 'scissors': {'paper',
'pencil'}, 'fire': {'pencil', 'paper', 'scissors'}, 'pencil': 'paper',
'paper': 'rock'}
############ This should be a set not a list (faster look up time)
choices = {'rock', 'scissors', 'fire', 'pencil', 'paper'}
play_again = "yes"
while play_again == "yes":
player1_choice = None
while player1_choice not in choices:
player1_choice = input("n PLAYER 1 - Please make a choice (rock/paper/scissors/fire/pencil):")
######### Random can choose for you.
player2_choice = random.choice(list(choices))
print (f"nPlayer 1 has choosen {player1_choice}")
print (f"nPlayer 2 has choosen {player2_choice}")
########## Don't use ==, use `in` for sets.
if player1_choice in rules[player2_choice]:
print('Player 2 wins the round!')
wins = 1
elif player2_choice in rules[player1_choice]:
print('Player 1 wins the round!')
losses = 1
else:
print('The round is a tie!')
ties = 1
play_again = input("nDo you want to play again?:")
########## Why was there an `else` here?
print(f"The player1 won {wins} times")
print(f"The player1 lost {losses} times")
print(f"The player1 tied {ties} times")
print("n Good Bye")