python - 石头、剪刀、布 - 平局时如何开始新游戏

标签 python python-3.x

我对 Python 编码非常陌生,而且由于我只是基础知识,所以每个代码实际上都是一个充满困惑代码的巨大块。我现在想做的是一个石头剪刀布蜥蜴斯波克游戏,稍后会转变成一个视觉游戏,希望能成为我手机上的一个基本应用程序,以提高我的学习能力,无论如何,这是代码。

我想做的是,当玩家和计算机打平时,询问用户是否想再次玩,我无法正确弄清楚,我将不胜感激任何帮助。

import random

computerChoice = random.randint(1,5)
playerChoosing = True
answer = True

if computerChoice == 1:
    computerChoice = "rock"
elif computerChoice == 2:
    computerChoice = "paper"
elif computerChoice == 3:
    computerChoice = "scissors"
elif computerChoice == 4:
    computerChoice = "spock"
elif computerChoice == 5:
    computerChoice = "lizard"

while playerChoosing == True:
    print("rock, paper, scissors, lizard, spock, What do you choose?")
    playerChoice = input()
    if playerChoice == "rock":
        print("you chose rock")
        playerChoosing = False
    elif playerChoice == "paper":
        print("you chose paper!")
        playerChoice = "paper"
        playerChoosing = False
    elif playerChoice == "scissors":
        print("you chose scissors!")
    playerChoice = "scissors"
    playerChoosing = False
elif playerChoice == "lizard":
    print("you chose lizard!")
    playerChoice = "lizard"
    playerChoosing = False
elif playerChoice == "spock":
    print("you chose spock!")
    playerChoice = "spock"
    playerChoosing = False
else:
    print("this is not an option, please try again")
    playerChoosing = True

input()

print("The computer chose: " +computerChoice+ "!")

input()
#lose


while answer == True:
    if playerChoice == "rock" and computerChoice == "paper":
        print("you lose!, the rock was covered by the paper!")   
    elif playerChoice == "paper" and computerChoice == "scissors":
        print("you lose!, scissors cut the paper in half")    
    elif playerChoice == "scissors" and computerChoice == "rock":
        print("you lose!, rock crushed the scissors")    
    elif playerChoice == "spock" and computerChoice == "lizard":
        print("you lose!, lizard poisons spock")    
    elif playerChoice == "scissors" and computerChoice == "spock":
        print("you lose!, spock smashes scissors")    
    elif playerChoice == "rock" and computerChoice == "spock":
        print("you lose!, spock vaporizes the rock")   
    elif playerChoice == "paper" and computerChoice == "lizard":
        print("you lose!, lizard eats paper")    
    elif playerChoice == "lizard" and computerChoice == "rock":
        print("you lose!, rock crushes lizard")    
    elif playerChoice == "lizard" and computerChoice == "scissors":
        print("you lose!, scissors kills lizard")    
    elif playerChoice == "spock" and computerChoice == "paper":
        print("you lose!, paper disproves spock")
#win   
elif playerChoice == "paper" and computerChoice == "rock":
    print("you win!, the rock was covered by the paper!")    
elif playerChoice == "scissors" and computerChoice == "paper":
    print("you win!, scissors cut the paper in half!") 
elif playerChoice == "rock" and computerChoice == "scissors":
    print("you win!, rock crushed the scissors!")    
elif playerChoice == "lizard" and computerChoice == "spock":
    print("you win!, lizard poisons spock!")   
elif playerChoice == "spock" and computerChoice == "scissors":
    print("you win!, spock smashes scissors!")   
elif playerChoice == "lizard" and computerChoice == "paper":
    print("you win!, lizard eats paper!")   
elif playerChoice == "rock" and computerChoice == "lizard":
    print("you win!, rock crushes lizard!") 
elif playerChoice == "scissors" and computerChoice == "lizard":
    print("you win!, scissors kills lizard!")  
elif playerChoice == "paper" and computerChoice == "spock":
    print("you win!, paper disproves spock!")
elif playerChoice == "spock" and computerChoice == "rock":
    print("you win!, spock vaporizes rock!")
#draw
elif playerChoice == "paper" and computerChoice == "paper":
    print("It's a draw, want to try again?, please type YES or NO: ")
    answer = input()
    if answer == "yes":
        answer = False
    else:
        break
elif playerChoice == "rock" and computerChoice == "rock":
    print("It's a draw, want to try again?, please type YES or NO: ")
    answer = input()
    if answer == "yes":
        answer = False
    else:
        break
elif playerChoice == "scissors" and computerChoice == "scissors":
    print("It's a draw, want to try again?, please type YES or NO: ")
    answer = input()
    if answer == "yes":
        answer = False
    else:
        break
elif playerChoice == "lizard" and computerChoice == "lizard":
    print("It's a draw, want to try again?, please type YES or NO: ")
    answer = input()

elif playerChoice == "spock" and computerChoice == "spock":
    print("It's a draw, want to try again?, please type YES or NO: ")
    answer = input()

最佳答案

您需要将代码包装在名为 play() 或类似名称的函数定义中。然后接近尾声:

answer = True

def play():
    # your code

    if playerChoice == computerChoice: 
        print "It's a draw, want to try again?, please type YES or NO: "
        # use a dictionary to convert; default answer is False
        answer = {'YES' : True, 'NO' : False}.get(input(), False)

if answer:
    play()

这一切都深深 Root 于Control Flow的想法。 。许多语言(包括 Python)都提供函数、类、模块、if-else 和其他控制结构,允许您控制代码的移动方向。其中许多结构还可以帮助您组织代码。

如果您的代码输出只需平局,那么您可以使用更高级的结构来获得去掉你的 if-else 语句。在我看来,它接近您的情况的最佳实现,但是当它没有包装在函数中时它非常丑陋。


这是使用 python 内置函数解决问题的另一种方法:

import random

newgame = True
choosing = False

playerchoice = ''
computerchoice = ''

options = ['rock', 'scissors', 'paper', 'lizard', 'spock']

def play():
    global choosing, computerchoice, computerchoice, newgame
    choosing = True

    while choosing == True: # or while choosing 
        choose()

    result = get_result(playerchoice, computerchoice)

    if result[0] == 'Draw':
        print "It's a draw, want to try again?", "Please type YES or NO:"

        # convert input into uppercase string, use dictionary to convert to boolean
        # default to False
        newgame = {'YES' : True, 'NO' : False}.get(str(input()).upper(), False)
        return # leave function back into 'while newgame' loop
    else:
        # fun code that converts the first value into the win/lose string, and combines it with the outcome of the round
        # join uses the string ', ' in between the two things we print
        values = [{True : 'You win!', False : 'You lose!'}[result[0]], result[1]]
        string = ', '.join(values)
        print string

def choose():
    global playerchoice, choosing, computerchoice

    print "rock, paper, scissors, lizard, spock. What do you choose?"
    playerchoice = input()

    if playerchoice in options: # if playerchoice == any option
        print 'you chose', playerchoice

        computerchoice = options[random.randint(0,4)] # take advantage of list indexes
        print 'computer chose', computerchoice

        choosing = False
    else: 
        print "this is not an option, please try again"

def get_result(playerchoice, computerchoice):
    results = {
               'rock' : {
                         'rock' : ('Draw',),
                         'paper' : (False, 'paper covers rock!'),
                         'scissors' : (True, 'rock crushes scissors!'),
                         'lizard' : (True, 'rock crushes lizard!'),
                         'spock' : (False, 'spock vaporizes rock!')
                        },
               'paper' : {
                          'rock' : (True, 'paper covers rock!'),
                          'paper' : ('Draw',),
                          'scissors' : (False, 'scissors cut paper!'),
                          'lizard' : (False, 'lizard eats paper!'),
                          'spock' : (True, 'paper disproves spock!')
                         },
               'scissors' : {
                             'rock' : (False, 'rock crushes scissors!'),
                             'paper' : (True, 'scissors cut paper!'),
                             'scissors' : ('Draw',),
                             'lizard' : (True, 'scissors kills lizard!'),
                             'spock' : (False, 'spock smashes scissors!')
                            },
               'lizard' : {
                           'rock' : (False, 'rock crushes lizard!'),
                           'paper' : (True, 'lizard eats paper!'),
                           'scissors' : (False, 'scissors kills lizard!'),
                           'lizard' : ('Draw',),
                           'spock' : (True, 'lizard poisons spock!')
                          },
               'spock' : {
                          'rock' : (True, 'spock vaporizes rock!'),
                          'paper' : (False, 'paper disproves spock!'),
                          'scissors' : (True, 'spock smashes scissors!'),
                          'lizard' : (False, 'lizard poisons spock!'),
                          'spock' : ('Draw',)
                         },
               }
    return results[playerchoice][computerchoice]

while newgame == True:
    play()

Python 有一些非常强大的内置类型和函数,所以我故意在上面的代码中使用它们,甚至达到了荒谬的程度。希望您能够查看代码并找到有关 Python 的新知识。

如果使用得当,if/else 就足够了,但我希望我已经演示了 Python 简化复杂代码的一些强大方法。像使用字典进行转换这样的小事情对于保持代码简洁非常有用。它们会带来轻微的性能开销,但如果您使用 Python,执行速度通常不是优先考虑的事项。

编辑:避免使用全局变量,因为如果您忘记 global 关键字,它们会很难调试 ^^;另一种常见的调试困难是,当您有一个只有一个元素 ('Draw') 的元组时,却忘记通过添加逗号来告诉 python 它是一个元组...

关于python - 石头、剪刀、布 - 平局时如何开始新游戏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36610889/

相关文章:

python - 如何将线和列等分

python - 为什么Python函数: type ("This is a string' ) - return no results in the PyCharm IDE,但在IDLE和其他编辑器中返回<class 'str'>?

Python 正则表达式 : Get only one expression to match

python - 如何在 django 中使用验证器

Python unicode 转义下划线和双引号

python-3.x - 如何使用tensorflow的one-hot编码正确编码标签?

python - 导入json并将所有列转换为字符串

python - 如何在客户环境中运行 python 生产

python - pyad:安装正常,但说找不到 adbase

python - 从 .pdf 中提取特定数据并保存在 Excel 文件中