【问题标题】:Determining winner in Rock Paper Scissors [python]确定剪刀石头布的获胜者 [python]
【发布时间】:2020-09-06 08:13:35
【问题描述】:

我是 python 的初学者,试图创建一个人类与计算机对战的 RPS 游戏。游戏是这样创建的,它将在多个确定的回合中进行(最好的 3 回合)。平局被视为双方各得一分。

我的问题是设置 while 条件。最初我是这样做的: while (player_count + computer_count) != winning_score : 完成所有回合后游戏结束的地方。但是,在某些情况下,并非所有回合都需要进行,并且已经可以确定获胜者(由于平局,每个玩家都会获得一分)。

如何更改 while 条件,以便当任一玩家获得 winning_score/2 + 1 时,游戏结束?

【问题讨论】:

  • 您好,欢迎来到 StackOverflow!到目前为止,您介意编辑您的帖子并向我们展示您的代码吗?

标签: python while-loop boolean


【解决方案1】:

如果您想从另一个角度了解如何实施游戏(以及如何确定获胜者),我建议您使用以下版本:

import random


options = {1: 'Rock', 2: 'Scissors', 3: 'Paper'}
def play():
    score = [0, 0]
    while not any(wins == 3 for wins in score):
        print(f'SCORE\tUser: {score[0]} - PC: {score[1]}')
        user_selection = int(input('Enter your selection:{}> '.format(
            ''.join([f'\n{n}: {option}\n' for n, option in options.items()]))))
        pc_selection = random.randint(1, 3)
        print(f'{options[user_selection]} vs. {options[pc_selection]}')
        if user_selection in (pc_selection - 1, pc_selection + 2):
            print('User wins')
            score[0] += 1
        elif user_selection == pc_selection:
            print('Draw')
        else:
            print('PC Wins')
            score[1] += 1
        input('\n_____ ENTER TO PROCEED _____')


    winner = 'User' if score[0] == 3 else 'PC'
    print(f'\n{winner} won the match!')


play()

希望您能在这里找到对您的学习过程有用且新的东西。

【讨论】:

  • 您好,感谢您的回复。你的代码中有几行我还没有学过,一旦我获得更多知识,我一定会重新审视这个:)
【解决方案2】:

你好,你可以这样做

winning_count = winning_score/2+1

while(player_count < winning_count) and (computer_count < winning_count):
  ...

一旦玩家获胜或计算机获胜超过获胜次数,它将变为 False 并且循环中断

【讨论】:

  • 啊,是的,所以我必须使用 and。我做了这个:while (player_count and computer_count) &lt; ((int(winning_score)/2)+1)。谢谢
  • 是的,因为您只希望游戏在他们的分数都低于要求的分数时继续进行
猜你喜欢
  • 1970-01-01
  • 2018-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-10
  • 1970-01-01
相关资源
最近更新 更多