You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
78 lines
2.1 KiB
78 lines
2.1 KiB
import random
|
|
import time
|
|
import pygame
|
|
from pygame.constants import *
|
|
|
|
|
|
class HeroPlane(object):
|
|
def __init__(self, screen):
|
|
# 4.创建一个玩家飞机图片,当做真正的飞机
|
|
self.player = pygame.image.load("./feiji/hero1.png")
|
|
|
|
# 定义飞机的坐标
|
|
self.x = 480 / 2 - 100 / 2
|
|
self.y = 600
|
|
|
|
# 飞机速度
|
|
self.speed = 15
|
|
|
|
# 记录当前的窗口对象
|
|
self.screen = screen
|
|
|
|
|
|
|
|
def key_control(self):
|
|
# 监听键盘事件
|
|
key_pressed = pygame.key.get_pressed()
|
|
|
|
if key_pressed[K_w] or key_pressed[K_UP]:
|
|
self.y -= self.speed
|
|
if key_pressed[K_s] or key_pressed[K_DOWN]:
|
|
self.y += self.speed
|
|
if key_pressed[K_a] or key_pressed[K_LEFT]:
|
|
self.x -= self.speed
|
|
if key_pressed[K_d] or key_pressed[K_RIGHT]:
|
|
self.x += self.speed
|
|
if key_pressed[K_SPACE]:
|
|
pass
|
|
|
|
def display(self):
|
|
# 5将飞机图片贴到窗口中
|
|
self.screen.blit(self.player, (self.x, self.y))
|
|
|
|
def main():
|
|
# 1. 创建一个窗口,用来显示内容
|
|
screen = pygame.display.set_mode((480, 852), 0, 32)
|
|
# 2. 创建一个和窗口大小的图片,用来充当背景
|
|
background = pygame.image.load("./feiji/background.png")
|
|
# 创建一个飞机的对象,注意不要忘记传窗口
|
|
player = HeroPlane(screen)
|
|
|
|
|
|
# 设定需要显示的背景图
|
|
while True:
|
|
# 3将背景图片贴到窗口中
|
|
screen.blit(background, (0, 0))
|
|
|
|
# 遍历所有的事件
|
|
for event in pygame.event.get():
|
|
# 判断事件类型如果是pygame的退出
|
|
if event.type == QUIT:
|
|
# 执行pygame退出
|
|
pygame.quit()
|
|
# python程序的退出
|
|
exit()
|
|
|
|
# 执行飞机的按键监听
|
|
player.key_control()
|
|
# 飞机的显示
|
|
player.display()
|
|
|
|
|
|
# 更新需要显示的内容
|
|
pygame.display.update()
|
|
time.sleep(0.01)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main() |