python中pygame放入图,在Pygame / Python中加载地图

这段代码展示了如何在Pygame中加载一个以文本格式存储的地图文件。它首先读取地图文件,然后根据文件内容创建二维列表来表示地图,并使用图片进行绘制。地图的每个元素可以是图片坐标或者随机选择的图片,以实现随机化效果。同时,代码还包含了限制视图范围和绘制地图到窗口的功能。
摘要由CSDN通过智能技术生成

How would I go about loading a map file in Pygame / Python?

I would like to load a map file in this format;

EDIT: I'm guessing it's a for loop, but I'm not sure on how to do that.

解决方案

Though some people have helped open a file, I understand you are actually looking to import a text file as a map:

I did not write this, but have been using it as an example for my game:

# This code is in the Public Domain

# -- richard@mechanicalcat.net

class Map:

def __init__(self, map, tiles):

self.tiles = pygame.image.load(tiles)

l = [line.strip() for line in open(map).readlines()]

self.map = [[None]*len(l[0]) for j in range(len(l))]

for i in range(len(l[0])):

for j in range(len(l)):

tile = l[j][i]

tile = tile_coords[tile]

if tile is None:

continue

elif isinstance(tile, type([])):

tile = random.choice(tile)

cx, cy = tile

if random.choice((0,1)):

cx += 192

if random.choice((0,1)):

cy += 192

self.map[j][i] = (cx, cy)

def draw(self, view, viewpos):

'''Draw the map to the "view" with the top-left of "view" being at

"viewpos" in the map.

'''

sx, sy = view.get_size()

bx = viewpos[0]/64

by = viewpos[1]/64

for x in range(0, sx+64, 64):

i = x/64 + bx

for y in range(0, sy+64, 64):

j = y/64 + by

try:

tile = self.map[j][i]

except IndexError:

# too close to the edge

continue

if tile is None:

continue

cx, cy = tile

view.blit(self.tiles, (x, y), (cx, cy, 64, 64))

def limit(self, view, pos):

'''Limit the "viewpos" variable such that it defines a valid top-left

rectangle of "view"'s size over the map.

'''

x, y = pos

# easy

x = max(x, 0)

y = max(y, 0)

# figure number of tiles in a view, hence max x and y viewpos

sx, sy = view.get_size()

nx, ny = sx/64, sy/64

mx = (len(self.map[0]) - nx) * 64

my = (len(self.map) - ny) * 64

print y, my

return (min(x, mx), min(y, my))

def main():

pygame.init()

win = pygame.display.set_mode((640, 480))

map = Map('map.txt', 'tiles.png')

viewpos = (0,0)

move = False

clock = pygame.time.Clock()

sx, sy = win.get_size()

while 1:

event = pygame.event.poll()

while event.type != NOEVENT:

if event.type in (QUIT, KEYDOWN):

sys.exit(0)

elif event.type == MOUSEBUTTONDOWN:

x, y = viewpos

dx, dy = event.pos

x += dx - sx/2

y += dy - sy/2

viewpos = map.limit(win, (x, y))

move = True

event = pygame.event.poll()

win.fill((0,0,0))

map.draw(win, viewpos)

pygame.display.flip()

clock.tick(30)

if __name__ == '__main__':

main()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值