Pygame单击平铺

2024-09-23 08:17:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我在游戏里做一个塔防游戏。我设置了背景,地图是一组以这种方式闪烁的图块:

for x in range(0,640, tile_size): #x starta od 0 i mice se po 32 sve do 640
    for y in range (0, 480, tile_size): #y isto
        window.blit(Tile.Grass, (x,y)

现在很容易获得鼠标位置:

^{pr2}$

但是瓷砖是20乘20的,我需要以某种方式确定瓷砖的中心位置,这样我就可以在适当的地方装载我的矩形和精灵。在


Tags: in游戏forsize方式地图range背景
1条回答
网友
1楼 · 发布于 2024-09-23 08:17:47

我想你已经在一个列表中存储了这些瓷砖。您可以对事件坐标进行平分,以获得列表中瓷砖的索引。例如,如果单击(164,97)并将这些坐标除以平铺大小(20),则可以得到索引(8,4),并可以使用它们交换平铺。在

import itertools
import pygame as pg


pg.init()
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
BG_COLOR = pg.Color('gray12')
tilesize = 20
IMG1 = pg.Surface((tilesize, tilesize))
IMG1.fill((0, 70, 170))
IMG2 = pg.Surface((tilesize, tilesize))
IMG2.fill((180, 200, 200))
img_cycle = itertools.cycle((IMG1, IMG2))

# A list of lists of lists which contain an image and a position.
tiles = []
# I create a checkerboard pattern here with the help of the `next`
# function and itertools.cycle.
for y in range(20):
    row = []
    for x in range(30):
        # I add a list consisting of an image and its position.
        row.append([next(img_cycle), [x*tilesize, y*tilesize]])
    next(img_cycle)
    tiles.append(row)

done = False
while not done:
    for event in pg.event.get():
        if event.type == pg.QUIT:
            done = True
        elif event.type == pg.MOUSEBUTTONDOWN:
            # Use floor division to get the indices of the tile.
            x = event.pos[0] // tilesize
            y = event.pos[1] // tilesize
            print(event.pos, x, y)
            if event.button == 1:  # Left mouse button.
                # Replace the image at indices y, x.
                tiles[y][x][0] = IMG1
            elif event.button == 3:  # Right mouse button.
                tiles[y][x][0] = IMG2

    # Blit the images at their positions.
    for row in tiles:
        for img, pos in row:
            screen.blit(img, pos)
    pg.display.flip()
    clock.tick(30)

pg.quit()

相关问题 更多 >