"""仙女采红心.py 用鼠标操作一个仙女去收集红心的简易小游戏 """ import random import arcade import os # --- Constants --- SPRITE_SCALING_PLAYER = 0.5 SPRITE_SCALING_heart = 0.2 HEART_COUNT = 50 SCREEN_WIDTH = 800 SCREEN_HEIGHT = 600 class MyGame(arcade.Window): """ 继承自arcade窗口类""" def __init__(self): """ 初始化方法,先调用父类的初始化方法 """ super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT, "仙女采红心") self.player_list = None # 定义玩家列表 self.heart_list = None # 定义红心列表 self.player_sprite = None # 定义玩家角色 self.score = 0 self.set_mouse_visible(False)# 隐藏鼠标指针 arcade.set_background_color(arcade.color.AMAZON) # 设置背景颜色 def setup(self): """ 设置游戏各个属性值 """ self.player_list = arcade.SpriteList() # 创建玩家列表 self.heart_list = arcade.SpriteList() # 创建红心列表 # Score self.score = 0 self.player_sprite = arcade.Sprite("princess.png", SPRITE_SCALING_PLAYER) # 生成角色实例 self.player_sprite.center_x = 50 # 设定角色x中心坐标 self.player_sprite.center_y = 50 # 设定角色y中心坐标 self.player_list.append(self.player_sprite)# 添加到角色列表 for i in range(HEART_COUNT): # 生成一些红心 heart = arcade.Sprite("heart red.png", SPRITE_SCALING_heart) heart.center_x = random.randrange(SCREEN_WIDTH) # 红心x坐标 heart.center_y = random.randrange(SCREEN_HEIGHT)# 红心y坐标 self.heart_list.append(heart) def on_draw(self): """ 画红心们和角色""" arcade.start_render() self.heart_list.draw() self.player_list.draw() output = f"Score: {self.score}" # 准备写文本 arcade.draw_text(output, 10, 20, arcade.color.WHITE, 14) def on_mouse_motion(self, x, y, dx, dy): """ 处理鼠标移动事件x,y是鼠标的坐标 """ self.player_sprite.center_x = x self.player_sprite.center_y = y def update(self, delta_time): """ 移动角色等游戏逻辑 """ self.heart_list.update() # 玩家角色和红心们的碰撞检测,返回碰到的红心列表 hearts_hit_list = arcade.check_for_collision_with_list(self.player_sprite, self.heart_list) # 把碰到的红心都杀掉,并加分 for heart in hearts_hit_list: heart.kill() self.score += 1 def main(): """ 主要的main方法""" window = MyGame() window.setup() arcade.run() if __name__ == "__main__": main()