python - 存储用户输入的 Python 3 Rock Paper Scissors 使其更具挑战性
问题描述
我正在 Python 3 中研究 Rock、Paper、Scissors。我需要帮助来尝试实现计算机跟踪用户选择的位置,以便它可以判断玩家喜欢什么并比玩家更有优势。我也让计算机使用整数随机选择,但我需要让玩家选择小写的“r”“p”“s”和“q”来退出,以便它可以检查无效条目并显示消息并再次询问。我不想为播放器使用整数。这是我所拥有的:
import os
import random
import time
#global variable
#0 is a placeholder and will not be used
choices = [0, 'rock', 'paper', 'scissors']
player_wins = 0
computer_wins = 0
tie_count = 0
round_number = 1
keep_playing = True
# sets cls() to clear screen
def cls():
os.system('cls' if os.name == 'nt' else 'clear')
# function to display stats
def stats():
print("Current Statistics:")
print("Player Wins: {}".format(player_wins))
print("Computer Wins: {}".format(computer_wins))
print("Tied Games: {}\n".format(tie_count))
# function to check outcome
def game_outcome(player, computer):
#this makes the variables global, else you'll get error
global player_wins, tie_count, computer_wins
if computer == player:
print("It's a tie!\n\n")
tie_count += 1 # incraments tie
# checks all possible win conditions for player. and if met, declares player a winner. If not, declares compute the winner.
elif (player == "rock" and computer == "scissors") or (player == "paper" and computer == "rock") or (player == "scissors" and computer == "paper"):
print("Player wins\n\n")
player_wins += 1 # incraments player's wins
else:
print("Computer wins!\n\n")
computer_wins += 1 # incraments computer's wins
# clears screen
cls()
print("Let's play Rock Paper Scissors!")
# 3-second time out before clearing and asking for input
time.sleep(3)
while keep_playing == True:
# make computer choice random from defined list. Only selects a range of 1-3 ignoring the "0" placeholder
# this is because the user selects a number, instead of typing the weapon, and that number pulls the weapon from the list
computer = random.choice(choices[1:4])
cls()
# prints starting of round and shows stats
print("+++++++++++++[Starting Round {}]+++++++++++++\n".format(round_number))
stats()
# ask for player input
player = input("What is your choice?\n(1) Rock\n(2) Paper\n(3) Scissors?\n\nEnter the number before the weapon of choice:")
player = choices[int(player)]
cls()
print("\n\nThe player's choice: [{}]\n".format(player))
print("The computer's choice: [{}]\n\n".format(computer))
game_outcome(player, computer)
round_number += 1
# ask if player wants to play again. If not, stop
play_again = input('Would you like to play again [y/n]? ')
if play_again.lower() == 'n':
break
print("Thanks for playing!")
解决方案
尝试使用字典:
# put this with the imports at the top
import sys
# replace `choices` at the top
choices = {'r': 'rock', 'p': 'paper', 's': 'scissors', 'q': 'quit'}
# get computer choice
# replaces `computer = random.choice(choices[1:4])`
computer = random.choice(['rock', 'paper', 'scissors'])
# ask for player input
# replace these two lines of code:
# player = input("What is your choice?\n(1) Rock\n(2) Paper\n(3) Scissors?\n\nEnter the number before the weapon of choice:")
# player = choices[int(player)]
while True:
try:
player = choices[input("What is your choice?\n(r) Rock\n(p) Paper\n(s) Scissors?\n(q) to quit.\n\nEnter the letter before the weapon of choice: ")]
if player == 'quit':
sys.exit(0)
break
except KeyError:
print('Please try again.')
推荐阅读
- javascript - 刷新网页时Firebase当前用户未定义
- php - Laravel code in HasAttributes-Trait nonsense?
- angular - “需要电子邮件”验证在 Angular5 的引导电子邮件框中不起作用
- javascript - org.springframework.web.multipart.MultipartException
- google-cloud-platform - 检索用户组映射列表的等效 gcloud API 是什么?
- php - 如何从将 JSON 结果返回到 ajax 的 PHP 脚本启动会话
- regex - 如何在正则表达式 perl 中不匹配字符串末尾的特定数字?
- c# - 从代码中发送鼠标左键单击处理程序?
- spring-data-jpa - 在 JPA Data Spring 中使用本机 SQL 计数返回 0
- c++ - 如何仅绘制 QPolarChart 的一部分?