如何解决我无法识别的代码中有错误
当我尝试运行代码时,会打开pygame窗口,但它保持黑色且无响应。以我的经验,这仅在已运行的代码不正确时发生。现在的问题是我在代码中找不到任何错误。 请帮我调试一下。 这是我的代码-
import pygame as pg
import player
import pygame
purple=(132,66,245)
class bullet(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((5,5))
self.image.fill(purple)
self.rect = self.image.get_rect()
def move(self,dx,dy):
self.rect.move_ip(dx,dy)
pg.init()
SCREEN=pg.display.set_mode((500,500))
SCREEN.fill((0,0))
go=True
clock=pg.time.Clock()
playerlist=pg.sprite.Group()
player1=player.PLAYER()
player1.rect.x=235
player1.rect.y=235
playerlist.add(player1)
bulletlist=pg.sprite.Group()
def Move(fx,fy,coeffy):
alive=True
bullet1=bullet()
bullet1.rect.x=235
bullet1.rect.y=235
bulletlist.add(bullet1)
if bullet1.rect.x==fx and bullet1.rect.y==fy:
bulletlist.remove(bullet1)
bullet1.kill()
alive=False
while alive:
bulletlist.draw(SCREEN)
bullet1.move(5,coeffy*5)
playerlist.draw(SCREEN)
while go:
for event in pg.event.get():
if event.type==pg.QUIT:
go=False
p1,p2,p3=pg.mouse.get_pressed()
mousex,mousey=pg.mouse.get_pos()
if p1:
if mousex>235:
distx=mousex-235
disty=mousey-235
coeff_y=disty/distx
Move(mousex,mousey,coeff_y)
pg.display.flip()
在这种情况下,程序应该以恒定的速度将精灵移动到单击鼠标的位置。
解决方法
while
函数中的Move
循环是一个无限循环,因为循环中的alive
状态永远不会改变。
您有一个应用程序循环,因此循环中不需要额外的循环。子弹每帧只需要移动一次。将Move
中的循环更改为一个选择(将while
更改为if
)
def Move(fx,fy,coeffy):
alive=True
bullet1=bullet()
bullet1.rect.x=235
bullet1.rect.y=235
bulletlist.add(bullet1)
if bullet1.rect.x==fx and bullet1.rect.y==fy:
bulletlist.remove(bullet1)
bullet1.kill()
alive=False
if alive: # <--- if instead of while
bulletlist.draw(SCREEN)
bullet1.move(5,coeffy*5)
pg.display.flip()
必须在应用程序循环中完成,而不是在应用程序循环后完成。关心Indentation:
while go:
for event in pg.event.get():
if event.type==pg.QUIT:
go=False
p1,p2,p3=pg.mouse.get_pressed()
mousex,mousey=pg.mouse.get_pos()
if p1:
if mousex>235:
distx=mousex-235
disty=mousey-235
coeff_y=disty/distx
Move(mousex,mousey,coeff_y)
#-->| INDENTATION
pg.display.flip()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。