02.基本动作

我的未来我决定 提交于 2019-12-03 03:39:30

 

 

玩家控制的小船:

def play_lives(num_icons, batch=None):
    """
    小船图标
    :param num_icons: 数量
    :param batch: 批处理
    :return:
    """
    play_lives = []
    for i in range(num_icons):
        new_sprite = pyglet.sprite.Sprite(img=resources.player_image, x=785 - i * 30, y=585, batch=batch)
        new_sprite.scale = 0.5  # 比例
        play_lives.append(new_sprite)
    return play_lives

运动类physicalobject:

"""运动类physicalobject"""
import pyglet


class Physicalobject(pyglet.sprite.Sprite):
    """
    存储对象的速度
    """

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.velocity_x, self.velocity_y = 0.0, 0.0

    def update(self, dt):
        """
        每个对象都需要在每一帧进行更新
        :param dt: “增量时间”或“时间步长”
        :return:
        """
        self.x += self.velocity_x * dt
        self.y += self.velocity_y * dt
        self.check_bounds()

    def check_bounds(self):
        """对象是否在屏幕一侧出去会移动到屏幕的另一侧"""
        min_x = -self.image.width / 2
        min_y = -self.image.height / 2
        max_x = 800 + self.image.height / 2
        max_y = 600 + self.image.height / 2
        if self.x < min_x:
            self.x = max_x
        elif self.x > max_x:
            self.x = min_x
        if self.y < min_y:
            self.y = max_y
        elif self.y > max_y:
            self.y = min_y

修改小行星让它动:

def asteroids(num_asteroids, play_position, batch=None):
    """
    随机位置小行星精灵
    :param num_asteroids: 生成小行星数量
    :param play_position: 玩家的位置
    :param batch 批处理
    :return: 返回小行星精灵
    """
    asteroids = []
    for i in range(num_asteroids):
        asteroid_x, asteroid_y = play_position
        while distance((asteroid_x, asteroid_y), play_position) < 100:
            asteroid_x = random.randint(0, 800)
            asteroid_y = random.randint(0, 600)
        # new_asteroid = pyglet.sprite.Sprite(img=resources.asteroid_image, x=asteroid_x, y=asteroid_y, batch=batch)
        new_asteroid = physicalobject.Physicalobject(img=resources.asteroid_image, x=asteroid_x, y=asteroid_y, batch=batch)
        # rotation:Sprite的旋转
        new_asteroid.rotation = random.randint(0, 360)  # 随机旋转
        # 速度
        new_asteroid.velocity_x = random.random()*40
        new_asteroid.velocity_y = random.random()*40

        asteroids.append(new_asteroid)
    return asteroids

编写游戏更新功能:

# 游戏对象列表
game_objects = [play_ship] + asteroids
def update(dt):
    for obj in game_objects:
        obj.update(dt)  # 调用Physicalobject的更新
if __name__ == '__main__':
    # 每秒调用update函数120次
    pyglet.clock.schedule_interval(update, 1 / 120.0)
    pyglet.app.run()

运行发现以前静止的小行星在屏幕上平静地漂移,当它们滑出边缘时又重新出现在另一侧。

玩家对象响应键盘输入:player.py

"""键盘输入"""
import math
from let import physicalobject, resources
from pyglet.window import key


class Player(physicalobject.Physicalobject):
    """玩家操控"""

    def __init__(self, *args, **kwargs):
        super().__init__(img=resources.player_image, *args, **kwargs)

        self.thrust = 300.0  # 速度
        self.rotate_speed = 200.0  # 角度调整度数
        # 按键字典
        self.keys = dict(left=False, right=False, up=False)

    def on_key_press(self, symbol, modifiers):  # 键盘按下
        if symbol == key.UP:
            self.keys['up'] = True
        elif symbol == key.LEFT:
            self.keys['left'] = True
        elif symbol == key.RIGHT:
            self.keys['right'] = True

    def on_key_release(self, symbol, modifiers):  # 键盘释放
        if symbol == key.UP:
            self.keys['up'] = False
        elif symbol == key.LEFT:
            self.keys['left'] = False
        elif symbol == key.RIGHT:
            self.keys['right'] = False

    def update(self, dt):
        super(Player, self).update(dt)
        if self.keys['left']:  # 向左转
            self.rotation -= self.rotate_speed * dt  # rotation为角度
        if self.keys['right']:  # 向右转
            self.rotation += self.rotate_speed * dt
        if self.keys['up']:  # 向前行
            angle_radians = -math.radians(self.rotation)  # 度转换为弧度,radians参数是弧度
            force_x = math.cos(angle_radians)*self.thrust*dt
            force_y = math.sin(angle_radians)*self.thrust*dt
            self.velocity_x += force_x
            self.velocity_y += force_y

主函数调用玩家调用:

play_ship = player.Player(x=400, y=300,batch=main_batch)
# 将其推送到事件堆栈中
game_window.push_handlers(play_ship)

现在,能够运行游戏并使用箭头键移动玩家

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!