我对编程很陌生,刚刚开始制作摇滚,纸张,剪刀游戏。但是我挂断了为一个物体分配randint,我做了一个大胆的评论,我遇到了问题。我假设当我一直调用计算机= randint(0,2)时,它每次都会改变计算机,那么我该如何解决呢?对不起,如果这是一个愚蠢的问题。
import random
from random import randint
import time
import sys
def choice():
print("Rock, paper, scissors, or quit?")
answer = input('> ').lower()
if answer in('rock'):
print("\nYou have chosen {}".format(answer))
elif answer in('paper'):
print("\nYou have chosen {}".format(answer))
elif answer in('scissors'):
print("\nYou have chosen {}".format(answer))
elif answer in('quit'):
sys.exit(0)
else:
print("Could not recognize your answer. Please try again.")
choice()
print("Rock")
time.sleep(0.5)
print("Paper")
time.sleep(0.5)
print("Scissors")
time.sleep(0.5)
options = ('Rock', 'Paper', 'Scissors')*3
print("\nI have chosen: " + random.choice(options))
print('\n')
new_answer = answer
#THIS IS WHERE IM HAVING TROUBLE ASSIGNING OBJECT TO THE RANDINT
computer = randint(0,2)
if new_answer == 'rock':
if computer == 0: #paper
print("1")
elif computer == 1: #scissors
print("2")
elif computer == 2: #
print("3")
if new_answer == 'paper':
if computer == 0: #
print("Paper covers rock. You win.")
elif computer == 1:
print("It's a draw. We suck.")
elif computer == 2:
print("Scissors cuts paper. I win")
if new_answer == 'scissors':
if computer == 0:
print("Rock crushes scissors. I win.")
if computer == 1:
print("Scissors cut paper. You win.")
if computer == 2:
print("It's a draw. We suck.")
答案 0 :(得分:2)
print("\nI have chosen: " + random.choice(options))
#...
computer = randint(0,2)
您正在让计算机选择两次。您应该选择(随机)一次,将结果分配给变量,然后然后打印它。
只要将函数调用的值赋给变量(如computer = randint(0,2)
),变量(computer
)的值就不会改变,除非再次分配给它。
还有几点评论:
wnnmaw
,您不需要导入random
exit
导入sys
,它本机可用time.sleep
list.index
in
来代替==
运营商in
('Rock', 'Paper', 'Scissors')*3
:这会创建一个包含9个元素的元组,这可能不是您想要的new_answer
变量似乎是多余的%
)以下是考虑这些提示的重写版本:
from random import choice
from time import sleep
CHOICES=('rock','paper','scissors')
def print_animation():
print("Rock")
sleep(0.5)
print("Paper")
sleep(0.5)
print("Scissors")
sleep(0.5)
def rock_paper_scissors():
while(True):
print("Rock, paper, scissors, or quit?")
answer = input('> ').lower()
if answer in CHOICES:
print("\nYou have chosen {}\n".format(answer))
break
elif answer=='quit':
sys.exit(0)
else:
print("Could not recognize your answer. Please try again.")
print_animation()
computer= choice(CHOICES)
print("\nI have chosen: " + computer + "\n")
player_answer_index= CHOICES.index(answer)
computer_answer_index= CHOICES.index(computer)
if player_answer_index==computer_answer_index:
print("draw")
elif (player_answer_index+1)%3==computer_answer_index:
print("computer wins")
else:
print("player wins")
rock_paper_scissors()