【问题标题】:Failing to blit image to screen无法将图像blit到屏幕
【发布时间】:2016-04-18 22:25:25
【问题描述】:

我正在尝试使用 pygame 将地图绘制到屏幕上,但不明白为什么它不会。我没有得到追溯。屏幕正在初始化,然后没有绘制图像。我尝试过使用其他 .bmp 图像,结果相同,所以我的代码中一定有一些东西没有正确排序/编写。

这里是游戏的主要模块:

import pygame
import sys
from board import Board

def run_game():

    #Launch the screen.

    screen_size = (1200, 700)
    screen = pygame.display.set_mode(screen_size)
    pygame.display.set_caption('Horde')


    #Draw the board.
    game_board = Board(screen)
    game_board.blit_board()

    #Body of the game.
    flag = True
    while flag == True:
        game_board.update_board()

run_game()

这是您看到正在使用的板模块。具体来说,blit_board() 函数,它默默地无法绘制我要求它的map.bmp 文件(文件在同一目录中)。

import pygame
import sys

class Board():

    def __init__(self, screen):
        """Initialize the board and set its starting position"""
        self.screen = screen

        #Load the board image and get its rect.
        self.image = pygame.image.load('coll.bmp')
        self.rect = self.image.get_rect()
        self.screen_rect = screen.get_rect()

        #Start the board image at the center of the screen.
        self.rect.centerx = self.screen_rect.centerx
        self.rect.centery = self.screen_rect.centery

    def blit_board(self):
        """Draw the board on the screen."""
        self.screen.blit(self.image, self.rect)



    def update_board(self):
        """Updates the map, however and whenever needed."""

        #Listens for the user to click the 'x' to exit.
        for event in pygame.event.get():
            if event.type == pygame.QUIT: sys.exit()

        #Re-draws the map.
        self.blit_board()

我得到的只是黑屏。为什么map.bmp 图像不绘制?

【问题讨论】:

标签: python pygame blit


【解决方案1】:

正如 Dan Mašek 所说,您需要告诉 PyGame 在绘制图像后更新显示。

要实现这一点,只需将“板”循环修改为以下内容:

def update_board(self):
    """Updates the map, however and whenever needed."""

    #Listens for the user to click the 'x' to exit.
    for event in pygame.event.get():
        if event.type == pygame.QUIT: sys.exit()

    #Re-draws the map.
    self.blit_board()

    pygame.display.update()

【讨论】:

  • 这正是我需要做的。 pygame.display.update()。忘记那个了。感谢您的帮助!
猜你喜欢
  • 2022-11-26
  • 2020-06-11
  • 2010-09-29
  • 2023-03-26
  • 1970-01-01
  • 1970-01-01
  • 2020-09-23
  • 2021-05-21
  • 2014-12-08
相关资源
最近更新 更多