这篇文章主要讲解了“怎么用Python代码实现简单飞机大战游戏”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“怎么用Python代码实现简单飞机大战游戏”吧!
功能
玩家飞机可以移动,可以发射子弹,敌机随机产生,自由坠落。未添加击落敌机的功能。主要用来练习类的封装与继承。
源码
# -*- coding=utf-8 -*- import pygame, random from pygame.locals import * class Base(object): def __init__(self, x, y, screen): self.screen = screen self.x = x self.y = y class Player(Base): def __init__(self): super().__init__(210, 600, screen) self.playerName = "./feiji/hero.gif" self.player = pygame.image.load(self.playerName).convert() self.bullet_list = [] def display(self): self.screen.blit(self.player, (self.x, self.y)) for bullet in self.bullet_list: bullet.display() bullet.mov() def move_left(self): self.x -= 10 def move_right(self): self.x += 10 def move_up(self): self.y -= 10 def move_down(self): self.y += 10 def shot(self): bullet = Bullet() self.bullet_list.append(bullet) class Bullet(Base): def __init__(self): super().__init__(player.x+40, player.y-20, screen) self.bulletName = "./feiji/bullet-3.gif" self.bullet = pygame.image.load(self.bulletName).convert() def display(self): self.screen.blit(self.bullet, (self.x, self.y)) def mov(self): self.y -= 10 class Enemy(Base): def __init__(self): super().__init__(random.randint(1, 10)*40, 0, screen) self.enemyName = "./feiji/enemy-1.gif" self.enemy = pygame.image.load(self.enemyName).convert() self.enemy_list = [] self.i = 0 def mov(self): self.y += 2 class EnemyArea(Enemy): def display(self): # 每隔一段时间创建一架敌机 if self.i % 80 == 0: new_enemy = Enemy() self.enemy_list.append(new_enemy) self.i += 1 for enemy in self.enemy_list: self.screen.blit(enemy.enemy, (enemy.x, enemy.y)) enemy.mov() if __name__ == "__main__": # 创建一个窗口,用来显示内容 screen = pygame.display.set_mode((480, 890)) # 创建一个和窗口大小的图片,用来充当背景 background = pygame.image.load("./feiji/background.png").convert() player = Player() enemy = Enemy() enemy_area = EnemyArea() while True: screen.blit(background, (0, 0)) player.display() enemy_area.display() # 判断按键 for event in pygame.event.get(): if event.type == QUIT: exit() elif event.type == KEYDOWN: if event.key == K_a or event.key == K_LEFT: player.move_left() elif event.key == K_d or event.key == K_RIGHT: player.move_right() elif event.key == K_w or event.key == K_UP: player.move_up() elif event.key == K_s or event.key == K_DOWN: player.move_down() elif event.key == K_SPACE: player.shot() elif event.key == K_q: exit() pygame.display.update() pygame.time.delay(10)
结果展示
感谢各位的阅读,以上就是“怎么用Python代码实现简单飞机大战游戏”的内容了,经过本文的学习后,相信大家对怎么用Python代码实现简单飞机大战游戏这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。