问题描述
不要问我在这里想做什么,但是如果我只绘制一个没有类的矩形,请帮忙,它工作正常,但不输出任何内容,甚至没有错误消息。那我应该不上课吗?我对这种东西很糟糕,它告诉我我需要写更多的字,而且我的帖子主要是代码,所以忽略这些东西 rn
import pygame
import os
pygame.init()
FPS=60
SCREEN = pygame.display.set_mode((400,500))
pygame.display.set_caption('test')
x=50
y=450
vel = 3
width = 20
height = 20
walk = pygame.draw.rect(SCREEN,(0,0),(x,y,width,height))
class player(object):
def __init__(self,x,height):
self.x = x
self.y = y
self.width = width
self.height = height
self.vel = 3
def draw(self,SCREEN):
SCREEN.blit (walk,(self.x,self.y))
def rdw():
SCREEN.blit((0,0))
player.draw(SCREEN)
pygame.display.update()
player = player(x,height)
#main loop
running = True
clock = pygame.time.Clock()
while running:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
if keys[pygame.K_a] and player.x > 30 - player.width - player.vel:
x-=player.vel
if keys[pygame.K_d] and player.x < 400 - player.width - player.vel:
x+=player.vel
SCREEN.fill((255,255,255))
pygame.display.update()
pygame.quit()
解决方法
pygame.display.update()
需要缩进到 while running
循环内。还需要在填满屏幕后调用 player.draw 方法。
此外,SCREEN.blit((0,0))
会导致程序崩溃,因为您没有为它提供任何要 blit 的东西。
创建玩家的 pygame.Surface
对象大小,并使用玩家的颜色 fill
它。这是您需要在 Player.draw
中 blit
的对象:
class Player(object):
def __init__(self,x,y,width,height):
# [...]
self.image = pygame.Surface((width,height))
self.image.fill((0,0))
def draw(self,SCREEN):
SCREEN.blit(self.image,(self.x,self.y))
player = Player(x,height)
移动播放器时,需要更改player
(player.x
,player.y
)而不是x
和y
的坐标:
keys = pygame.key.get_pressed()
if keys[pygame.K_a] and player.x > 30 - player.width - player.vel:
player.x -= player.vel
if keys[pygame.K_d] and player.x < 400 - player.width - player.vel:
player.x += player.vel
您必须在清除屏幕后和更新屏幕之前绘制播放器:
SCREEN.fill((255,255,255))
player.draw(SCREEN)
pygame.display.update()
完整示例(关心 Indentation):
import pygame
import os
pygame.init()
FPS=60
SCREEN = pygame.display.set_mode((400,500))
pygame.display.set_caption('test')
x=50
y=450
vel = 3
width = 20
height = 20
class Player(object):
def __init__(self,height):
self.x = x
self.y = y
self.width = width
self.height = height
self.vel = 3
self.image = pygame.Surface((width,0))
def draw(self,height)
#main loop
running = True
clock = pygame.time.Clock()
while running:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
if keys[pygame.K_a] and player.x > 30 - player.width - player.vel:
player.x -= player.vel
if keys[pygame.K_d] and player.x < 400 - player.width - player.vel:
player.x += player.vel
SCREEN.fill((255,255))
player.draw(SCREEN)
pygame.display.update()
pygame.quit()
典型的 PyGame 应用程序循环必须:
- 通过
pygame.event.pump()
或pygame.event.get()
处理事件。 - 根据输入事件和时间(分别为帧)更新游戏状态和对象位置
- 清除整个显示或绘制背景
- 绘制整个场景(
blit
所有对象) - 通过
pygame.display.update()
或pygame.display.flip()
更新显示 - 限制每秒帧数以限制 CPU 使用率