python - 基本 Pygame 程序未执行

标签 python 2d pygame graphic

输入此 pygame 代码进行动画测试,我预计会出现一些错误,但程序根本不会执行:

第一部分导入模块

import sys
import os
import pygame
from pygame.locals import *

初始化pygame

pygame.init ()

加载 Sprite 图像文件的类,然后是声音

class Processes (object):
    @staticmethod
    def load_image (imagefile):
        image = pygame.image.load (imagefile)
        return image, image.get_rect ()

Sprite 类

class Sprite (pygame.sprite.Sprite):
    def __init__ (self):
        pygame.sprite.Sprite.__init__ (self)
        self.image, self.rect = Processes.load_image ('frame1.jpg')

简单的动画功能——让生活更轻松

    def animation (self, key_event):
        if key_event == K_DOWN:
            self.rect.centery = self.rect.centery - 10

        if key_event == K_UP:
            self.rect.centery = self.rect.centery + 10

        if key_event == K_RIGHT:
            self.rect.centerx = self.rect.centerx + 10

        if key_event == K_LEFT:
           self.rect.centerx = self.rect.centerx - 10

        return self.rect

主要功能:

def main ():
    mecha = Sprite ()
    allsprites = pygame.sprite.RenderPlain ((mecha, ))

游戏循环:

while True:
    Surface = pygame.display.set_mode ((400, 400))
    pygame.display.set_caption ('Animation Test')

    for event in pygame.event.get ():
        if event.type == KEYDOWN:
            mecha.animation (event.key)

        if event.type == QUIT:
            pygame.quit ()
            sys.exit (0)


    allsprites.draw (Surface)
    pygame.display.update ()

这是真正的“错误”

C:/Khan's Family/python/Bunnies Vs. Zombies/BvZ_Animtest.py 

现在这里是输出:

(Nothing)

C:/Khan's Family/python/Bunnies Vs. Zombies

没有输出,这是我的问题。

最佳答案

当 pygame 出现错误时,它会发生什么,我认为你所说的“不会执行”是什么意思。您必须垃圾邮件单击 x 按钮将其关闭,错误将显示在 shell 中。在这个特定程序上,错误是:

File "C:/Python32/projects/deletable.py", line 45, in <module>
    allsprites.draw (Surface)
NameError: name 'allsprites' is not defined

您可以自己处理问题,但事实就是如此。

关于python - 基本 Pygame 程序未执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13187926/

相关文章:

python - 使矩形对象可滚动

python - Selenium +Python+单元测试:Error message when executing Test "Other element would receive the click"

python - 有/没有事先编译的 exec 语句

android - Unity 背景 Sprite 会影响 fps

java - 带位图的高效onDraw和硬件加速的复杂裁剪

python - 在 Python 中使用 lambda 时遇到问题

python - 通过套接字发送网络摄像头

python - 使用 pickle 将巨大的二元字典保存到文件中

python - 将文件添加到文件夹时如何自动运行python脚本?

c++ - 实时 2D 渲染到系统内存