代码
import math
import pygame
import pytmx
def limit_position_to_screen(x, y, width, height):
"""限制物体在屏幕内"""
x = max(0, min(x, SCREEN_WIDTH - width))
y = max(0, min(y, SCREEN_HEIGHT - height))
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_data = pytmx.load_pygame("demo2.tmx")
player_speed = 3
player = None
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):
dic = None
try:
x_pos = math.floor(x / tmx_data.tilewidth)
y_pos = math.floor(y / tmx_data.tileheight)
print(x_pos, y_pos)
dic = tmx_data.get_tile_properties(x_pos, y_pos, layer=1)
except Exception as e:
pass
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))
pygame.display.flip()
clock.tick(30)
pygame.quit()