繁体   English   中英

如何修复这个简单的 Python 程序? 我想我的逻辑错了

[英]How to fix this simple Python program? I think I have got the logic wrong

我尝试在 python 中创建游戏。 有两名玩家,他们掷骰子并更新他们的总分。 第一个达到100胜。 这个程序的output很奇怪。 我得到 35 个 NumPy arrays 像这样一个:[0]。 根据我没有经验的大脑,我已经做好了一切。

# Snakes and Ladders (2 players)
import numpy as np

player_one_score = np.array([0])
player_two_score = np.array([0])

for p1 in range(30) :

        player_one_roll = np.random.randint(1,7)
        np.append(player_one_score, player_one_roll)
        if player_one_score == 100 :
        print('Player 1 won!') 
        else :
        print(player_one_score)

        player_two_roll = np.random.randint(1,7)
        np.append(player_two_score, player_two_roll)
        if player_two_score == 100 :
        print('Player 2 won!')
        else :
        print(player_two_score)

文档中, np.append不会修改原始数组,这与 Python 的list.append不同。 相反,它返回一个新数组,其中包含原始数组以及新的附加值。 而不仅仅是写作

np.append(player_one_score, player_one_roll)

你应该改为写

player_one_score = np.append(player_one_score, player_one_roll)

进一步阅读代码,看起来你有几个缩进错误。 if/else 语句应如下所示:

 if player_one_score == 100 :
    print('Player 1 won!') 
 else :
    print(player_one_score)

此外,如果获胜条件是总数超过 100,则应使用player_one_score数组的sum ,如下所示:

 if sum(player_one_score) >= 100:
    print('Player 1 won!') 
 else:
    print(player_one_score)

player_two_score也是如此(另请注意从==>=的变化)。

最后,就像 Pouya 说的,你真的不需要 NumPy 来做这样的事情。 使用 vanilla Python 可能是学习编码的最佳方式。 您还应该查看while循环; 对于这样的事情,应该使用它们而不是for循环。

例子:

while ( sum(player_one_score) < 100 or sum(player_two_score) < 100 ):
   # Code here
   # ...

尽管您希望将条件存储在变量中,这样代码看起来就不会那么难看。

暂无
暂无

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

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