""" 本程序给coin增加一个标志,让它当被收集后会改变造型 """ import random import arcade import os SPRITE_SCALING = 1 SCREEN_WIDTH = 800 SCREEN_HEIGHT = 600 SCREEN_TITLE = "能改变造型的金币译:lixingqiu" class MyGame(arcade.Window): """ Main application class.a """ def __init__(self, width, height, title): super().__init__(width, height, title) # 设置工作目录 file_path = os.path.dirname(os.path.abspath(__file__)) os.chdir(file_path) # 角色列表定义 self.player_list = None self.coin_list = None # 设置玩家 self.score = 0 self.player_sprite = None def setup(self): """设置游戏 """ # Sprite lists self.player_list = arcade.SpriteList() self.coin_list = arcade.SpriteList() # Set up the player self.score = 0 self.player_sprite = arcade.Sprite("images/character.png", 0.5) 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) coin.append_texture( arcade.load_texture("images/bumper.png") ) coin.width = 30 coin.height = 30 coin.changed = False # 新增的‘改变了’属性 # 随机放金币 coin.center_x = random.randrange(SCREEN_WIDTH) coin.center_y = random.randrange(SCREEN_HEIGHT) # 增加金币到列表 self.coin_list.append(coin) # 隐藏鼠标 self.set_mouse_visible(False) # 设置背景颜色 arcade.set_background_color(arcade.color.AMAZON) def on_draw(self): """ 重画所有对象 """ # 开始渲染 arcade.start_render() # 画所有角色 self.coin_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为坐标,dx和dy应该是每次移动的相对距离 """ self.player_sprite.center_x = x self.player_sprite.center_y = y def update(self, delta_time): """ Movement and game logic """ # 更新玩家和金币,如坐标等 self.player_list.update() self.coin_list.update() # 玩家和所有金币的碰撞检测 hit_list = arcade.check_for_collision_with_list(self.player_sprite, self.coin_list) # 遍历每个金币,如果碰到就修改它的造型 for coin in hit_list: if not coin.changed: # 如果这枚金币被捡到 # 那么就设置新的纹理 coin.set_texture( 1 ) # 设置为索引为1的纹理 coin.changed = True coin.width = 30 coin.height = 30 self.score += 1 def main(): """ Main method """ window = MyGame(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE) window.setup() arcade.run() if __name__ == "__main__": main()
李兴球
李兴球的博客是Python创意编程原创博客