小学生python游戏编程arcade----坦克大战(1)
- 前言
- 坦克类,地图,角色的控制,声音等前期学习的汇总
- 1、坦克类
- 2、title地图加载
- 2.1设置,tank类的引入
- 2.2 角色的引入
- 2.3 效果图
- 2.4 代码实现
- 总结
- 源码获取
前言
接上篇文章继续解绍arcade游戏编程的基本知识。
坦克类,地图,角色的控制,声音等前期学习的汇总
1、坦克类
代码实现
# _*_ coding: UTF-8 _*_
"""
坦克键盘控制转弯,及按角度前进与后退
子弹根据坦克的角度进行射击
"""
from arcadegame.seting import *
import arcade
import math
class BulletSprite(arcade.Sprite):
""" 将其角度设置为其行进方向的精灵. """
def update(self):
"""设置子弹精灵的角度与change_y,x 相关联 """
super().update()
self.angle = math.degrees(math.atan2(self.change_y, self.change_x))
class Tank(arcade.Sprite):
"""
旋转角色类
"""
def __init__(self, filename, scale):
# 调用图片
super().__init__(filename, scale)
# 前进的信息
# 角度自动从父类传入。
self.thrust = 0 # 前进动力,一直按键时,前进动力的增加
self.speed = 0 # 速度
self.max_speed = 3 # 最大速度,防止一直增加
self.drag = 0.05 # 摩擦力
# 炮台口位置
self.paokou = 0, 0
# 重生
self.respawning = 0 # 重生计时器
self.respawn()
def respawn(self):
"""
死而复生画面
'respawning'重生计时器.
"""
# 如果我们正在重生,这不能为零
self.respawning = 1
self.center_x = SCREEN_width / 2
self.center_y = SCREEN_height / 2
self.angle = 0
def update(self):
# 死后复生
if self.respawning:
self.respawning += 1
self.alpha = self.respawning
if self.respawning > 250:
self.respawning = 0
self.alpha = 255
if self.speed > 0:
self.speed -= self.drag
if self.speed < 0:
self.speed = 0
if self.speed < 0:
self.speed += self.drag
if self.speed > 0:
self.speed = 0
self.speed += self.thrust
if self.speed > self.max_speed:
self.speed = self.max_speed
if self.speed < -self.max_speed:
self.speed = -self.max_speed
self.change_x = -math.sin(math.radians(self.angle)) * self.speed
self.change_y = math.cos(math.radians(self.angle)) * self.speed
self.center_x += self.change_x
self.center_y += self.change_y
# # 过界处理
# if self.right < 0:
# self.left = SCREEN_width
#
# if self.left > SCREEN_width:
# self.right = 0
#
# if self.bottom < 0:
# self.top = SCREEN_height
#
# if self.top > SCREEN_height:
# self.bottom = 0
""" 调用父类update """
super().update()
2、title地图加载
2.1设置,tank类的引入
from arcadegame.guigl import *
from arcadegame.mysprite import *
from arcadegame.tank import *
2.2 角色的引入
# 添加角色.
self.wanjia = Tank("images/坦克.png", 0.5)
self.wanjia.center_x = PLAYER_start_x
self.wanjia.center_y = PLAYER_start_y
self.scene.add_sprite("wj", self.wanjia)
self.scene.add_sprite_list_after("wj", LAYER_platforms) # 添加精灵列表,把玩家放在哪一层,前后层在此关健
self.scene.add_sprite("wj",self.wanjia)
self.physics_engine = arcade.PhysicsEngineSimple(
self.wanjia,
walls=self.scene['fz'])
2.3 效果图
2.4 代码实现
from arcadegame.guigl import *
from arcadegame.mysprite import *
from arcadegame.tank import *
import os
class GameView(arcade.View):
def __init__(self):
super().__init__()
self.scene = None
self.wanjia = None
file_path = os.path.dirname(os.path.abspath(__file__))
os.chdir(file_path)
arcade.set_background_color(arcade.csscolor.BLUE)
self.physics_engine = None
self.camera = None # 摄象机
self.gui_camera = None # 第二摄象机
self.score = 0
# 加载声音
self.collect_coin_sound = arcade.load_sound("sounds/coin2.wav")
self.jump_sound = arcade.load_sound("sounds/s3.wav")
self.game_over = arcade.load_sound(":resources:sounds/gameover1.wav")
self.shoot_sound = arcade.load_sound(":resources:sounds/hurt5.wav")
self.hit_sound = arcade.load_sound(":resources:sounds/hit5.wav")
# 设置地图
self.tile_map = None
# 是否重新设置分数
self.reset_score = True
# 地图的最右边
self.end_of_map = 0
# 关卡级别
self.level = 1
# 射击
self.angle = 0
def setup(self):
# 摄象机
self.camera = arcade.Camera(SCREEN_width, SCREEN_height)
self.gui_camera = arcade.Camera(SCREEN_width, SCREEN_height)
# 初始化场景
map_name = f"地图\家2.json" # jia{self.level}.json"
# 层属性
layer_options = {
LAYER_platforms: {
"use_spatial_hash": True,
},
LAYER_tree: {
"use_spatial_hash": False,
},
'fz': {
"use_spatial_hash": True,
},
# 'tizi': {
# "use_spatial_hash": True,
# },
'Enemies': {
"use_spatial_hash": True,
},
}
# 读地图文件
self.tile_map = arcade.load_tilemap(map_name, TILE_Scaling, layer_options)
# 使用我们的TileMap初始化场景,这将自动添加所有层,以正确的顺序在场景中显示为SpriteList。
self.scene = arcade.Scene.from_tilemap(self.tile_map)
print('精灵列表', self.scene['fz'])
if self.reset_score:
self.score = 0
self.reset_score = True
self.end_of_map = self.tile_map.width * GRID_pixel_size
# 添加角色.
self.wanjia = Tank("images/坦克.png", 0.5)
self.wanjia.center_x = PLAYER_start_x
self.wanjia.center_y = PLAYER_start_y
self.scene.add_sprite("wj", self.wanjia)
self.scene.add_sprite_list_after("wj", LAYER_platforms) # 添加精灵列表,把玩家放在哪一层,前后层在此关健
self.scene.add_sprite("wj",self.wanjia)
self.physics_engine = arcade.PhysicsEngineSimple(
self.wanjia,
walls=self.scene['fz'])
# -- 敌人 Enemies
enemies_layer = self.tile_map.object_lists['Enemies']
for my_object in enemies_layer:
cartesian = self.tile_map.get_cartesian(
my_object.shape[0], my_object.shape[1]
)
enemy_type = my_object.properties["type"]
if enemy_type == "robot":
enemy = RobotEnemy()
elif enemy_type == "zombie":
enemy = ZombieEnemy()
else:
raise Exception(f"Unknown enemy type {enemy_type}.")
enemy.center_x = math.floor(
cartesian[0] * TILE_Scaling * self.tile_map.tile_width
)
enemy.center_y = math.floor(
(cartesian[1] + 1) * (self.tile_map.tile_height * TILE_Scaling)
)
self.scene.add_sprite(LAYER_enemies, enemy)
if "boundary_left" in my_object.properties:
enemy.boundary_left = my_object.properties["boundary_left"]
if "boundary_right" in my_object.properties:
enemy.boundary_right = my_object.properties["boundary_right"]
if "change_x" in my_object.properties:
enemy.change_x = my_object.properties["change_x"]
# 增加子弹层
self.scene.add_sprite_list_after(LAYER_bullet, 'wj')
def on_show_view(self):
self.setup()
def on_key_press(self, key: int, modifiers: int):
if not self.wanjia.respawning and key == arcade.key.SPACE:
bullet_sprite = BulletSprite(":resources:images/space_shooter/"
"laserBlue01.png",
1)
bullet_sprite.guid = "子弹"
bullet_speed = 13
bullet_sprite.change_y = \
math.cos(math.radians(self.wanjia.angle)) * bullet_speed
bullet_sprite.change_x = \
-math.sin(math.radians(self.wanjia.angle)) \
* bullet_speed
bullet_sprite.center_x = self.wanjia.center_x
bullet_sprite.center_y = self.wanjia.center_y
bullet_sprite.update()
self.scene[LAYER_bullet].append(bullet_sprite)
# arcade.play_sound(self.laser_sound, speed=random.random() * 3 + 0.5)
if key == arcade.key.LEFT:
self.wanjia.change_angle = 3
elif key == arcade.key.RIGHT:
self.wanjia.change_angle = -3
elif key == arcade.key.UP:
self.wanjia.thrust = 0.15
elif key == arcade.key.DOWN:
self.wanjia.thrust = -.2
def on_key_release(self, key: int, modifiers: int):
if key == arcade.key.LEFT:
self.wanjia.change_angle = 0
elif key == arcade.key.RIGHT:
self.wanjia.change_angle = 0
elif key == arcade.key.UP:
self.wanjia.thrust = 0
elif key == arcade.key.DOWN:
self.wanjia.thrust = 0
def on_draw(self):
self.clear()
self.camera.use() # 摄象机
self.scene.draw() # 摄相机与scence的顺序不能放错,否则不会移动
self.gui_camera.use()
# 在屏幕上绘制分数,用屏幕滚动
score_text = f"得分: {self.score}"
arcade.draw_text(score_text, 10, 500, arcade.csscolor.RED, 18, )
score_text = f"玩家: {self.wanjia.center_x}"
arcade.draw_text(score_text, 10, 600, arcade.csscolor.RED, 18, )
# for enemy in self.scene[LAYER_enemies]:
# arcade.draw_text(enemy.string, enemy.left, enemy.top-80, arcade.csscolor.RED, 30, )
# arcade.draw_text(str(int(self.wanjia.barrel.top))+';'+str(int(self.wanjia.barrel.left)), 10, 300, arcade.csscolor.RED, 18, )
def center_camera_to_player(self):
"""摄相机随角色移动"""
screen_center_x = self.wanjia.center_x - (self.camera.viewport_width / 2)
screen_center_y = self.wanjia.center_y - (self.camera.viewport_height / 2)
# 防止相机出界
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
# print(player_centered)
self.camera.move_to(player_centered)
def bengchuang(self):
# 子弹的碰撞检测
for bullet in self.scene[LAYER_bullet]:
hit_list = arcade.check_for_collision_with_lists(
bullet,
[
self.scene[LAYER_enemies],
self.scene[LAYER_tree],
],
)
if hit_list:
bullet.remove_from_sprite_lists()
for collision in hit_list:
if (self.scene[LAYER_enemies] in collision.sprite_lists):
# The collision was with an enemy
collision.health -= BULLET_shanghai
if collision.health <= 0:
collision.remove_from_sprite_lists()
self.score += 100
# Hit sound
arcade.play_sound(self.hit_sound)
return
if (bullet.right < 0) or (
bullet.left
> (self.tile_map.width * self.tile_map.tile_width) * TILE_Scaling
):
bullet.remove_from_sprite_lists()
# 碰撞检测
player_collision_list = arcade.check_for_collision_with_lists(
self.wanjia,
[
# self.scene[LAYER_tree],
self.scene[LAYER_enemies],
],
)
# 检测磁到的是硬币还是敌人
for collision in player_collision_list:
if self.scene[LAYER_enemies] in collision.sprite_lists:
arcade.play_sound(self.game_over)
self.setup()
return
else:
# 算出这枚硬币值多少分
if "Points" not in collision.properties:
print("警告,收集的硬币没有点数属性.")
else:
points = int(collision.properties["Points"])
self.score += points
# Remove the coin
collision.remove_from_sprite_lists()
arcade.play_sound(self.collect_coin_sound)
# # 是否走到地图尽头
# if self.wanjia.center_x >= self.end_of_map:
# # 关卡升级
# self.level += 1
# # 不需重新积分
# self.reset_score = False
# # 加载下个场景
# self.setup()
def on_update(self, delta_time: float):
# print(self.physics_engine)
self.physics_engine.update() # 运用引擎移动角色
self.scene['wj'].update()
self.scene[LAYER_bullet].update()
# # 掉下或level达到最后一关时,游戏结束,或重新开始
# if self.wanjia.center_y < -100 or self.level == 3:
# self.wanjia.center_x = PLAYER_start_x
# self.wanjia.center_y = PLAYER_start_y
# arcade.play_sound(self.game_over)
# 更新动画
self.scene.update_animation(delta_time, [LAYER_enemies])
# 看看敌人是否达到了边界,需要改变方向.
for enemy in self.scene[LAYER_enemies]:
if (
enemy.boundary_right
and enemy.right > enemy.boundary_right
and enemy.change_x > 0
):
enemy.change_x *= -1
if (
enemy.boundary_left
and enemy.left < enemy.boundary_left
and enemy.change_x < 0
):
enemy.change_x *= -1
# print(enemy.string)
arcade.draw_text(enemy.string, enemy.center_x, enemy.center_y, arcade.csscolor.RED, 18, )
# 更新敌人及子弹
self.scene.update([LAYER_enemies, LAYER_bullet]) #
self.center_camera_to_player() # 摄象机
class MainMenu(arcade.View):
"""Class that manages the 'menu' view."""
def on_show_view(self):
"""设置背景"""
arcade.set_background_color(arcade.color.WHITE)
self.g = GuiGL()
# 初始化场景
self.background = arcade.Sprite("images/坦克12.png", 1.4)
self.background.center_x = SCREEN_width / 2
self.background.center_y = SCREEN_height / 2
# 设置背景色
arcade.set_background_color(arcade.color.DARK_BLUE_GRAY)
# 事件方法2,自定义方法函数
self.g.start_button.on_click = self.on_click_start
def on_draw(self):
self.clear()
self.background.draw()
self.g.manager.draw()
score_text = f"坦克大战"
arcade.draw_text(
score_text,
SCREEN_width / 2-80,
SCREEN_height / 2+220,
arcade.csscolor.GOLD,
30,
)
def on_click_start(self, event):
print("自定义方法调用--开始:", event)
game_view = GameView()
self.window.show_view(game_view)
class GameOverView(arcade.View):
"""结整界面"""
def on_show_view(self):
"""设置背景"""
arcade.set_background_color(arcade.color.BLACK)
def on_draw(self):
"""Draw the game overview"""
self.clear()
arcade.draw_text(
"游戏结束,点击重新开始",
SCREEN_width / 2,
SCREEN_height / 2,
arcade.color.WHITE,
30,
anchor_x="center",
)
def on_mouse_press(self, _x, _y, _button, _modifiers):
"""Use a mouse press to advance to the 'game' view."""
game_view = GameView()
self.window.show_view(game_view)
def main():
"""主函数"""
window = arcade.Window(SCREEN_width, SCREEN_height, SCREEN_title)
menu_view = MainMenu()
window.show_view(menu_view)
arcade.run()
if __name__ == "__main__":
main()
总结
代码较长,是前面知识学习后的一个简单应用
源码获取
可关注博主后,私聊博主免费获取
需要技术指导,育娃新思考,企业软件合作等更多服务请联系博主
今天是以此模板持续更新此育儿专栏的第 21/50次。
可以关注我,点赞我、评论我、收藏我啦。