import sys
import pygame
WIDTH=800
HEIGHT=600
SIZE=WIDTH,HEIGHT
pygame.init()
screen=pygame.display.set_mode(SIZE)
class Player:
def __init__(self):
self.surf = pygame.Surface((50,50))
self.surf.fill("white")
self.rect=self.surf.get_rect()
# self.rect = self.surf.get_rect()
def move(self):
pressed_key = pygame.key.get_pressed()
if pressed_key[pygame.K_DOWN]:
self.rect.move_ip(0, 10)
# player_rect.top +=10
if pressed_key[pygame.K_UP]:
self.rect.move_ip(0, -10)
# player_rect.top -=10
if pressed_key[pygame.K_RIGHT]:
self.rect.move_ip(10, 0)
# player_rect.right +=10
if pressed_key[pygame.K_LEFT]:
self.rect.move_ip(-10, 0)
# player_rect.left -=10
# 限制玩家在屏幕中移动
if self.rect.right >= WIDTH:
self.rect.right = WIDTH
if self.rect.left <= 0:
self.rect.left = 0
if self.rect.bottom >= HEIGHT:
self.rect.bottom = HEIGHT
if self.rect.top <= 0:
self.rect.top = 0
def draw(self):
screen.blit(self.surf,self.rect)
player=Player()
clock=pygame.time.Clock()
while True:
for event in pygame.event.get():
if event.type==pygame.QUIT:
pygame.quit()
sys.exit()
# if event.type==pygame.KEYDOWN and event.key==pygame.K_DOWN:
# player_rect.top +=10
# move
player.move()
# draw
screen.fill("black")
player.draw()
pygame.display.flip()
clock.tick(60)
标签:10,小方块,self,画布,小游戏,pygame,key,rect,pressed
From: https://www.cnblogs.com/tellw/p/18550127