繁体   English   中英

Python Pygame图片未显示

[英]Python Pygame image not displaying

我正在尝试在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()

只是一个猜测,因为我实际上并未执行此操作:

屏幕只是显示为蓝色,而您缺少pacman图像吗? 可能发生的情况是,您将pacman拖到屏幕上,然后执行screen.fill(blue),这实际上是用蓝色覆盖pacman图像。 尝试将代码中的这些步骤反向(即,将屏幕填充为蓝色,然后再使pacman闪烁)。

注意:

  • 您正在每帧创建一个新图像。 太慢了
  • blit的坐标可以是Rect()

这是更新的代码。

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()    

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

同样,必须在顶部定义蓝色,并且它应该处于不同的循环中。 这是我要怎么做:

    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()

首先您先将图像变白,然后再填充蓝色,这样它可能只会显示蓝屏,

解决方案:首先将屏幕填充为蓝色,然后将其变白。

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()

    blue = (0,0,255)
    screen.fill(blue)   # first fill screen with blue
    screen.blit(pacman_obj, (pacman_x,pacman_y))  # Blit the iamge
    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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM