因此,我现在正在高中上编程课程,并且正在编写由我们分配给我们所有人的老师制作的游戏程序。该游戏称为“棒子游戏”(如果您希望更好地了解游戏的运行原理,请跳过此视频https://www.youtube.com/watch?v=dUXW3Kh_kxo&t=280s的一半)。基本上,我们桌上有15条,您可以拿走1、2或3条。我有一个适用于该游戏的代码,但它说我在进行任何动作时都非法移走了5条木棍。我找不到问题,希望其他人也可以。
pl1 = input("Player 1, what is your username?") #player 1
pl2 = input("Player 2, what is your username?") #player 2
turnsa = 0 #player1 turns
turnsb = 0 #player2 turns
x = 15 #number of sticks
whichplayer = 1
while(x != 1):
while(whichplayer == 1):
P1 = int(input(pl1 + ', choose an amount of sticks from 1-3 ' + str(x) +
' sticks remaining'))
if P1 < x and P1 < 4: # check for legal move
x = x - P1
turnsa = turnsa + 1
whichplayer = 2 #ending loop to start player 2 turn
if P1 > 3 or P1 > x: #check for illegal move
print('illegal move')
continue #restarting player 1 loop
while(whichplayer == 2):
P2 = int(input(pl2 + ', choose an amount of sticks from 1-3 ' + str(x) +
' sticks remaining'))
if P2 < x and P2 < 4:
x = x - P2
turnsb = turnsb + 1
whichplayer = 1
if P2 > 3 or P2 > x:
print('illegal move')
continue
if turnsa > turnsb:
print('congrats ' + pl1 + ' you win')
if turnsb > turnsa:
print('congrats ' + pl2 + ' you win')
答案 0 :(得分:2)
您要在第一个x
语句中减少if
,然后在第二个if
检查P1 > x
时,这是正确的,因为您从{{ 1}}到x
,而5
是2
。您可以在此处使用P1
,因为如果移动无效,那么您已经知道它将是无效的移动。另外,您还有一些边缘情况需要与您的3
,if/else
和>
比较进行检查(尝试每转3支,看看会发生什么情况)。我将把剩下的工作留给您解决,因为这是学校的工作,将是一次很好的学习经历。稍后将在需要帮助时进行编辑。
<