朝向式的移动角色示例,坦克那样移动示例

"""
朝向式的移动角色示例,本程序按左右键改变角色方向,按上下键移动角色,并且图片同时会旋转。
它让角色像Python的海龟画图里的海龟一样移动。注释翻译:李兴球
"""
import arcade
import os
import math

SPRITE_SCALING = 0.5

SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
SCREEN_TITLE = "朝向式的移动角色示例,坦克那样移动示例"

MOVEMENT_SPEED = 5
ANGLE_SPEED = 5


class Player(arcade.Sprite):
    """ 玩家类继承自角色类 """

    def __init__(self, image, scale):
        """ 初始化玩家 """

        # 调用玩家父类方法
        super().__init__(image, scale)

        # 速度变量
        self.speed = 0

    def update(self):
        # 转换成弧度表示
        angle_rad = math.radians(self.angle)

        # 旋转图像真简单,只要直接设置角度就行了
        self.angle += self.change_angle

        # 向前移动
        self.center_x += -self.speed * math.sin(angle_rad)
        self.center_y += self.speed * math.cos(angle_rad)


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

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

        # 调用父类初始化方法
        super().__init__(width, height, title)
        
        # 玩家列表
        self.player_list = None

        # 玩家角色变量的定义
        self.player_sprite = None

        # 设置背景为黑色
        arcade.set_background_color(arcade.color.BLACK)

    def setup(self):
        """ 设置游戏参数 """

        # Sprite lists
        self.player_list = arcade.SpriteList()

        # Set up the player
        self.player_sprite = Player("images/playerShip1_orange.png", SPRITE_SCALING)
        self.player_sprite.center_x = SCREEN_WIDTH / 2
        self.player_sprite.center_y = SCREEN_HEIGHT / 2
        self.player_list.append(self.player_sprite)

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

        # This command has to happen before we start drawing
        arcade.start_render()

        # Draw all the sprites.
        self.player_list.draw()

    def update(self, delta_time):
        """ Movement and game logic """

        # 调用更新
        self.player_list.update()

    def on_key_press(self, key, modifiers):
        """Called whenever a key is pressed. """

        # 前进或后退
        if key == arcade.key.UP:
            self.player_sprite.speed = MOVEMENT_SPEED
        elif key == arcade.key.DOWN:
            self.player_sprite.speed = -MOVEMENT_SPEED

        # 左右旋转
        elif key == arcade.key.LEFT:     # 左方向增加
            self.player_sprite.change_angle = ANGLE_SPEED
        elif key == arcade.key.RIGHT:
            self.player_sprite.change_angle = -ANGLE_SPEED

    def on_key_release(self, key, modifiers):
        """松开按键时调用此方法. """

        if key == arcade.key.UP or key == arcade.key.DOWN:
            self.player_sprite.speed = 0
        elif key == arcade.key.LEFT or key == arcade.key.RIGHT:
            self.player_sprite.change_angle = 0


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


if __name__ == "__main__":
    main()