行星模拟Python代码报错:TypeError: 'type'对象不可迭代
行星模拟代码迭代错误修复
错误信息
File "C:\Python prog\orbit.py", line 57, in main
for planets in Planet:
TypeError: 'type' object is not iterable
问题代码
import pygame import math pygame.init WIDTH,HEIGHT= 800,800 WIN = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Planet simulation") WHITE = (255,255,255) YELLOW = (255,255,0) BLUE = (100, 149, 237) RED = (188, 39, 50) DARK_GREY = (80, 78, 81) #FONT = pygame.font.SysFont("comicsans", 16) class Planet: AU = 149.6e6 * 1000 G = 6.67428e-11 SCALE = 250 / AU TIMESTEP = 3600*24 def __init__(self, x, y, radius, color, mass): self.x = x self.y = y self.radius = radius self.color = color self.mass = mass self.orbit = [] self.sun = False self.distance_to_sun = 0 self.x_vel = 0 self.y_vel = 0 def draw(self, win): x=self.x * self.SCALE + WIDTH /2 y=self.y * self.SCALE + HEIGHT /2 pygame.draw.circle(win, self.color, (x, y), self.radius) def main(): run=True clock = pygame.time.Clock() sun = Planet(0,0,30,YELLOW, 1.98892 * 10**30) earth = Planet(-1 * Planet.AU, 0, 16, BLUE, 5.9742 * 10**24) sun.sun = True planets = [sun, earth] while run: clock.tick(60) WIN.fill((0, 0, 0)) for event in pygame.event.get(): if event.type ==pygame.QUIT: run = False for planets in Planet: planet.draw(WIN) #planet.Update_position(planets) pygame.display.update() pygame.QUIT() main()
修复方案
- 核心错误修复:你试图迭代
Planet类(不可迭代的类型),而应该迭代你创建的行星实例列表planets。同时循环变量名不要和列表名重复,改成planet,并使用该变量调用draw方法。 - 初始化修复:
pygame.init需要添加括号,改为pygame.init(),否则Pygame无法正确初始化。 - 细节修复:
pygame.QUIT改为pygame.quit(),调用退出函数而非引用事件常量。
修改后的代码
import pygame import math pygame.init() # 修复:添加括号完成初始化 WIDTH,HEIGHT= 800,800 WIN = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Planet simulation") WHITE = (255,255,255) YELLOW = (255,255,0) BLUE = (100, 149, 237) RED = (188, 39, 50) DARK_GREY = (80, 78, 81) #FONT = pygame.font.SysFont("comicsans", 16) class Planet: AU = 149.6e6 * 1000 G = 6.67428e-11 SCALE = 250 / AU TIMESTEP = 3600*24 def __init__(self, x, y, radius, color, mass): self.x = x self.y = y self.radius = radius self.color = color self.mass = mass self.orbit = [] self.sun = False self.distance_to_sun = 0 self.x_vel = 0 self.y_vel = 0 def draw(self, win): x=self.x * self.SCALE + WIDTH /2 y=self.y * self.SCALE + HEIGHT /2 pygame.draw.circle(win, self.color, (x, y), self.radius) def main(): run=True clock = pygame.time.Clock() sun = Planet(0,0,30,YELLOW, 1.98892 * 10**30) earth = Planet(-1 * Planet.AU, 0, 16, BLUE, 5.9742 * 10**24) sun.sun = True planets = [sun, earth] while run: clock.tick(60) WIN.fill((0, 0, 0)) for event in pygame.event.get(): if event.type ==pygame.QUIT: run = False # 修复:迭代行星实例列表,使用正确的循环变量 for planet in planets: planet.draw(WIN) #planet.Update_position(planets) pygame.display.update() pygame.quit() # 修复:调用退出函数 main()
内容的提问来源于stack exchange,提问作者Steven Chambers
相关产品推荐
相关产品推荐

