Python Pygame图像不显示

2024-05-23 17:27:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在pygame中显示一个游戏。但是因为某种原因它不会起作用,有什么想法吗?这是我的代码:

import pygame, sys
from pygame.locals import *
pygame.init()
screen=pygame.display.set_mode((640,360),0,32)
pygame.display.set_caption("My Game")
p = 1
green = (0,255,0)
pacman ="imgres.jpeg"
pacman_x = 0
pacman_y = 0
while True:
    pacman_obj=pygame.image.load(pacman).convert()
    screen.blit(pacman_obj, (pacman_x,pacman_y))
    blue = (0,0,255)
    screen.fill(blue)
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        if event.type==KEYDOWN:
            if event.key==K_LEFT:
                p=0
    pygame.display.update()

Tags: 代码fromimporteventobj游戏iftype
3条回答

如果屏幕显示为蓝色,那是因为您需要在执行screen.fill之后“blit”图像

另外,蓝色必须在顶部定义,它应该在一个不同的循环中。我可以这样做:

    import pygame, sys
    from pygame.locals import *
    pygame.init()
    screen=pygame.display.set_mode((640,360),0,32)
    pygame.display.set_caption("My Game")
    p = 1
    green = (0,255,0)
    blue = (0,0,255)
    pacman ="imgres.jpeg"
    pacman_x = 0
    pacman_y = 0
    pacman_obj=pygame.image.load(pacman).convert()
    done = False
    clock=pygame.time.Clock()
    while done==False:
        for event in pygame.event.get(): 
            if event.type == pygame.QUIT:
                done=True
            if event.type==KEYDOWN:
                if event.key==K_LEFT:
                    p=0
        screen.fill(blue)
        screen.blit(pacman_obj, (pacman_x,pacman_y))

        pygame.display.flip()
        clock.tick(100)

    pygame.quit()

注:

  • 你在创造一个新的画面。这很慢。在
  • blit的坐标可以是Rect()s

这是更新的代码。在

WINDOW_TITLE = "hi world - draw image "

import pygame
from pygame.locals import *
from pygame.sprite import Sprite
import random
import os

class Pacman(Sprite):
    """basic pacman, deriving pygame.sprite.Sprite"""
    def __init__(self, file=None):
        """create surface"""
        Sprite.__init__(self)
        # get main screen, save for later
        self.screen = pygame.display.get_surface()                

        if file is None: file = os.path.join('data','pacman.jpg')
        self.load(file)

    def draw(self):
        """draw to screen"""
        self.screen.blit(self.image, self.rect)

    def load(self, filename):
        """load file"""
        self.image = pygame.image.load(filename).convert_alpha()
        self.rect = self.image.get_rect()      

class Game(object):
    """game Main entry point. handles intialization of game and graphics, as well as game loop"""    
    done = False
    color_bg = Color('seagreen') # or also: Color(50,50,50) , or: Color('#fefefe')

    def __init__(self, width=800, height=600):
        """Initialize PyGame window.

        variables:
            width, height = screen width, height
            screen = main video surface, to draw on

            fps_max     = framerate limit to the max fps
            limit_fps   = boolean toggles capping FPS, to share cpu, or let it run free.
            color_bg    = backround color, accepts many formats. see: pygame.Color() for details
        """
        pygame.init()

        # save w, h, and screen
        self.width, self.height = width, height
        self.screen = pygame.display.set_mode(( self.width, self.height ))
        pygame.display.set_caption( WINDOW_TITLE )        

        # fps clock, limits max fps
        self.clock = pygame.time.Clock()
        self.limit_fps = True
        self.fps_max = 40        

        self.pacman = Pacman()

    def main_loop(self):
        """Game() main loop.
        Normally goes like this:

            1. player input
            2. move stuff
            3. draw stuff
        """
        while not self.done:
            # get input            
            self.handle_events()

            # move stuff            
            self.update()

            # draw stuff
            self.draw()

            # cap FPS if: limit_fps == True
            if self.limit_fps: self.clock.tick( self.fps_max )
            else: self.clock.tick()

    def draw(self):
        """draw screen"""
        # clear screen."
        self.screen.fill( self.color_bg )

        # draw code
        self.pacman.draw()

        # update / flip screen.
        pygame.display.flip()

    def update(self):
        """move guys."""
        self.pacman.rect.left += 10

    def handle_events(self):
        """handle events: keyboard, mouse, etc."""
        events = pygame.event.get()

        for event in events:
            if event.type == pygame.QUIT: self.done = True
            # event: keydown
            elif event.type == KEYDOWN:
                if event.key == K_ESCAPE: self.done = True

if __name__ == "__main__": 
    game = Game()
    game.main_loop()    

只是一个猜测,因为我还没有实际运行过这个:

屏幕是蓝色的而你没有看到pacman的图像吗?可能会发生的是你把pacman放到屏幕上,然后做一个屏幕填充(蓝色),这实际上是用蓝色覆盖pacman图像。试着在你的代码中反转这些步骤(也就是说,把屏幕填成蓝色,然后在后面用blitting pacman)。在

相关问题 更多 >