python/pygame 挑战魂斗罗 笔记(二)

发布于:2024-04-19 ⋅ 阅读:(31) ⋅ 点赞:(0)

一、建立地面碰撞体:

现在主角Bill能够站立在游戏地图的地面,是因为我们初始化的时候把Bill的位置固定了self.rect.y = 250。而不是真正的站在地图的地面上。

背景地图是一个完整的地图,没有地面、台阶的概念,就无法通过碰撞检测来实现玩家角色在各台阶地面上的移动跳跃,可以考虑在PS中把地面、台阶给提取出来,让角色可以通过碰撞检测来实现,但这需要重新PS中修改地图,并在代码中加载好多个图片。

这里采用的是在所有地面、台阶的位置画一条线,暂时就叫地面碰撞体吧。然后实现主角Bill和这些地面碰撞体发生碰撞,从而让主角Bill能够站在这个碰撞体上面。

1、先写出地面碰撞体的类:

在ContraMap.py中增加CollideGround类:

class CollideGround(pygame.sprite.Sprite):
    def __init__(self, length, x, y):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface((length * Constant.MAP_SCALE, 3))
        self.image.fill((255, 0, 0))
        self.rect = self.image.get_rect()
        self.rect.x = x * Constant.MAP_SCALE - Constant.WIDTH * 2
        self.rect.y = y * Constant.MAP_SCALE

这个类很简单,就是一个3像素高的红色矩形。因为地图放大了3倍,同时我们在主角出现,也就是地图走到- Constant.WIDTH * 2的时候再把碰撞体画出来,把这些因素考虑进去,可以使在PS中测量碰撞体长度、坐标位置更方便一点。

2、测量并定义地面碰撞体:

在Config.py中增加一些存放碰撞体的组,测量可以在PS或其它画图软件中进行:

    collider = pygame.sprite.Group()
    collider83 = pygame.sprite.Group()
    collider115 = pygame.sprite.Group()
    collider146 = pygame.sprite.Group()
    collider163 = pygame.sprite.Group()
    collider178 = pygame.sprite.Group()
    collider211 = pygame.sprite.Group()
    collider231 = pygame.sprite.Group()

这里先测量并定义出前面的部分,其实有collider一个组就行,这里按照y坐标的位置分了很多组只是为了测量、加载的时候更清晰一点,不容易乱,最后统一加入collider组。

Variable.collider115.add(
    CollideGround(736, 832, 115)
)

Variable.collider146.add(
    CollideGround(97, 959, 146),
    CollideGround(66, 1215, 146)
)

Variable.collider163.add(
    CollideGround(95, 1440, 163)
)

Variable.collider178.add(
    CollideGround(32, 1055, 178),
    CollideGround(32, 1151, 178)
)

Variable.collider211.add(
    CollideGround(63, 1088, 211),
    CollideGround(63, 1407, 211)
)

Variable.collider.add(Variable.collider83, Variable.collider115, Variable.collider146, Variable.collider163,
                      Variable.collider178, Variable.collider211, Variable.collider231)
3、修改StateMap类的update方法,在Varibale.step==2时,加入all_sprites组进行绘制。
    def update(self):
        if self.order == 2:
            print('纵向地图')
        else:
            if Variable.step == 0 and self.rect.x >= -Constant.WIDTH:
                self.rect.x -= 10
            if Variable.step == 1 and self.rect.x > -Constant.WIDTH * 2:
                self.rect.x -= 10
                if self.rect.x == -Constant.WIDTH * 2:
                    Variable.step = 2
                    Variable.all_sprites.add(Variable.collider)

这样就得到了这张带红色地面线的图片。 

二、主角Bill移动+跳跃:

1、给主角Bill定义移动、跳跃、下落三种状态。

初始状态为下落,也就是主角从画面外降落,碰撞到地面碰撞体后把碰撞体的top值赋值给Bill的bottom,实现停止下落。

            self.falling = True
            self.jumping = False
            self.moving = False
2、常量中增加x、y两个方向的移动速度,以及模拟重力。
    SPEED_X = 3
    SPEED_Y = -10
    GRAVITY = 0.5
 3、先定义移动、跳跃、下落、动作图片序列四个方法:

移动需要考虑三种情况:

第一是开始直到人物走到屏幕中间,这部分是主角Bill正常移动;

第二是Bill移动到游戏窗口中间时,Bill需要一直停留在中间,而Bill的向前移动实际是地图向后移动,这里设立了一个x = self.rect.centerx - Constant.WIDTH / 2,也就是Bill移动超过游戏窗口中间的距离,然后让all_sprites中的所有精灵,包括Bill都向后移动这个距离。反过来也一样。

第三是地图移动到边界时就不能继续移动了,这时需要Bill继续移动,并保证不能走出游戏窗口。这里为了控制地图,需要获取地图的rect属性。网上搜了很多一直没找到怎么从all_sprites精灵组中获取指定精灵的方法,搞了好久,后来终于想到给地图单独一个组Varible.map_storage,通过遍历这个组来获取地图以及地图的rect属性。

    def move(self):
        if self.direction == 'right' and self.rect.right <= Constant.WIDTH - 80 * Constant.MAP_SCALE:
            self.rect.x += Constant.SPEED_X
            if self.rect.centerx >= Constant.WIDTH / 2:
                x = self.rect.centerx - Constant.WIDTH / 2
                for j in Variable.map_storage:
                    if j.rect.right >= Constant.WIDTH:
                        for i in Variable.all_sprites:
                            i.rect.x -= x

        elif self.direction == 'left' and self.rect.left >= 40 * Constant.MAP_SCALE:
            self.rect.x -= Constant.SPEED_X
            if self.rect.centerx <= Constant.WIDTH / 2:
                x = Constant.WIDTH / 2 - self.rect.centerx
                for j in Variable.map_storage:
                    if j.rect.left <= -Constant.WIDTH * 2:
                        for i in Variable.all_sprites:
                            i.rect.x += x

图片序列:就是正常设定时间钟,然后image_order在0-5中间循环。

跳跃:先设定SPEED_Y为-10,GRAVITY为0.5,这样向上移动SPPED_Y的值逐渐减小,直到SPPED_Y==0,调整jumping和falling状态,并将SPEED_Y恢复为-10,完成一次跳跃。

下落:简单的写了一个10倍Constant.GRAVITY 下落。

    def order_loop(self):
        self.now_time = pygame.time.get_ticks()
        if self.now_time - self.last_time >= 100:
            self.image_order += 1
            if self.image_order > 5:
                self.image_order = 0
            self.last_time = self.now_time

    def jump(self):
        Constant.SPEED_Y += Constant.GRAVITY
        self.rect.y += Constant.SPEED_Y
        if Constant.SPEED_Y == 0:
            self.jumping = False
            self.falling = True
            Constant.SPEED_Y = -10

    def fall(self):
        self.rect.y += Constant.GRAVITY * 10
4、修改update方法,实现跳下功能:

前后移动以及跳跃都可以根据设定的按键来修改状态以及图片类型。

重点是向下跳跃,向下跳跃实现的思路,是将Bill的状态设定为一直处于下落状态(跳跃时除外),让他与地面碰撞体一直碰撞,并将碰撞体的top值赋值给self.floor变量,然后向下跳的时候(s和j键同时按下),将该碰撞体从collider中删除并用sprite_storage组暂时寄存,实现Bill往下落:

            if key_pressed[pygame.K_s] and key_pressed[pygame.K_j]:
                self.image_type = 'oblique_down'
                Variable.collider.remove(l[0])
                Variable.sprite_storage.add(l[0])

等到Bill的rect.top值大于self.floor时,也就是完全超过哪条地面线的位置,再把该碰撞体加载回来,否则就会出现跳下一半就检测到碰撞,被拉回原来地面的情况。加回碰撞体后,就可以实现跳回来的动作。

        if self.rect.top >= self.floor:
            for i in Variable.sprite_storage:
                Variable.collider.add(i)
                Variable.sprite_storage.remove(i)

其它的部分,就是按照按键以及按键组合,调整各自的状态参数就可以了。

把按键监测写到碰撞后的for循环里面,是想控制主角Bill必须是与碰撞体接触后才能进行移动及跳跃等操作,否则在刚开始下落的时候就可以移动了,也会出现半空中继续跳跃的情况。 

    def update(self):
        self.image = self.image_dict[self.image_type][self.image_order]
        if self.direction == 'left':
            self.image = pygame.transform.flip(self.image, True, False)

        if self.rect.top >= self.floor:
            for i in Variable.sprite_storage:
                Variable.collider.add(i)
                Variable.sprite_storage.remove(i)

        key_pressed = pygame.key.get_pressed()
        if self.falling:
            self.fall()

        if self.jumping:
            self.jump()

        if self.moving:
            self.move()

        self.order_loop()

        collider_ground = pygame.sprite.groupcollide(Variable.player_sprites, Variable.collider, False, False)
        for p, l in collider_ground.items():
            self.floor = l[0].rect.top
            p.rect.bottom = self.floor
            if key_pressed[pygame.K_d]:
                self.direction = 'right'
                self.moving = True
                if key_pressed[pygame.K_w]:
                    self.image_type = 'oblique_up'
                elif key_pressed[pygame.K_s]:
                    self.image_type = 'oblique_down'
                elif key_pressed[pygame.K_j]:
                    self.image_type = 'jump'
                    self.jumping = True
                    self.falling = False
                else:
                    self.image_type = 'run'
            elif key_pressed[pygame.K_a]:
                self.direction = 'left'
                self.moving = True
                if key_pressed[pygame.K_w]:
                    self.image_type = 'oblique_up'
                elif key_pressed[pygame.K_s]:
                    self.image_type = 'oblique_down'
                elif key_pressed[pygame.K_j]:
                    self.image_type = 'jump'
                    self.jumping = True
                    self.falling = False
                else:
                    self.image_type = 'run'

            elif key_pressed[pygame.K_w]:
                self.image_type = 'up'
                self.moving = False

            elif key_pressed[pygame.K_s]:
                self.image_type = 'down'
                self.moving = False

            else:
                self.image_type = 'stand'
                self.moving = False

            if key_pressed[pygame.K_s] and key_pressed[pygame.K_j]:
                self.image_type = 'oblique_down'
                Variable.collider.remove(l[0])
                Variable.sprite_storage.add(l[0])

这一部分功能的实现费了挺长时间,前前后后改了很多次才终于完成,虽然总觉得跳的有点别扭,但总算是实现了跳下跳回的功能,就这样吧。

三、现阶段各文件完整代码:

1、Contra.py
# Contra.py
import sys
import pygame

import ContraBill
import ContraMap
from Config import Constant, Variable


def control():
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            Variable.game_start = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_RETURN:
                Variable.step = 1


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()
            if Variable.stage == 1:
                ContraMap.new_stage()
                ContraBill.new_player()

            if Variable.stage == 2:
                pass

            if Variable.stage == 3:
                pass

            Variable.all_sprites.draw(self.game_window)
            Variable.all_sprites.update()

            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()
2、ContraMap.py

这里把第一关的全部地面碰撞体都测量并加载出来。

# ContraMap.py
import os
import pygame

from Config import Constant, Variable


class StageMap(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

    def update(self):
        if self.order == 2:
            print('纵向地图')
        else:
            if Variable.step == 0 and self.rect.x >= -Constant.WIDTH:
                self.rect.x -= 10
            if Variable.step == 1 and self.rect.x > -Constant.WIDTH * 2:
                self.rect.x -= 10
                if self.rect.x == -Constant.WIDTH * 2:
                    Variable.step = 2
                    Variable.all_sprites.add(Variable.collider)


def new_stage():
    if Variable.map_switch:
        stage_map = StageMap(Variable.stage - 1)
        Variable.all_sprites.add(stage_map)
        Variable.map_storage.add(stage_map)
        Variable.map_switch = False


class CollideGround(pygame.sprite.Sprite):
    def __init__(self, length, x, y):
        pygame.sprite.Sprite.__init__(self)
        self.image = pygame.Surface((length * Constant.MAP_SCALE, 3))
        self.image.fill((255, 0, 0))
        self.rect = self.image.get_rect()
        self.rect.x = x * Constant.MAP_SCALE - Constant.WIDTH * 2
        self.rect.y = y * Constant.MAP_SCALE


Variable.collider83.add(
    CollideGround(511, 2176, 83),
    CollideGround(161, 2847, 83),
    CollideGround(64, 3296, 83)
)

Variable.collider115.add(
    CollideGround(736, 832, 115),
    CollideGround(128, 1568, 115),
    CollideGround(160, 1695, 115),
    CollideGround(128, 1856, 115),
    CollideGround(256, 1984, 115),
    CollideGround(224, 2656, 115),
    CollideGround(65, 3040, 115),
    CollideGround(64, 3264, 115),
    CollideGround(64, 3392, 115),
    CollideGround(128, 3808, 115)
)

Variable.collider146.add(
    CollideGround(97, 959, 146),
    CollideGround(66, 1215, 146),
    CollideGround(225, 2400, 146),
    CollideGround(96, 2976, 146),
    CollideGround(64, 3136, 146),
    CollideGround(160, 3424, 146),
    CollideGround(64, 3744, 146),
    CollideGround(32, 3936, 146)
)

Variable.collider163.add(
    CollideGround(95, 1440, 163),
    CollideGround(64, 2304, 163),
    CollideGround(32, 2912, 163),
    CollideGround(32, 2328, 163),
    CollideGround(32, 3328, 163),
    CollideGround(97, 3840, 163)
)

Variable.collider178.add(
    CollideGround(32, 1055, 178),
    CollideGround(32, 1151, 178),
    CollideGround(65, 2720, 178),
    CollideGround(64, 2816, 178),
    CollideGround(96, 3168, 178),
    CollideGround(63, 3648, 178),
    CollideGround(32, 3969, 178)
)

Variable.collider211.add(
    CollideGround(63, 1088, 211),
    CollideGround(63, 1407, 211),
    CollideGround(97, 2208, 211),
    CollideGround(192, 2528, 211),
    CollideGround(33, 3135, 211),
    CollideGround(33, 3295, 211),
    CollideGround(97, 3520, 211),
    CollideGround(242, 3807, 211)
)

Variable.collider.add(Variable.collider83, Variable.collider115, Variable.collider146, Variable.collider163,
                      Variable.collider178, Variable.collider211, Variable.collider231)
3、ContraBill.py
# ContraBill.py
import os
import pygame

from Config import Constant, Variable


class Bill(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)
        self.image_dict = {
            'be_hit': [],
            'down': [],
            'jump': [],
            'oblique_down': [],
            'oblique_up': [],
            'run': [],
            'shoot': [],
            'stand': [],
            'up': []
        }
        for i in range(6):
            for key in self.image_dict:
                image = pygame.image.load(os.path.join('image', 'bill', str(key), str(key) + str(i + 1) + '.png'))
                rect = image.get_rect()
                image_scale = pygame.transform.scale(
                    image, (rect.width * Constant.PLAYER_SCALE, rect.height * Constant.PLAYER_SCALE))
                self.image_dict[key].append(image_scale)

            self.image_order = 0
            self.image_type = 'stand'

            self.image = self.image_dict[self.image_type][self.image_order]
            self.rect = self.image.get_rect()
            self.rect.x = 100
            self.rect.y = 100
            self.direction = 'right'

            self.now_time = 0
            self.last_time = 0

            self.falling = True
            self.jumping = False
            self.moving = False
            self.floor = 0

    def update(self):
        self.image = self.image_dict[self.image_type][self.image_order]
        if self.direction == 'left':
            self.image = pygame.transform.flip(self.image, True, False)

        if self.rect.top >= self.floor:
            for i in Variable.sprite_storage:
                Variable.collider.add(i)
                Variable.sprite_storage.remove(i)

        key_pressed = pygame.key.get_pressed()
        if self.falling:
            self.fall()

        if self.jumping:
            self.jump()

        if self.moving:
            self.move()

        self.order_loop()

        collider_ground = pygame.sprite.groupcollide(Variable.player_sprites, Variable.collider, False, False)
        for p, l in collider_ground.items():
            self.floor = l[0].rect.top
            p.rect.bottom = self.floor
            if key_pressed[pygame.K_d]:
                self.direction = 'right'
                self.moving = True
                if key_pressed[pygame.K_w]:
                    self.image_type = 'oblique_up'
                elif key_pressed[pygame.K_s]:
                    self.image_type = 'oblique_down'
                elif key_pressed[pygame.K_j]:
                    self.image_type = 'jump'
                    self.jumping = True
                    self.falling = False
                else:
                    self.image_type = 'run'
            elif key_pressed[pygame.K_a]:
                self.direction = 'left'
                self.moving = True
                if key_pressed[pygame.K_w]:
                    self.image_type = 'oblique_up'
                elif key_pressed[pygame.K_s]:
                    self.image_type = 'oblique_down'
                elif key_pressed[pygame.K_j]:
                    self.image_type = 'jump'
                    self.jumping = True
                    self.falling = False
                else:
                    self.image_type = 'run'

            elif key_pressed[pygame.K_w]:
                self.image_type = 'up'
                self.moving = False

            elif key_pressed[pygame.K_s]:
                self.image_type = 'down'
                self.moving = False

            else:
                self.image_type = 'stand'
                self.moving = False

            if key_pressed[pygame.K_s] and key_pressed[pygame.K_j]:
                self.image_type = 'oblique_down'
                Variable.collider.remove(l[0])
                Variable.sprite_storage.add(l[0])

    def order_loop(self):
        self.now_time = pygame.time.get_ticks()
        if self.now_time - self.last_time >= 100:
            self.image_order += 1
            if self.image_order > 5:
                self.image_order = 0
            self.last_time = self.now_time

    def move(self):
        if self.direction == 'right' and self.rect.right <= Constant.WIDTH - 80 * Constant.MAP_SCALE:
            self.rect.x += Constant.SPEED_X
            if self.rect.centerx >= Constant.WIDTH / 2:
                x = self.rect.centerx - Constant.WIDTH / 2
                for j in Variable.map_storage:
                    if j.rect.right >= Constant.WIDTH:
                        for i in Variable.all_sprites:
                            i.rect.x -= x

        elif self.direction == 'left' and self.rect.left >= 40 * Constant.MAP_SCALE:
            self.rect.x -= Constant.SPEED_X
            if self.rect.centerx <= Constant.WIDTH / 2:
                x = Constant.WIDTH / 2 - self.rect.centerx
                for j in Variable.map_storage:
                    if j.rect.left <= -Constant.WIDTH * 2:
                        for i in Variable.all_sprites:
                            i.rect.x += x

    def jump(self):
        Constant.SPEED_Y += Constant.GRAVITY
        self.rect.y += Constant.SPEED_Y
        if Constant.SPEED_Y == 0:
            self.jumping = False
            self.falling = True
            Constant.SPEED_Y = -10

    def fall(self):
        self.rect.y += Constant.GRAVITY * 10


def new_player():
    if Variable.step == 2 and Variable.player_switch:
        bill = Bill()
        Variable.all_sprites.add(bill)
        Variable.player_sprites.add(bill)
        Variable.player_switch = False
4、Config.py
# Config.py
import pygame


class Constant:
    WIDTH = 1200
    HEIGHT = 720
    FPS = 60

    MAP_SCALE = 3
    PLAYER_SCALE = 2.5

    SPEED_X = 3
    SPEED_Y = -10
    GRAVITY = 0.5


class Variable:
    all_sprites = pygame.sprite.Group()
    player_sprites = pygame.sprite.Group()

    collider = pygame.sprite.Group()
    collider83 = pygame.sprite.Group()
    collider115 = pygame.sprite.Group()
    collider146 = pygame.sprite.Group()
    collider163 = pygame.sprite.Group()
    collider178 = pygame.sprite.Group()
    collider211 = pygame.sprite.Group()
    collider231 = pygame.sprite.Group()

    sprite_storage = pygame.sprite.Group()
    map_storage = pygame.sprite.Group()

    game_start = True
    map_switch = True
    player_switch = True

    stage = 1
    step = 0

以上代码完成,我们的主角Bill终于可以连跑带跳游览整个地图,并终于站在了第一关的关头。