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

2024-06-08 00:04:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我是新来这个网站的,所以请容忍我。我需要创建一个石头布剪刀程序,输出每一轮和每一轮的赢家,但有困难的投入。当我运行我的程序(这只是它的一部分)时,计算机能够识别R=石头,P=纸,S=剪刀,但是当R,P,或S在PlayerChoice中输入时,程序不理解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

Tags: 程序gameinput代表computerpaperscissorsrock
2条回答

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

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 + "\"")

不过,我同意普吕恩的回答:你应该用整数来代替字符或字符串,否则你会有一些复杂的逻辑来决定游戏的胜负(布打败石头,石头打败剪刀,剪刀打败布,石头被布打败,剪刀被石头打败,布被剪刀打败)

“理解”是编程的问题。你必须对两个玩家使用相同的表示。这里的问题是,玩家使用的是字符“R”、“P”、“S”,而计算机使用的是整数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是另一面。可以使用模运算“%3”将其映射为0、1、2作为游戏结果

这能让你动起来吗

相关问题 更多 >

    热门问题