使用变量定义字符串,然后将该变量用作输入

时间:2017-02-06 22:41:43

标签: python python-2.7

我是这个网站的新手,所以请耐心等待我。我需要创建一个石头剪刀程序,输出每一轮和每轮的赢家,但我对输入有困难。当我运行我的程序(这只是它的一部分)时,计算机能够识别R = rock,P = paper和S =剪刀,但是当在PlayerChoice中输入R,P或S时,程序不明白R代表摇滚或P代表纸张等。我该如何解决这个问题?

R='rock'
P='paper'
S='scissors'
RPS=[R,P,S]
Name=input('please enter your name')

while PlayerCounter<3 and CompCounter<3

PlayerChoice=input('choose:rock(R),paper(P),scissors(S)')

CompChoice=RPS[random.randint(0,2)]

print('computer chose ' + str(CompChoice))

这是输出的样本

__________Game  1 __________
choose:rock(R),paper(P),scissors(S) R
computer chose rock
__________Game  1 __________
choose:rock(R),paper(P),scissors(S)P
computer chose rock
__________Game  1 __________
choose:rock(R),paper(P),scissors(S)S
computer chose scissors

2 个答案:

答案 0 :(得分:1)

&#34;理解&#34;是一个编程问题。你必须为两个玩家使用相同的表示。这里的问题是你使用了字符&#39; R&#39; P&#39;&#39; S&#39; S&#39;对于播放器,但计算机的整数为0,1,2。试试这个:

move_dict = {'R': 0, 'P': 1, 'S': 2}
player_num = move_dict[PlayerChoice]
move_diff = CompChoice - player_num
# Now you evaluate move_diff to find out who wins.

我建议您将播放器选项转换为相同的整数集。然后你可以简单地减去两个选项来找出谁赢了:0是平局,1或-2是一方; 2或-1是另一侧。您可以使用模数运算&#34;%3&#34;将其映射为0,1,2作为游戏结果。

这会让你感动吗?

答案 1 :(得分:0)

在这种情况下,使用单个列表来处理播放器和计算机的移动会容易得多。从字符串到字符的转换是不必要的复杂化。

import random

# Establish the potential values from which players can choose
values = ["R", "P", "S"]

chosen = 0
# Don't proceed until the user has provided reasonable input
while chosen == 0:
    # The [0] at the end of this finds the first letter, even if the player inputs something like "rock"
    player_choice = input("Choose rock (R), paper (P), or scissors (S): ").upper()[0]
    if player_choice in values:
        chosen = 1 # Allow the program to proceed

# Choose a random value for the computer
computer_choice = values[random.randint(0, 2)]

# Display the results
print("The computer chose \"" + computer_choice + "\" and the player chose \"" + player_choice + "\"")

但是,我同意Prune的回答:你应该使用整数来代替字符或字符串,否则你将有一些复杂的逻辑来确定游戏的胜利者(纸拍摇滚乐,摇滚乐剪刀,剪刀节拍纸,岩石被纸殴打,剪刀被岩石击打,纸被剪刀殴打。