【问题标题】:Pygame level system causing list indexing errorsPygame 级别系统导致列表索引错误
【发布时间】:2012-05-11 01:18:09
【问题描述】:

我创建了一个pygame,游戏的目的是避免球在屏幕上移动(随机)

ballpic = pygame.image.load('ball.png').convert_alpha()

我有一个水平功能:

def levels(score):
 global enemies
 global velocity
 enemies = enemies
 velocity = velocity

#level one 
if score >= 500:
  enemies = 6
  velocity = 2

#level two
if score >= 1000:
  enemies = 6
  velocity = 2
  #....And so on

带有缩进的游戏:///已过期/

如果我尝试这样做,我会收到此错误:

Traceback (most recent call last):
 File "C:\Users\MO\Desktop\Twerk\twerk-bck.py", line 252, in <module>
  game()
File "C:\Users\MO\Desktop\Twerk\twerk-bck.py", line 199, in game
 positionx[i]=positionx[i]+positionxmove[i]
IndexError: list index out of range

我知道我需要将新值附加到列表中以将它们扩展 3 个条目。我想要实现的是在屏幕上添加更多的球,得分达到一定的数字。但我不知道我该怎么做?

谢谢

【问题讨论】:

  • 为每个球使用对象,这样您就不需要保留许多具有相同索引的列表,这很脆弱且难以管理。

标签: python arrays python-3.x pygame


【解决方案1】:

您在主循环的第 147 行之前在第 134 行初始化 positionx 和朋友。然后在循环内调用 levels(score),这会更新 enemies 计数,但实际上并未在 positionx 中为额外的敌人。 levels() 应该负责在增加敌人数量时调整数组的大小。

正如 Lattyware 所评论的,为每个敌人使用对象将是一个更好的设计。通常,如果您要保留任何类型的并行数组,例如 positionxpositiony,则应将它们替换为对象数组。然后,range(enemies) 上的所有不同循环将被一个大循环替换,例如:

for enemy in enemies:
    enemy.update(globalGameState)

其中globalGameState 是一个或多个变量,用于跟踪诸如鼠标位置之类的东西,所有敌人都相同

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多