我正在关注一个youtube教程系列,我在我的pygame游戏中遇到了这个问题。我创建了一个名为messagetoscreen的函数,它在视频中运行良好,但它对我没有用。
这是我的代码:
#Imports
import pygame
pygame.init()
pygame.font.init()
import sys
import random
import cx_Freeze
import time
#Variables
playerhealth = 100
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
green = (0 ,255, 0)
windowtitle = "Climber"
sizex = 1000
sizey = 700
rect1x = 500
rect1y = 350
rect1sizex = 50
rect1sizey = 50
rect1xchange = 0
rect1ychange = 0
clock = pygame.time.Clock()
fps = 600
font = pygame.font.SysFont(None, 25)
#Functions
def messagetoscreen (msg,color):
screentext = font.render(msg, True, color)
gamedisplay.blit(screentext , [sizex / 2, sizey / 2])
#Initialization
gamedisplay = pygame.display.set_mode((sizex, sizey))
pygame.display.set_caption(windowtitle)
#Game Loop
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_w:
rect1ychange -= 1
elif event.key == pygame.K_a:
rect1xchange -= 1
elif event.key == pygame.K_s:
rect1ychange += 1
elif event.key == pygame.K_d:
rect1xchange += 1
if event.type == pygame.KEYUP:
if event.key == pygame.K_w:
rect1ychange = 0
elif event.key == pygame.K_a:
rect1xchange = 0
elif event.key == pygame.K_s:
rect1ychange = 0
elif event.key == pygame.K_d:
rect1xchange = 0
if rect1y > 650:
rect1y = 650
if rect1x > 950:
rect1x = 950
if rect1y < 0:
rect1y = 0
if rect1x < 0:
rect1x = 0
rect1x += rect1xchange
rect1y += rect1ychange
messagetoscreen("HAPPY", red)
gamedisplay.fill(white)
pygame.draw.rect(gamedisplay, green, (rect1x, rect1y, rect1sizex, rect1sizey))
pygame.display.update()
clock.tick(fps)
我想知道如何修复我的功能,以及其他任何可能导致错误的内容。
答案 0 :(得分:0)
答案是我在用白色填充游戏显示之前将文本显示在屏幕上。记住在绘制背景后blit文本。
这是绘制图形的代码 在while循环中:
gamedisplay.fill(white)
pygame.draw.rect(gamedisplay, green, (rect1x, rect1y, rect1sizex, rect1sizey))
messagetoscreen("HAPPY", red)