python - Pygame for-loop 只运行一次
问题描述
我正在制作一个平台游戏。我有一个平台列表,然后是一个“for platform in platform_list:”,即使有两个或更多平台,for 循环也只运行一次。我有另一个文件,我在其中存储平台类和 make_platform() 函数。
###### platformer_main.py #######
from platform import make_platform
def platform_handler():
print(len(platform_list)) # even if this prints out 2, the for loop still only runs once
for platform in platform_list:
pygame.draw.rect(window, green, (platform.x, platform.y, platform.w, platform.h)) # draw
platform.x -= platform.speed # move to the left
if platform.done == False: # add next platform
if platform.x <= 650:
platform.done = True
add_platform()
if platform.x + platform.w <= 0: # delete platform
platform_list.remove(platform)
return platform_list
# character collision detection
if charac.x + charac.w >= platform.x and charac.x <= platform.x + platform.w and charac.y + charac.h >= platform.y and charac.y <= platform.y + platform.h:
charac.fall = False
else:
charac.fall = True
return charac
###### platform.py #####
class Platform:
def __init__(self):
self.x = 0
self.y = 0
self.w = 0
self.h = 0
self.speed = 0
self.done = 0
def make_platform():
platform = Platform()
platform.x = 1000
platform.y = random.randrange(200, 600)
platform.w = random.randrange(300, 500)
platform.h = 20
platform.done = False
platform.speed = 5
return platform
不会出现错误消息。
解决方案
return
导致函数返回,停止任何正在进行的循环。
推荐阅读
- node.js - PM2 节点应用程序在新端口上生成每个集群实例
- php - PHP 数组和 Worpdress 重新格式化
- python - 如何将计算列添加到多索引数据框
- matrix - 如何在 Power BI 中正确构建矩阵
- php - 使用 PHP/AJAX 实时监控 MySQL 表的变化
- stripe-payments - 通过 Stripe 客户门户更新订阅时,如何移植剩余的试用天数?
- mysql - 选择客户完成的最新步骤的行?
- r - 在 R 中生成唯一的行对
- postgresql - 在 Postgres 中重定向数据
- java - 如何创建在两个不同类中工作的相同 HashMap,而无需在 Android Studio 中创建另一个 HashMap?