Arcade街机平铺地图多关卡示例

"""
Arcade街机平铺地图多关卡示例,改编:lixingqiu
本程序加载tmx地图,生成关卡,根据角色到达地图最右边界来决定进入下一关的。


"""

import arcade
import os
import time

SPRITE_SCALING = 0.5

SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
SCREEN_TITLE = "Python平铺地图多关卡示例_by lixingqiu"
SPRITE_PIXEL_SIZE = 128
GRID_PIXEL_SIZE = (SPRITE_PIXEL_SIZE * SPRITE_SCALING)

# 视口边距
VIEWPORT_MARGIN_TOP = 60
VIEWPORT_MARGIN_BOTTOM = 60
VIEWPORT_RIGHT_MARGIN = 270
VIEWPORT_LEFT_MARGIN = 270

# Physics
MOVEMENT_SPEED = 5
JUMP_SPEED = 23
GRAVITY = 1.1


class MyGame(arcade.Window):
    """ 继承自窗口的游戏类. """

    def __init__(self):
        """
        初始化方法
        """
        super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)
        
        # 定义角色列表
        self.wall_list = None
        self.player_list = None
        self.coin_list = None

        # 定义玩家相关变量
        self.score = 0
        self.player_sprite = None

        self.physics_engine = None
        self.view_left = 0
        self.view_bottom = 0
        self.game_over = False
        self.last_time = None       # 用来算fps的上次时间变量
        self.frame_count = 0        # 帧计数器
        self.fps_message = None     # fps字符串

        self.level = 1
        self.max_level = 2

    def setup(self):
        """ 设置与初始化变量的值. """

        # 角色列表初始化
        self.player_list = arcade.SpriteList()
        self.coin_list = arcade.SpriteList()

        # 玩家操作的角色实例化,这里是一只昆虫
        self.player_sprite = arcade.Sprite("images/lixingqiu.png", SPRITE_SCALING)

        # 给昆虫设定坐标
        self.player_sprite.center_x = 64
        self.player_sprite.center_y = 64
        self.player_list.append(self.player_sprite)

        self.load_level(self.level) # 加载第一关

        self.game_over = False

    def load_level(self, level):
        # 读取第一关的地图
        my_map = arcade.read_tiled_map(f"level_{level}.tmx", SPRITE_SCALING)

        # 读取不可移动的平台数据阵列'Platforms'是一图层的名称
        map_array = my_map.layers_int_data['Platforms']

        # 计算最右边像素值
        self.end_of_map = (len(map_array[0]) - 1) * GRID_PIXEL_SIZE
        # 从墙生成地图列表
        self.wall_list = arcade.generate_sprites(my_map, 'Platforms', SPRITE_SCALING)
        # 加载平台型的物理引擎
        self.physics_engine = arcade.PhysicsEnginePlatformer(self.player_sprite,
                                                             self.wall_list,
                                                             gravity_constant=GRAVITY)
        # 读取金币阵列,added by lixingqiu
        coins_array = my_map.layers_int_data['Coins']
        # 生成金币列表
        self.coin_list = arcade.generate_sprites(my_map, 'Coins', SPRITE_SCALING)


        # 其它情况,如有背景颜色属性
        if my_map.backgroundcolor:
            arcade.set_background_color(my_map.backgroundcolor)

        # 设置视口以便移动这个矩形
        self.view_left = 0
        self.view_bottom = 0

    def on_draw(self):
        """
        渲染屏幕
        """

        self.frame_count += 1      # 帧计数器

        # 开始渲染屏幕
        arcade.start_render()

        # 画所有的角色
        self.player_list.draw()
        self.wall_list.draw()
        self.coin_list.draw()
        # 计算FPS,帧率
        if self.last_time and self.frame_count % 60 == 0:
            fps = 1.0 / (time.time() - self.last_time) * 60
            self.fps_message = f"FPS: {fps:5.0f}"

        if self.fps_message:
            arcade.draw_text(self.fps_message, self.view_left + 10, self.view_bottom + 40, arcade.color.BLACK, 14)

        if self.frame_count % 60 == 0:
            self.last_time = time.time()

        # 显示距离与游戏结束文本
        distance = self.player_sprite.right
        output = f"Distance: {distance}"
        arcade.draw_text(output, self.view_left + 10, self.view_bottom + 20, arcade.color.BLACK, 14)

        if self.game_over:
            arcade.draw_text("Game Over", self.view_left + 200, self.view_bottom + 200, arcade.color.BLACK, 30)

    def on_key_press(self, key, modifiers):
        """
        当按键时调用此方法
        """
        if key == arcade.key.UP:
            if self.physics_engine.can_jump():
                self.player_sprite.change_y = JUMP_SPEED
        elif key == arcade.key.LEFT:
            self.player_sprite.change_x = -MOVEMENT_SPEED
        elif key == arcade.key.RIGHT:
            self.player_sprite.change_x = MOVEMENT_SPEED

    def on_key_release(self, key, modifiers):
        """
        当松开键时调用此方法
        """
        if key == arcade.key.LEFT or key == arcade.key.RIGHT:
            self.player_sprite.change_x = 0

    def update(self, delta_time):
        """ 移动与游戏的逻辑 """

        if self.player_sprite.right >= self.end_of_map:
            if self.level < self.max_level:
                self.level += 1
                self.load_level(self.level)
                self.player_sprite.center_x = 64
                self.player_sprite.center_y = 64
            else:
                self.game_over = True

        # 角色更新
        if not self.game_over:
            self.physics_engine.update()
        # 角色与金币的碰撞检测,返回列表,列表不为空则把里面的金币删除并加分
        coins_hit = arcade.check_for_collision_with_list(self.player_sprite, self.coin_list)
        for coin in coins_hit:
            coin.kill()
            self.score += 1

        # 跟踪角色的移动以决定是否需要移动视口矩形

        changed = False

        # Scroll left
        left_bndry = self.view_left + VIEWPORT_LEFT_MARGIN
        if self.player_sprite.left < left_bndry:
            self.view_left -= left_bndry - self.player_sprite.left
            changed = True

        # Scroll right
        right_bndry = self.view_left + SCREEN_WIDTH - VIEWPORT_RIGHT_MARGIN
        if self.player_sprite.right > right_bndry:
            self.view_left += self.player_sprite.right - right_bndry
            changed = True

        # Scroll up
        top_bndry = self.view_bottom + SCREEN_HEIGHT - VIEWPORT_MARGIN_TOP
        if self.player_sprite.top > top_bndry:
            self.view_bottom += self.player_sprite.top - top_bndry
            changed = True

        # Scroll down
        bottom_bndry = self.view_bottom + VIEWPORT_MARGIN_BOTTOM
        if self.player_sprite.bottom < bottom_bndry:
            self.view_bottom -= bottom_bndry - self.player_sprite.bottom
            changed = True

        # If we need to scroll, go ahead and do it.
        if changed:
            self.view_left = int(self.view_left)
            self.view_bottom = int(self.view_bottom)
            arcade.set_viewport(self.view_left,
                                SCREEN_WIDTH + self.view_left,
                                self.view_bottom,
                                SCREEN_HEIGHT + self.view_bottom)


def main():
    window = MyGame()
    window.setup()
    arcade.run()


if __name__ == "__main__":
    main()