小学生python游戏编程arcade----基本知识2

前言

接上篇文章继续解绍arcade游戏编程的基本知识。

重力应用、移动摄象机、碰撞及检测

1、重力应用

许多游戏都包含某种物理学。 最简单的是自上而下的程序,可防止角色穿过墙壁等。 平台开发人员通过重力和移动平台增加了更多的复杂性。 有些游戏使用具有质量,摩擦力,弹簧等的完整2D物理引擎。
在此setup 方法,将物理引擎更改为 PhysicsEnginePlatformer 并将重力作为一个参数
# 物理引擎
# self.physics_engine = arcade.PhysicsEngineSimple(
# self.player_sprite, self.scene.get_sprite_list(“Walls”))
跳起时,因重力作用而回到地面,在游戏中就是把精灵的y坐标值按上下方向加个速度
if key == arcade.key.UP or key == arcade.key.W:
if self.physics_engine.can_jump():
self.player_sprite.change_y = PLAYER_JUMP_SPEED
效果:
在这里插入图片描述
在这里插入图片描述

# _*_ coding: UTF-8 _*_
# 开发团队: 信息化未来
# 开发人员: Administrator
# 开发时间:2022/11/4 16:59
# 文件名称: game1.py
# 开发工具: PyCharm
import arcade

# 设置
SCREEN_WIDTH = 1000
SCREEN_HEIGHT = 650
SCREEN_TITLE = "我的游戏"

# 常量用于从原始大小缩放精灵
CHARACTER_SCALING = 1
TILE_SCALING = 0.5
PLAYER_MOVEMENT_SPEED = 2.5
# 重力
GRAVITY = 1
PLAYER_JUMP_SPEED = 20


class MyGame(arcade.Window):
    def __init__(self):
        # Call the parent class and set up the window
        super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)
        self.scene = None
        self.player_sprite = None

        arcade.set_background_color(arcade.csscolor.BLUE)

        self.physics_engine = None

    def setup(self):

        # 初始化场景
        self.scene = arcade.Scene()

        # 添加精灵列表
        self.scene.add_sprite_list("Player")
        self.scene.add_sprite_list("Walls", use_spatial_hash=True)

        # 添加角色.
        image_source = "images/1-1.png"
        self.player_sprite = arcade.Sprite(image_source, CHARACTER_SCALING)
        self.player_sprite.center_x = 264
        self.player_sprite.center_y = 128
        self.scene.add_sprite("Player", self.player_sprite)

        wall = arcade.Sprite("images/房子.png", TILE_SCALING)
        wall.center_x = SCREEN_WIDTH /2
        wall.center_y = SCREEN_HEIGHT /2
        self.scene.add_sprite("Walls", wall)

        for x in range(0, 1250, 64):
            wall = arcade.Sprite(":resources:images/tiles/grassMid.png", TILE_SCALING)
            wall.center_x = x
            wall.center_y = 32
            self.scene.add_sprite("Walls", wall)

        # 物理引擎
        # self.physics_engine = arcade.PhysicsEngineSimple(
        #     self.player_sprite, self.scene.get_sprite_list("Walls"))

        self.physics_engine = arcade.PhysicsEnginePlatformer(
            self.player_sprite, gravity_constant=GRAVITY, walls=self.scene["Walls"]
        )

    def on_draw(self):
        self.clear()
        self.scene.draw()
        # self.wall_list.draw()
        # self.player_list.draw()

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

        if key == arcade.key.UP or key == arcade.key.W:
            if self.physics_engine.can_jump():
                self.player_sprite.change_y = PLAYER_JUMP_SPEED
        elif key == arcade.key.LEFT or key == arcade.key.A:
            self.player_sprite.change_x = -PLAYER_MOVEMENT_SPEED
        elif key == arcade.key.RIGHT or key == arcade.key.D:
            self.player_sprite.change_x = PLAYER_MOVEMENT_SPEED

    def on_key_release(self, key, modifiers):
        """Called when the user releases a key."""

        if key == arcade.key.LEFT or key == arcade.key.A:
            self.player_sprite.change_x = 0
        elif key == arcade.key.RIGHT or key == arcade.key.D:
            self.player_sprite.change_x = 0

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

        # Move the player with the physics engine
        self.physics_engine.update()


def main():
    """Main function"""
    window = MyGame()
    window.setup()
    arcade.run()


if __name__ == "__main__":
    main()

2、摄象机

上个游戏,人物走到最右侧后,再向右走,人物走出了屏幕,怎么办?可以让我们的窗口成为一个小的视窗,进入一个更大的世界,只需给它添加一个摄像头。玩过游戏的人大多数知道,地图随着人物移动而变化,如何做呢,看下面:
初始时添加一个摄象机
self.camera = None # 摄象机
在setup中加
def setup(self):
# 摄象机
self.camera = arcade.Camera(self.width, self.height)
self.width, self.height如过用一半,你会发现,一半屏在闪,可以试试,有利于理解窗口宽高这两个参数的作用。

摄象机随人物移动 这个功能在pygame中想实现是需费些功夫的。

 def center_camera_to_player(self): 
    screen_center_x = self.player_sprite.center_x - (self.camera.viewport_width / 2)
    screen_center_y = self.player_sprite.center_y - (
            self.camera.viewport_height / 2
    )
    # Don't let camera travel past 0
    if screen_center_x < 0:
        screen_center_x = 0
    if screen_center_y < 0:
        screen_center_y = 0
    player_centered = screen_center_x, screen_center_y
    self.camera.move_to(player_centered)

效果:地图随人物移动在变在这里插入图片描述

# _*_ coding: UTF-8 _*_
# 开发团队: 信息化未来
# 开发人员: Administrator
# 开发时间:2022/11/4 16:59
# 文件名称: game1.py
# 开发工具: PyCharm
import arcade

# 设置
SCREEN_WIDTH = 1000
SCREEN_HEIGHT = 650
SCREEN_TITLE = "我的游戏"

# 常量用于从原始大小缩放精灵
CHARACTER_SCALING = 1
TILE_SCALING = 0.5
PLAYER_MOVEMENT_SPEED = 2.5
# 重力
GRAVITY = 1
PLAYER_JUMP_SPEED = 20


class MyGame(arcade.Window):
    def __init__(self):
        # 初始化窗体
        super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)
        self.scene = None
        self.player_sprite = None

        arcade.set_background_color(arcade.csscolor.BLUE)

        self.physics_engine = None
        self.camera = None  # 摄象机

    def setup(self):
        # 摄象机
        self.camera = arcade.Camera(self.width, self.height)

        # 初始化场景
        self.scene = arcade.Scene()

        # 添加精灵列表
        self.scene.add_sprite_list("Player")
        self.scene.add_sprite_list("Walls", use_spatial_hash=True)

        # 添加角色.
        image_source = "images/1-1.png"
        self.player_sprite = arcade.Sprite(image_source, CHARACTER_SCALING)
        self.player_sprite.center_x = 264
        self.player_sprite.center_y = 128
        self.scene.add_sprite("Player", self.player_sprite)

        wall = arcade.Sprite("images/房子.png", TILE_SCALING)
        wall.center_x = SCREEN_WIDTH /2
        wall.center_y = SCREEN_HEIGHT /2+200
        self.scene.add_sprite("Walls", wall)

        for x in range(0, 1250, 64):
            wall = arcade.Sprite(":resources:images/tiles/grassMid.png", TILE_SCALING)
            wall.center_x = x
            wall.center_y = 32
            self.scene.add_sprite("Walls", wall)

        # 物理引擎
        # self.physics_engine = arcade.PhysicsEngineSimple(
        #     self.player_sprite, self.scene.get_sprite_list("Walls"))

        self.physics_engine = arcade.PhysicsEnginePlatformer(
            self.player_sprite, gravity_constant=GRAVITY, walls=self.scene["Walls"]
        )

    def on_draw(self):
        self.clear()
        self.scene.draw()
        self.camera.use()  # 摄象机

    def on_key_press(self, key, modifiers):
        """每当按下键时调用."""
        if key == arcade.key.UP or key == arcade.key.W:
            if self.physics_engine.can_jump():
                self.player_sprite.change_y = PLAYER_JUMP_SPEED
        elif key == arcade.key.LEFT or key == arcade.key.A:
            self.player_sprite.change_x = -PLAYER_MOVEMENT_SPEED
        elif key == arcade.key.RIGHT or key == arcade.key.D:
            self.player_sprite.change_x = PLAYER_MOVEMENT_SPEED

    def on_key_release(self, key, modifiers):
        """Called when the user releases a key."""

        if key == arcade.key.LEFT or key == arcade.key.A:
            self.player_sprite.change_x = 0
        elif key == arcade.key.RIGHT or key == arcade.key.D:
            self.player_sprite.change_x = 0

    def center_camera_to_player(self):  # 摄象机随人物移动
        screen_center_x = self.player_sprite.center_x - (self.camera.viewport_width / 2)
        screen_center_y = self.player_sprite.center_y - (
                self.camera.viewport_height / 2
        )
        # Don't let camera travel past 0
        if screen_center_x < 0:
            screen_center_x = 0
        if screen_center_y < 0:
            screen_center_y = 0
        player_centered = screen_center_x, screen_center_y
        self.camera.move_to(player_centered)

    def on_update(self, delta_time):
        """运动和游戏逻辑"""
        self.physics_engine.update()  # 运用引擎移动角色
        self.center_camera_to_player()   # 摄象机


def main():
    """主程序"""
    window = MyGame()
    window.setup()
    arcade.run()


if __name__ == "__main__":
    main()

3、碰撞及检测,声音加载

碰到金币,金币消失
在这里插入图片描述
在这里插入图片描述
代码:

# _*_ coding: UTF-8 _*_
# 开发团队: 信息化未来
# 开发人员: Administrator
# 开发时间:2022/11/4 16:59
# 文件名称: game1.py
# 开发工具: PyCharm
import arcade

# 设置
SCREEN_WIDTH = 1000
SCREEN_HEIGHT = 650
SCREEN_TITLE = "我的游戏"

# 常量用于从原始大小缩放精灵
CHARACTER_SCALING = 1
TILE_SCALING = 0.5
PLAYER_MOVEMENT_SPEED = 2.5
# 重力
GRAVITY = 1
PLAYER_JUMP_SPEED = 20


class MyGame(arcade.Window):
    def __init__(self):
        # 初始化窗体
        super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)
        self.scene = None
        self.player_sprite = None

        arcade.set_background_color(arcade.csscolor.BLUE)

        self.physics_engine = None
        self.camera = None  # 摄象机
        # 加载声音
        self.collect_coin_sound = arcade.load_sound("sounds/coin2.wav")
        self.jump_sound = arcade.load_sound("sounds/s3.wav")

    def setup(self):
        # 摄象机
        self.camera = arcade.Camera(self.width, self.height)

        # 初始化场景
        self.scene = arcade.Scene()

        # 添加精灵列表
        self.scene.add_sprite_list("Player")
        self.scene.add_sprite_list("Walls", use_spatial_hash=True)

        # 添加角色.
        image_source = "images/1-1.png"
        self.player_sprite = arcade.Sprite(image_source, CHARACTER_SCALING)
        self.player_sprite.center_x = 264
        self.player_sprite.center_y = 128
        self.scene.add_sprite("Player", self.player_sprite)

        wall = arcade.Sprite("images/房子.png", TILE_SCALING)
        wall.center_x = SCREEN_WIDTH /2
        wall.center_y = SCREEN_HEIGHT /2+200
        self.scene.add_sprite("Walls", wall)

        for x in range(0, 1250, 64):
            wall = arcade.Sprite(":resources:images/tiles/grassMid.png", TILE_SCALING)
            wall.center_x = x
            wall.center_y = 32
            self.scene.add_sprite("Walls", wall)

        for x in range(128, 1250, 125):
            coin = arcade.Sprite(":resources:images/items/coinGold.png", 0.5)
            coin.center_x =x
            coin.center_y = 96
            self.scene.add_sprite("Coins", coin)

        # 物理引擎
        # self.physics_engine = arcade.PhysicsEngineSimple(
        #     self.player_sprite, self.scene.get_sprite_list("Walls"))

        self.physics_engine = arcade.PhysicsEnginePlatformer(
            self.player_sprite, gravity_constant=GRAVITY, walls=self.scene["Walls"]
        )

    def on_draw(self):
        self.clear()
        self.scene.draw()
        self.camera.use()  # 摄象机

    def on_key_press(self, key, modifiers):
        """每当按下键时调用."""
        if key == arcade.key.UP or key == arcade.key.W:
            if self.physics_engine.can_jump():
                self.player_sprite.change_y = PLAYER_JUMP_SPEED
                arcade.play_sound(self.jump_sound)
        elif key == arcade.key.LEFT or key == arcade.key.A:
            self.player_sprite.change_x = -PLAYER_MOVEMENT_SPEED
        elif key == arcade.key.RIGHT or key == arcade.key.D:
            self.player_sprite.change_x = PLAYER_MOVEMENT_SPEED

    def on_key_release(self, key, modifiers):
        """Called when the user releases a key."""

        if key == arcade.key.LEFT or key == arcade.key.A:
            self.player_sprite.change_x = 0
        elif key == arcade.key.RIGHT or key == arcade.key.D:
            self.player_sprite.change_x = 0

    def center_camera_to_player(self):
        screen_center_x = self.player_sprite.center_x - (self.camera.viewport_width / 2)
        screen_center_y = self.player_sprite.center_y - (
                self.camera.viewport_height / 2
        )

        # Don't let camera travel past 0
        if screen_center_x < 0:
            screen_center_x = 0
        if screen_center_y < 0:
            screen_center_y = 0
        player_centered = screen_center_x, screen_center_y
        self.camera.move_to(player_centered)

    def on_update(self, delta_time):
        """运动和游戏逻辑"""
        # Move the player with the physics engine
        self.physics_engine.update()

        # See if we hit any coins
        coin_hit_list = arcade.check_for_collision_with_list(
            self.player_sprite, self.scene["Coins"]
        )

        # Loop through each coin we hit (if any) and remove it
        for coin in coin_hit_list:
            # Remove the coin
            coin.remove_from_sprite_lists()
            # Play a sound
            arcade.play_sound(self.collect_coin_sound)

        self.physics_engine.update()  # 运用引擎移动角色
        self.center_camera_to_player()   # 摄象机


def main():
    """主程序"""
    window = MyGame()
    window.setup()
    arcade.run()


if __name__ == "__main__":
    main()

源码获取

关注博主后,私聊博主免费获取
需要技术指导,育娃新思考,企业软件合作等更多服务请联系博主

今天是以此模板持续更新此育儿专栏的第 12 /50次。
可以关注我,点赞我、评论我、收藏我啦。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Learn and use Python and PyGame to design and build cool arcade games. In Program Arcade Games: With Python and PyGame, Second Edition, Dr. Paul Vincent Craven teaches you how to create fun and simple quiz games; integrate and start using graphics; animate graphics; integrate and use game controllers; add sound and bit-mapped graphics; and build grid-based games. After reading and using this book, you'll be able to learn to program and build simple arcade game applications using one of today's most popular programming languages, Python. You can even deploy onto Steam and other Linux-based game systems as well as Android, one of today's most popular mobile and tablet platforms. You'll learn: How to create quiz games How to integrate and start using graphics How to animate graphics How to integrate and use game controllers How to add sound and bit-mapped graphics How to build grid-based games Audience This book assumes no prior programming knowledge. Table of Contents Chapter 1: Before Getting Started… Chapter 2: Create a Custom Calculator Chapter 3: What Is a Computer Language? Chapter 4: Quiz Games and If Statements Chapter 5: Guessing Games with Random Numbers and Loops Chapter 6: Introduction to Graphics Chapter 7: Back to Looping Chapter 8: Introduction to Lists Chapter 9: Introduction to Animation Chapter 10: Functions Chapter 11: Controllers and Graphics Chapter 12: Bitmapped Graphics and Sound Chapter 13: Introduction to Classes Chapter 14: Introduction to Sprites Chapter 15: Libraries and Modules Chapter 16: Searching Chapter 17: Array-Backed Grids Chapter 18: Sorting Chapter 19: Exceptions Chapter 20: Recursion Chapter 21: Formatting Chapter 22: Exercises

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

信息化未来

你的鼓励将是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值