02.基本動做

 

 

玩家控制的小船:

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()

運行發現之前靜止的小行星在屏幕上平靜地漂移,當它們滑出邊緣時又從新出如今另外一側。app

玩家對象響應鍵盤輸入: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)

如今,可以運行遊戲並使用箭頭鍵移動玩家dom

相關文章
相關標籤/搜索