【发布时间】:2015-03-09 00:07:03
【问题描述】:
在我们找到here 的作业中,我们正在创建一个名为 Cowboy, Ninja, Bear 的游戏,它本质上是 Rock, Paper, Scissors。所以我有两个问题。
1.) 如何将 c、n 或 b 分配给程序生成的随机数 1、2 或 3?
2.) 在比较程序的选择和用户的选择时,是否有一种快速简便的方法来确保 N 等于 n 以缩短代码?所以它只需要在 c、b 和 n 之间进行比较,而不是将 C、B 和 N 也扔到循环中?
"""
Author:
Program: cnb.py
Description: A game of Cowboy, Ninja, Bear. Similar to Rock, Paper, Scissors.
The user picks either Ninja, Cowboy, or Bear. The program compares this against
its own randomly generated choice and replys with the rounds outcome. The program
also keeps track of the number of wins, losses, ties, and overall rounds.
"""
import random
random.seed()
counter = 1
winCounter = 0
loseCounter = 0
tieCounter = 0
#Input Rules
print ("Enter:")
print (" 'C' or 'c' for Cowboy")
print (" 'N' or 'n' for Ninja")
print (" 'B' or 'b' for Bear")
print()
#Prompt user for input
print ("Round", counter, "Fight!")
userStr = input("Please enter a weapon: ")
#If user input is not compliant with rules instruct
#user to retry.
if userStr == "q" or userStr == "Q":
print("Game Over!")
if userStr != "N" or userStr != "n" or userStr != "C" or userStr != "c" or userStr != "B" or userStr != "b" or userStr == "q" or userStr == "Q":
print ()
print ("That's not a valid choice!")
userStr = input("Please enter a weapon: ")
#Computer picks Weapon
computer = random.randint(1,3)
#Compare Results and print results
#Win
if userStr == c and computer == c
winCounter = winCounter + 1
print ("You win")
if userStr == n and computer == n
winCounter = winCounter + 1
print ("You win")
if userStr == b and computer == b
winCounter = winCounter + 1
print ("You win")
#Loss
if userStr == c and computer == c
lossCounter = lossCounter + 1
print ("You lose")
if userStr == n and computer == n
lossCounter = lossCounter + 1
print ("You lose")
if userStr == b and computer == b
lossCounter = lossCounter + 1
print ("You lose")
#Tie
if userStr == c and computer == c
tieCounter = tieCounter + 1
print ("You tied")
if userStr == n and computer == n
tieCounter = tieCounter + 1
print ("You tied")
if userStr == b and computer == b
tieCounter = tieCounter + 1
print ("You tied")
#Loop to new round
counter = counter + 1
print()
print ("Round", counter)
userStr = input("Please enter a weapon: ")
【问题讨论】:
-
速记。这总是正确的:
if userStr != "N" or userStr != "n" or userStr != "C" or userStr != "c" or userStr != "B" or userStr != "b" or userStr == "q" or userStr == "Q": -
for 1) 不要生成数字,而是从列表中选择。即
foo = ['c', 'b', 'n'] print(random.choice(foo)) -
for 2) 将用户输入转换为小写,即
s.lower()
标签: python python-3.x random