有背景图片的收集金币小游戏,译:lixingqiu

"""
有背景图片的收集金币小游戏
"""
import random
import arcade
import os

SPRITE_SCALING = 0.5

SCREEN_WIDTH = 1024
SCREEN_HEIGHT = 600
SCREEN_TITLE = "有背景图片的收集金币小游戏,译:lixingqiu"


class MyGame(arcade.Window):
    """
    Main application class.
    """

    def __init__(self, width, height, title):
        """ Initializer """

        # 调用父类方法,新建窗口
        super().__init__(width, height, title)

        # 设置工作目录, 
        file_path = os.path.dirname(os.path.abspath(__file__))
        os.chdir(file_path)

        # 背景图片定义
        self.background = None

        # 玩家列表和金币列表定义
        self.player_list = None
        self.coin_list = None

        # 玩家信息
        self.player_sprite = None
        self.score = 0
        self.score_text = None

        # 不显示鼠标指针
        self.set_mouse_visible(False)

        # 设置背景颜色
        arcade.set_background_color(arcade.color.AMAZON)

    def setup(self):
        """ 设置变量的值 """
        # 给背景变量赋值
        self.background = arcade.load_texture("images/background.jpg")

        # 实例化角色列表
        self.player_list = arcade.SpriteList()
        self.coin_list = arcade.SpriteList()

        # 设置玩家角色
        self.score = 0
        self.player_sprite = arcade.Sprite("images/character.png", SPRITE_SCALING)
        self.player_sprite.center_x = 50
        self.player_sprite.center_y = 50
        self.player_list.append(self.player_sprite)

        for i in range(50):

            # 实例化金币
            coin = arcade.Sprite("images/coin_01.png", SPRITE_SCALING / 3)

            # 放置金币
            coin.center_x = random.randrange(SCREEN_WIDTH)
            coin.center_y = random.randrange(SCREEN_HEIGHT)

            # 增加金币到列表
            self.coin_list.append(coin)

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

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

        # 画纹理矩形 
        arcade.draw_texture_rectangle(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2,
                                      SCREEN_WIDTH, SCREEN_HEIGHT, self.background)

        # 画所有的角色
        self.coin_list.draw()
        self.player_list.draw()

        # 画文本 
        arcade.draw_text(f"Score: {self.score}", 10, 20, arcade.color.WHITE, 14)

    def on_mouse_motion(self, x, y, dx, dy):
        """
        鼠标移动事件
        """
        self.player_sprite.center_x = x
        self.player_sprite.center_y = y

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

        # 金币列表更新
        self.coin_list.update()

        # 玩家和金币的碰撞检测
        hit_list = arcade.check_for_collision_with_list(self.player_sprite, self.coin_list)

        # 碰到的金币直接杀死并加分
        for coin in hit_list:
            coin.kill()
            self.score += 1


def main():
    """ Main method """
    window = MyGame(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)
    window.setup()
    arcade.run()


if __name__ == "__main__":
    main()