首页 > 解决方案 > 为什么调用 font.render() 时程序会返回错误?

问题描述

我正在尝试通过以下 pdf 学习 pygame 的一些基础知识:https ://buildmedia.readthedocs.org/media/pdf/pygame/latest/pygame.pdf 我停在第 29 页,它向我展示了 Rect类定义了 4 个角点、4 个中点和 1 个中心点。但是当我启动程序时,它给了我一个错误,说没有名为“rect”的模块,如果我删除它说字体未定义,我应该添加什么以使其正常工作?

import pygame
from pygame.locals import *
from rect import *

def draw_point(text, pos):
    img = font.render(text, True, BLACK)
    pygame.draw.circle(screen, RED, pos, 3)
    screen.blit(img, pos)

pygame.init()

GRAY = (125, 125, 125)
GREEN = (0, 255, 0)
BLACK = (0, 0, 0)
RED = (255, 0, 0)

screen = pygame.display.set_mode((640, 240))

rect = Rect(50, 40, 250, 80)
pts = ('topleft', 'topright', 'bottomleft', 'bottomright', 'midtop', 'midright', 'midbottom', 'midleft', 'center')

running = True
while running:
    for event in pygame.event.get():
        if event.type == QUIT:
            running = False
    
    screen.fill(GRAY)
    pygame.draw.rect(screen, GREEN, rect, 4)
    
    for pt in pts:
        draw_point(pt, eval('rect.'+pt))
    
    pygame.display.flip()

pygame.quit()

标签: pythonpygame

解决方案


继续读那本书;该部分3.9 The common code包含以下定义rect.py

import pygame
from pygame.locals import *
from random import randint

width = 500
height = 200

RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)

YELLOW = (255, 255, 0)
MAGENTA = (255, 0, 255)
CYAN = (0, 255, 255)

BLACK = (0, 0, 0)
GRAY = (150, 150, 150)
WHITE = (255, 255, 255)

dir = {K_LEFT: (-5, 0), K_RIGHT: (5, 0), K_UP: (0, -5), K_DOWN: (0, 5)}

pygame.init()
screen = pygame.display.set_mode((width, height))
font = pygame.font.Font(None, 24)
running = True

创建该文件后,您会没事的。


推荐阅读