繁体   English   中英

陷入无限循环,不知道为什么 - python

[英]Stuck in infinite loop, cant figure out why - python

当这段代码运行时,它应该在玩家和计算机之间交替,但是当轮到计算机时,它只是完成了游戏。 我反复检查了缩进级别,但找不到问题所在。

你写这个的方式让你很难真正弄清楚控制流是如何进行的。 有很多重复对于游戏来说并不是真正必要的,这增加了复杂性。 一个主要的事情是你有四个位置可以询问玩家是否重新开始游戏。 如果您只确保拥有一次,那么您已经可以大大简化一切。

然后你会注意到的第一件事是结构是这样的:

while winFlag == False:
    # player move
    while sticksOnBoard != 0:
        # evaluate winner
        # AI move
        # evaluate winner

因此,除非任何玩家已经通过低于 0 棒而获胜,否则 AI 移动将一遍又一遍地发生,直到有人获胜。 但是玩家再也没有机会移动了。 相反,您可能希望完全移除winFlag因为当棋盘上没有更多木棍时,游戏就结束了。 所以你会像这样:

while sticksOnBoard > 0:
    # player move
    if sticksOnBoard <= 0:
        # evaluate winner
    # AI move
# evaluate winner

或者要删除重复的评估,您只需切换活动播放器:

isPlayerMove = True
while sticksOnBoard > 0:
    if isPlayerMove:
        # player move
    else:
        # AI move
    isPlayerMove = not isPlayerMove # toggle current player
# evaluate winner

这就是我制作这款游戏​​的方式,减少所有重复:

def playerVsAiGame (sticksOnBoard):
    # main game loop
    while True:
        sticks = sticksOnBoard
        isPlayerMove = True

        # only ask when there are more than 3 left; otherwise the current
        # player can just choose the remaining number and win
        while sticks > 3:
            print('There are {} sticks on the board.'.format(sticks))
            if isPlayerMove:
                move = int(input('How many sticks would you like to take? (1-3) '))
            else:
                # the computer just chooses randomly between 1, 2, and 3 sticks
                # this is where you could add additional game logic to make the AI
                # smarter
                move = random.choice((1, 2, 3))
                print('The computer takes {} sticks.'.format(move))

            sticks -= move
            isPlayerMove = not isPlayerMove

        # the current player wins
        print('There are {} sticks on the board.'.format(sticks))
        if isPlayerMove:
            print('You win!')
        else:
            print('The computer wins!')

        # break the main loop unless the player wants to play again
        if input('Play again? Yes (1) / No (0) ').lower() not in ('1', 'yes', 'y'):
            break

我认为你在这段代码中得到了一些非常错误的东西。

你永远不会在你的内部循环中请求用户输入。

您检查sticksOnBoard是否小于0,并检查它是否为1。但是,在大多数情况下, sticksOnBoard只会具有更大的值,因此, while sticksOnBoard != 0将循环直到您的游戏结束。

同时,您的基本 AI 将不断地从棋盘上抽出棍棒,而无需用户做任何事情。

看来你对编程不是很熟悉(这没问题,大家都开始了)。 这就是为什么我会建议您带上笔和纸,并逐步完成您的函数的示例运行。 这样,程序无法按您想要的方式运行的原因就很明显了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM