"""
收集金币游戏改善下落例子,本程序用角色列表的move方法统一移动金币,实现性能提升。
这个游戏需要arcade模块支持。
"""
import random
import arcade
import os
SPRITE_SCALING = 0.5
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
SCREEN_TITLE = "收集金币游戏改善下落例子,译:lixingqiu"
class Coin(arcade.Sprite):
"""
继承自角色类的金币类
"""
def reset_pos(self):
# 重置坐标
self.center_y = random.randrange(SCREEN_HEIGHT + 20,SCREEN_HEIGHT + 100)
self.center_x = random.randrange(SCREEN_WIDTH)
def update(self):
# 更新,这里只做个判断,让它移到最上这去
if self.top < 0:
self.reset_pos()
class MyGame(arcade.Window):
""" Main application class. """
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.all_sprites_list = None
self.coin_list = None
# 定义玩家的相关变量
self.score = 0
self.player_sprite = None
def start_new_game(self):
""" 设置与初始化游戏 """
# 实例化所有角色列表
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 = 70
for i in range(50):
# 实例化金币
coin = Coin("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)
# 不显示鼠标指针
self.set_mouse_visible(False)
# 设置背景颜色
arcade.set_background_color(arcade.color.AMAZON)
def on_draw(self):
"""
渲染屏幕
"""
# 开始渲染,此命令要在所有重画命令之前
arcade.start_render()
# 画所有的角色
self.player_sprite.draw()
self.coin_list.draw()
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):
""" Movement and game logic """
# 更新坐标等等
self.player_sprite.update()
self.coin_list.update()
self.coin_list.move(0, -1)
# 玩家和所有金币的碰撞检测.
hit_list = \
arcade.check_for_collision_with_list(self.player_sprite,self.coin_list)
# 遍历碰到的金币列表
for coin in hit_list:
coin.reset_pos()# 金币并没有被删除而是移到了最上边
self.score += 1
def main():
window = MyGame(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)
window.start_new_game()
arcade.run()
if __name__ == "__main__":
main()