代码功能:
创建一个坦克大战游戏项目是一个很好的实践项目,它可以帮助你学习Python编程、面向对象编程、事件处理、图形用户界面等技能。
以下是一个使用Python的pygame库来实现坦克大战游戏的完整代码。
我们创建了一个窗口,加载了坦克和子弹的图像,并允许玩家使用方向键来控制两个坦克的移动,以及空格键来射击子弹。子弹在屏幕上飞行,如果超出屏幕边界,则消失.
软件:PyCharm
语言:python
代码下载:edacode.com 请使用浏览器访问
工程文件
程序文件
运行效果
部分代码展示:
mport pygame # 子弹类 class Bullet(pygame.sprite.Sprite): def __init__(self): pygame.sprite.Sprite.__init__(self) # 子弹四个方向(上下左右) self.bullets = ['./images/bullet/bullet_up.png', './images/bullet/bullet_down.png', './images/bullet/bullet_left.png', './images/bullet/bullet_right.png'] # 子弹方向(默认向上) self.direction_x, self.direction_y = 0, -1 self.bullet = pygame.image.load(self.bullets[0]) self.rect = self.bullet.get_rect() # 在坦克类中再赋实际值 self.rect.left, self.rect.right = 0, 0 # 速度 self.speed = 6 # 是否存活 self.being = False # 是否为加强版子弹(可碎钢板) self.stronger = False # 改变子弹方向 def turn(self, direction_x, direction_y): self.direction_x, self.direction_y = direction_x, direction_y if self.direction_x == 0 and self.direction_y == -1: self.bullet = pygame.image.load(self.bullets[0]) elif self.direction_x == 0 and self.direction_y == 1: self.bullet = pygame.image.load(self.bullets[1]) elif self.direction_x == -1 and self.direction_y == 0: self.bullet = pygame.image.load(self.bullets[2]) elif self.direction_x == 1 and self.direction_y == 0: self.bullet = pygame.image.load(self.bullets[3]) else: raise ValueError('Bullet class -> direction value error.') # 移动 def move(self): self.rect = self.rect.move(self.speed*self.direction_x, self.speed*self.direction_y) # 到地图边缘后消失 if (self.rect.top < 3) or (self.rect.bottom > 630 - 3) or (self.rect.left < 3) or (self.rect.right > 630 - 3): self.being = False