【问题标题】:Optimizing rock, paper, scissors (newbie)优化石头剪刀布(新手)
【发布时间】:2020-10-29 19:17:07
【问题描述】:

我是python的初学者,并试图制作一个石头剪刀布游戏。请检查它并通过缩短代码来帮助我优化或简化代码。

这可能是我编写的第四个程序,所以它可能效率不高。我需要一些关于在哪里可以减少代码长度的反馈。

from random import randint
sc=0 #computer score
sp=0 #player score
inp=False
c=0 #logic variable
t=['rock','paper','scissors']
print("enter 1 for rock\n\t  2 for paper\n\t  3 for scissors")
player=False
while player==False :
    inp=False
    c=3
    computer = t[randint(0, 2)]
    while inp==False:
        inp=input('\n1.rock,2.paper,3.scissors: ')
        if inp=='1':
            player='rock'
        elif inp=='2':
            player= 'paper'
        elif inp=='3':
            player= 'scissors'
        else:
            print("incorrect input!")
            inp=False
    if computer==player:
        print("Computer chose", computer)
        print('tie')
    elif player == 'rock':
        if computer=='paper':
            c=1
        else :
            c=0
    elif player=='paper':
        if computer=='scissors' :
            c=1
        else:
            c=0
    elif player=='scissors':
        if computer=='rock':
            c=1
        else:
            c=0
    else:
        print("that is not a valid input")
        c==2
    if c==1:
        sc+=1
        print("Computer chose", computer)
        print('you lose', computer, 'beats', player)
    elif c==0:
        sp+=1
        print("Computer chose", computer)
        print('you win', player, 'beats', computer)
    p=False
    while p==False:
        p=input('do you want to play again: (y/n) ?')
        if p=="y":
            player=False
        elif p=="n":
            player=True
        else:
            print("incorrect input,please re enter!")
            p=False
print("final score:\ncomputer:",sc,"\nplayer:",sp)
print("the game has ended")

【问题讨论】:

标签: python optimization


【解决方案1】:

你说的地方:

while player==False: #this could be any statement with while (variable)==(true or false)

您可以将其更改为:

while not player:

(如果是while player == True,可以输入while player:) 当您定义所有变量时:

sc=0 
sp=0 
inp=False
c=0 

您可以将其缩减为:

sc = 0, sp = 0, inp = False, c = 0

在 ~61 行你说:

else:
    print("incorrect input,please re enter!")
    p=False

p=False 语句实际上是不需要的,因为如果您选择 y 或 n 以外的其他值,p 永远不会更改。 最后,在 ~44 行,输入:

else:
    print("that is not a valid input")
    c==2

c==2 语句没有将 c 赋值为 2,它会检测 c 是否等于 2。因此,如果要使其工作,则需要将其更改为 c=2

【讨论】:

    猜你喜欢
    • 2015-11-28
    • 1970-01-01
    • 1970-01-01
    • 2021-01-10
    • 2018-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-10
    相关资源
    最近更新 更多