首页 > 解决方案 > Pygame 显示黑屏(《Pro Python 最佳实践》)

问题描述

我从“Pro Python Best Practices”一书中获取了此代码,但无法运行游戏。运行此代码后,它显示黑屏:

from load_tiles import load_tiles
from generate_maze import create_maze
from event_loop import event_loop
from draw_maze import draw_grid, parse_grid
from moves import move, LEFT, RIGHT, UP, DOWN
from pygame import Rect
import pygame


DIRECTIONS = {
    276: LEFT, 275: RIGHT,
    273: UP, 274: DOWN
}


def draw():
    """Displays the maze on the screen"""
    img = draw_grid(maze, tile_img, tiles)
    display.blit(img, Rect((0, 0, 384, 224)), Rect((0, 0, 384, 224)))
    pygame.display.update()


def handle_key(key):
    """Handles key events in the game"""
    direction = DIRECTIONS.get(key)
    if direction:
        move(maze, direction)
    draw()


if __name__ == '__main__':
    # initialize display
    pygame.init()
    pygame.display.set_mode((800, 600))
    display = pygame.display.get_surface()
    tile_img, tiles = load_tiles()

    # prepare the maze
    maze = parse_grid(create_maze(12, 7))
    maze[1][1] = '*'
    maze[5][10] = 'x'

    # start the game
    draw()
    event_loop(handle_key)

终端没有显示任何错误。它只是运行黑屏。我试图找到类似的问题,但在大多数情况下,问题出在代码中。根据书它必须工作。我将不胜感激任何帮助!

标签: pythonpython-3.xpygame

解决方案


我碰巧有这本书的副本,它在 github 目录上的一个文本文件中有许多要求,我假设你从那里粘贴了这段代码。确保您满足所有要求,因为这可能是问题所在


推荐阅读