以下是部分代码预览:
"""没有定义类通过键盘移动角色核心代码示例.py,这是没有定义类的一个程序,它通过按键检测,控制一个矩形移动。"""
import pygame
BLACK = (0, 0, 0)
CYAN = (0, 255, 255)
SCREENSIZE = [800, 600]
# 实始化pygame引擎
pygame.init()
# 创建屏幕,它是一个图层
screen = pygame.display.set_mode(SCREENSIZE)
# 设置窗口标题
pygame.display.set_caption('通过键盘移动角色示例_作者:李兴球')
# 创建方块,用一个surface代表它
square = pygame.Surface([15, 15])
square.fill(CYAN)
square_rect = square.get_rect()
square_rect.center = SCREENSIZE[0]//2,SCREENSIZE[1]//2
clock = pygame.time.Clock()
done = False
while not done:
#遍历每一个发生的事件
for event in pygame.event.get():
if event.type == pygame.QUIT:done = True
# 否则如果按键,则再判断具体按哪个键来决定
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
square_rect.x -= 15
elif event.key == pygame.K_RIGHT:
square_rect.x += 15
elif event.key == pygame.K_UP:
square_rect.y -= 15
elif event.key == pygame.K_DOWN:
square_rect.y += 15
# -- 重画所有对象
# 首先清屏幕为黑色
screen.fill(BLACK)
# 画 角色
screen.blit(square,square_rect)
# 显示
pygame.display.flip()
# fps为40
clock.tick(40)
pygame.quit()
如需要查看完整代码,请
需要浏览更多吗?
成为会员后,登陆才能继续浏览!联系微信scratch8即可办理会员。
(会员专属:能浏览所有文章,下载所有带链接的Python资源。)

