前面完成了飞机和坦克两个经典游戏的基本功能,想挑战一下魂斗罗?这里的难点感觉是玩家的上下左右移动和变换动作,还有跳跃、趴下、射击等,尤其是跳到地面下的各个台阶部分,有点复杂。
下面开始我的魂斗罗1.0的挑战,看看能不能实现。
一、建立一个配置文件Config.py。
这一次将代码想模块化管理,将所有的全局常量、变量都统一归口到这个配置文件中,方便调用。
网络上找到的背景地图图片高度为240像素,这里将游戏窗口设定为720像素高,地图放大3倍。
# Config.py
import pygame
class Constant:
WIDTH = 1200
HEIGHT = 720
FPS = 60
MAP_SCALE = 3
class Variable:
all_sprites = pygame.sprite.Group()
game_start = True
二、建立主循环文件Contra.py
文件主要包括键盘控制、游戏窗口、游戏时钟设定以及主循环
# Contra.py
import sys
import pygame
from Config import Constant, Variable
def control():
for event in pygame.event.get():
if event.type == pygame.QUIT:
Variable.game_start = False
class Main:
def __init__(self):
pygame.init()
self.game_window = pygame.display.set_mode((Constant.WIDTH, Constant.HEIGHT))
self.clock = pygame.time.Clock()
def game_loop(self):
while Variable.game_start:
control()
self.clock.tick(Constant.FPS)
pygame.display.set_caption(f'魂斗罗 1.0 {self.clock.get_fps():.2f}')
pygame.display.update()
pygame.quit()
sys.exit()
if __name__ == '__main__':
main = Main()
main.game_loop()
三、建立ContraMap.py文件:
1、先载入背景地图
素材一共有8个不同阶段地图,按照stage1-8的方式命名,建立一个image_list列表。每通过一关,增加stage值进入下一关地图。
# ContraMap.py
import os
import pygame
from Config import Constant, Variable
class Stage(pygame.sprite.Sprite):
def __init__(self, order):
pygame.sprite.Sprite.__init__(self)
self.image_list = []
self.order = order
for i in range(1, 9):
image = pygame.image.load(os.path.join('image', 'map', 'stage' + str(i) + '.png'))
rect = image.get_rect()
image = pygame.transform.scale(image, (rect.width * Constant.MAP_SCALE, rect.height * Constant.MAP_SCALE))
self.image_list.append(image)
self.image = self.image_list[self.order]
self.rect = self.image.get_rect()
self.rect.x = 0
self.rect.y = 0
self.speed = 0
2、地图移动
魂斗罗的背景地图移动相对复杂一点,不是简单的重复移动。
素材中只有stage3是纵向移动的,其它是横向移动的,这里先不管stage3 ,先考虑横向移动方式。
横向移动方式设计为三步:先是一段英文