import pygame # 导入pygame包
pygame.init() # 初始化游戏
win_x = 800 # 窗口宽
win_y = 800 # 窗口高
# 创建窗口
win = pygame.display.set_mode((win_x, win_y))
# 游戏标题
pygame.display.set_caption("按下键盘不放控制")
# 背景颜色
win.fill((255, 255, 255))
# 静态小鸡
ji = pygame.image.load('image/快乐小鸡右.png')
ji_l = pygame.image.load("image/快乐小鸡.png")
jidong = ji
jix, jiy = 200, 300
win.blit(ji, (jix, jiy))
# 刷新界面
pygame.display.flip()
# 用一个变量设置是否移动,初始值为Fasle,当按下键盘某键是为Treu,便执行移动
is_move = False
x_s = 0
y_s = 0
# 循环游戏
while True:
if is_move == True:
win.fill((255, 255, 255))
jix += x_s
jiy += y_s
win.blit(jidong, (jix, jiy))
pygame.display.update()
# 检测事件的发生
for evt in pygame.event.get():
# 判断事件类型
if evt.type == pygame.QUIT:
exit()
# 判断键盘被按下事件
elif evt.type == pygame.KEYDOWN:
if evt.unicode == "w":
is_move = True
x_s = 0
y_s = -1
elif evt.unicode == "s":
x_s = 0
y_s = 1
is_move = True
elif evt.unicode == "a":
is_move = True
jidong = ji_l
x_s = -1
y_s = 0
elif evt.unicode == "d":
is_move = True
jidong = ji
x_s = 1
y_s = 0
elif evt.type == pygame.KEYUP:
is_move = False
有不理解的欢迎评论区留言,我会一 一解答