[英]player.update wont take key input and make character move pygame
I am new to pygame and this code I created by following a tutorial is not working.我是 pygame 的新手,我按照教程创建的这段代码不起作用。 The white box i made on the screen should be moving with my arrow keys but its not.我在屏幕上制作的白框应该会随着我的箭头键移动,但事实并非如此。 Does anyone know why?有谁知道为什么? Also can someone explain what self means in the class and defs?也有人可以解释 self 在 class 和 defs 中的含义吗?
import pygame
from pygame.locals import (
K_UP,
K_DOWN,
K_LEFT,
K_RIGHT,
K_ESCAPE,
KEYDOWN,
QUIT,
)
pygame.init()
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
#Define a player object by extending pygame.sprite.Sprite
# The surface drawn on the screen is now an attribute of Player
class Player(pygame.sprite.Sprite):
def __init__(self):
super(Player,self).__init__()
self.surf = pygame.Surface((75,25))
self.surf.fill((255,255,255))
self.rect = self.surf.get_rect()
def update(self, pressed_keys):
if pressed_keys[K_UP]:
self.rect.move_ip(0,-5)
if pressed_keys[K_DOWN]:
self.rect.move_ip(0,5)
if pressed_keys[K_LEFT]:
self.rect.move_ip(-5,0)
if pressed_keys[K_RIGHT]:
self.rect.move_ip(5,0)
#Instantiate player
pygame.init()
player = Player()
#keeps main loop running
running = True
#main loop
while running:
for event in pygame.event.get():
#Did user hit a key?
if event.type == KEYDOWN:
# Was it the escape key? if so, exit loop
if event.key == K_ESCAPE:
running = False
elif event.type == QUIT:
running = False
pressed_keys = pygame.key.get_pressed()
player.update(pressed_keys)
screen.fill((0,0,0))
screen.blit(player.surf,(SCREEN_WIDTH/2,SCREEN_HEIGHT/2))
pygame.display.flip()
I tried to make the block move by clicking the arrow keys.我试图通过单击箭头键来移动块。
You always draw the player in the center of the screen:你总是在屏幕中央绘制玩家:
screen.blit(player.surf,(SCREEN_WIDTH/2,SCREEN_HEIGHT/2))
You have to draw the player at player.rect
:您必须在player.rect
处绘制玩家:
screen.blit(player.surf, player.rect)
However, since you use pygame.sprite.Sprite
you should also use pygame.sprite.Group
and you should limit the frames per second with pygame.time.Clock.tick
:但是,由于您使用pygame.sprite.Sprite
您还应该使用pygame.sprite.Group
并且您应该使用pygame.time.Clock.tick
限制每秒的帧数:
clock = pygame.time.Clock()
player = Player()
spriteGroup = pygame.sprite.Group()
spriteGroup.add(player)
running = True
while running:
clock.tick(60)
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
running = False
elif event.type == QUIT:
running = False
pressed_keys = pygame.key.get_pressed()
player.update(pressed_keys)
screen.fill((0,0,0))
spriteGroup.draw(screen)
pygame.display.flip()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.