python+pygame+pytmx+map editor开发一个tiled游戏demo 05使用object层初始化player位置

发布于:2025-02-10 ⋅ 阅读:(57) ⋅ 点赞:(0)

在这里插入图片描述

代码

import math

import pygame

# 限制物体在屏幕内
import pytmx


def limit_position_to_screen(x, y, width, height):
    """限制物体在屏幕内"""
    x = max(0, min(x, SCREEN_WIDTH - width))  # 限制x坐标
    y = max(0, min(y, SCREEN_HEIGHT - height))  # 限制y坐标
    return x, y

pygame.init()

# 设置窗口大小
SCREEN_WIDTH = 640
SCREEN_HEIGHT = 640
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Pytmx Demo")


# 加载 .tmx 地图文件
tmx_data = pytmx.load_pygame("demo2.tmx")  # 将 'your_map.tmx' 替换为你的文件路径

# player.x = 50
# player.y = 50
player_speed = 3  # 玩家速度
# 设置玩家的初始位置
player = None
# 找到玩家对象(在 Object Layer 中)
for obj in tmx_data.objects:
    if obj.name == "player":
        player = obj
        break

if player is None:
    raise ValueError("Player object not found in the Object Layer")

# 检查某个位置是否有墙体
def check_collision(x, y):
    # 获取该位置的瓦片 ID
    dic = None
    try:
        x_pos = math.floor(x / tmx_data.tilewidth)
        y_pos = math.floor(y / tmx_data.tileheight)
        # print(x, y)
        print(x_pos, y_pos)
        dic = tmx_data.get_tile_properties(x_pos, y_pos, layer=1)
    except Exception as e:
        pass

    # print(gid)
    if dic:
        return dic['Collidable'] == True
    else:
        return False

# 创建一个地图渲染函数
def draw_map():
    for layer in tmx_data.visible_layers:
        if isinstance(layer, pytmx.TiledTileLayer):
            if layer.name == 'wall':
                continue

            for x, y, gid in layer:
                tile = tmx_data.get_tile_image_by_gid(gid)

                if tile:
                    screen.blit(tile, (x * tmx_data.tilewidth, y * tmx_data.tileheight))

# 游戏主循环
running = True
while running:
    clock = pygame.time.Clock()
    draw_map()  # 绘制地图

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # 处理键盘输入来移动玩家
    keys = pygame.key.get_pressed()
    new_x, new_y = player.x, player.y

    if keys[pygame.K_LEFT]:
        new_x -= player_speed  # 向左移动
        if not check_collision(new_x, new_y):
            player.x = new_x

    if keys[pygame.K_RIGHT]:
        new_x += player_speed  # 向右移动
        if not check_collision(new_x, new_y):
            player.x = new_x

    if keys[pygame.K_UP]:
        new_y -= player_speed  # 向上移动
        if not check_collision(new_x, new_y):
            player.y = new_y

    if keys[pygame.K_DOWN]:
        new_y += player_speed  # 向下移动
        if not check_collision(new_x, new_y):
            player.y = new_y

    # 限制玩家位置在屏幕内
    player.x, player.y = limit_position_to_screen(player.x, player.y, 32, 32)
    pygame.draw.rect(screen, (255, 0, 0), pygame.Rect(player.x, player.y, 32, 32))  # 32x32 是玩家的大小
    pygame.display.flip()  # 更新显示
    # 控制帧率
    clock.tick(30)

pygame.quit()

网站公告

今日签到

点亮在社区的每一天
去签到