简体   繁体   English

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

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

I have tried to create a game in python.我尝试在 python 中创建游戏。 There are two players, they roll a die and their total score is updated.有两名玩家,他们掷骰子并更新他们的总分。 The first to reach 100 wins.第一个达到100胜。 The output of this program is very weird.这个程序的output很奇怪。 I get 35 NumPy arrays like this one: [0].我得到 35 个 NumPy arrays 像这样一个:[0]。 According to my inexperienced brain, I have got everything right.根据我没有经验的大脑,我已经做好了一切。

# 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)

From the documentation , np.append does not modify the original array, unlike Python's list.append .文档中, np.append不会修改原始数组,这与 Python 的list.append不同。 It instead returns a new array containing the original array along with the new appended values.相反,它返回一个新数组,其中包含原始数组以及新的附加值。 Instead of just writing而不仅仅是写作

np.append(player_one_score, player_one_roll)

You should instead write你应该改为写

player_one_score = np.append(player_one_score, player_one_roll)

Reading further into the code, it looks like you have a couple of indentation errors.进一步阅读代码,看起来你有几个缩进错误。 The if/else statements should look something like this: if/else 语句应如下所示:

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

Additionally, if the win condition is for the total to be over 100, the sum of player_one_score array should be used like so:此外,如果获胜条件是总数超过 100,则应使用player_one_score数组的sum ,如下所示:

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

The same goes for player_two_score (Also note the change from == to >= ). player_two_score也是如此(另请注意从==>=的变化)。

Lastly, like Pouya said, you don't really need NumPy for something like this.最后,就像 Pouya 说的,你真的不需要 NumPy 来做这样的事情。 Using vanilla Python is probably the best way to learn coding.使用 vanilla Python 可能是学习编码的最佳方式。 You should also look into while loops;您还应该查看while循环; they should be used instead of for loops for something like this.对于这样的事情,应该使用它们而不是for循环。

Example:例子:

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

though you would want to store the conditions in a variable so the code doesn't look as ugly.尽管您希望将条件存储在变量中,这样代码看起来就不会那么难看。

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

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