pygame在采取行动后立即崩溃

时间:2016-07-15 19:06:38

标签: python pygame

我是Python的新手,所以我的代码中的问题可能是一个愚蠢的问题。 在播放器的图像移动之后,pygame的窗口在IDLE处崩溃而没有错误消息。

即时通讯使用Python 2.7。 这是代码:

import pygame,sys
from pygame.locals import *

pygame.init()
dis=pygame.display.set_mode((1084,638),0,32)
pygame.display.set_caption('ledders and snakes')

FPS=30
fpsClock=pygame.time.Clock()
White=(255,255,255)
img=pygame.image.load('smal.gif')
bg = pygame.image.load("under.gif")

cax=150
cay=150
di='right'
flag=True

while flag:
    dis.blit(bg, (0, 0))
    if di=='right':
        cax+=10
        cay-=10
        if cax==280:
            di='down'
    elif di=='down':
        cay+=10
        cax+=10
        if cax==410:
            flag=False


    dis.blit(img,(cax,cay))

    for event in pygame.event.get():
        if event.type==QUIT:
            pygame.quit()
            sys.exit()

    pygame.display.update()
    fpsClock.tick(FPS)

2 个答案:

答案 0 :(得分:0)

我只是略过了你的程序,如果我没错(希望我不是),你继续向cax添加10,结果是你的玩家到达了将标志设置为false的位置在你的while循环中只有26次迭代。 这将很快发生。

答案 1 :(得分:0)

我查看了您的计划,问题是您在flag = False时设置了if cax == 410。这就是你的程序退出的原因,因为在几秒钟后条件变为True。但是你应该考虑很多事情,所以我做了一些改变(不是在程序中,而是在名称中):

import pygame
import sys
from pygame.locals import *

pygame.init()
SIZE = WIDTH, HEIGHT = 1084, 638  # Have a reference to WIDTH and HEIGHT.
screen = pygame.display.set_mode(SIZE, 0, 32)  # 'screen' is the convention and describes the variable better than 'dis'.
pygame.display.set_caption('ledders and snakes')

FPS = 30
clock = pygame.time.Clock()  # Use lowercase for variables.
WHITE = (255, 255, 255)  # Use CAPS for constants.
img = pygame.Surface((32, 32))  # Used these two lines because I don't have your image.
img.fill((0, 0, 255))
bg = pygame.Surface((32, 32))    # Used these two lines because I don't have your image.
bg.fill((255, 0, 0))

cax = 150  # Since I don't know your program I can't tell if these are describable variables or not. 
cay = 150
direction = 'right'  # 'di' isn't describable enough.
running = True  # 'flag' seems like an indescribable variable.

while running:
    screen.blit(bg, (0, 0))
    if direction == 'right':
        cax += 10
        cay -= 10
        if cax == 280:
            direction = 'down'
    elif direction == 'down':
        cay += 10
        cax += 10
        if cax == 410:
            running = False

    screen.blit(img, (cax, cay))

    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

    pygame.display.update()
    clock.tick(FPS)

此外,将运算符之间的空格设置为“==”或逗号之后,例如“(0,0)”而不是(0,0)。并使用小写的变量名,其中单词用下划线分隔。尝试关注PEP8,只要打破它就没有意义。

相关问题