Pygame 3字体无效

时间:2016-04-29 14:41:08

标签: python fonts pygame

我观看了一些教程,但我似乎无法弄清楚如何使用Pygame在Python 3上做字体。这是我的代码:

import pygame
import time
import font
pygame.init

white = (255,255,255)
black = (0,0,0)
red = (255,0,0)

display_width = 800
display_height = 600

gameDisplay = pygame.display.set_mode((display_width,display_height))

pygame.display.set_caption('Slither')

gameExit = False

lead_x = display_width/2
lead_y = display_height/2

lead_x_change = 0
lead_y_change = 0

clock = pygame.time.Clock()

block_size = 10
FPS = 30

font = pygame.font.SysFont(None, 25)

def message_to_screen(msg,color):
    screen_text = font.render(msg, True, color)
    gameDisplay.blit(screen_text, [display_width/2, display_height/2])
while not gameExit:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            gameExit = True
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                lead_x_change = -block_size
                lead_y_change = 0
            elif event.key == pygame.K_RIGHT:
                lead_x_change = block_size
                lead_y_change = 0
            elif event.key == pygame.K_UP:
                lead_y_change = -block_size
                lead_x_change = 0
            elif event.key == pygame.K_DOWN:
                lead_y_change = block_size
                lead_x_change = 0

    if lead_x >= display_width or lead_x < 0 or lead_y >= display_height or lead_y < 0:
        gameExit = True


    lead_x += lead_x_change
    lead_y += lead_y_change

    gameDisplay.fill(white)
    pygame.draw.rect(gameDisplay, black, [lead_x,lead_y,block_size,block_size])
    pygame.display.update()

    clock.tick(FPS)

message_to_screen("You Lose", True, red)
pygame.display.update()
time.sleep(2)     
pygame.quit()
quit()

2 个答案:

答案 0 :(得分:0)

除第3行和第4行外,您的代码很好。您不必import font,因为您使用的字体是pygame模块的一部分。您收到错误的原因&#34; pygame.error:font not initialized &#34;是因为你永远不会初始化pygame模块。在第4行,你必须用括号写pygame.init()

这就是为什么你的代码不起作用的原因。除了这两行之外,代码还可以。

其他答案不正确,因为pygame docs明确说明:

&#34;如果文件名为None,将加载Pygame默认字体。&#34;

答案 1 :(得分:-1)

font = pygame.font.SysFont(&#39; arial&#39;,25)