点击瓷砖的Pygame

时间:2018-06-07 21:20:28

标签: python python-3.x pygame

我正在玩游戏中的塔防游戏。我设置了背景,地图是以这种方式设置的一组瓷砖:

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)

现在通过以下方式轻松获得鼠标位置:

if event.type == pygame.MOUSEBUTTONUP:
    print('Click')
    pos = pygame.mouse.get_pos()
    print(pos)

但是瓷砖是20乘20,我需要以某种方式确定瓷砖的中心位置,以便我可以在适当的位置加载我的rects和sprite。

1 个答案:

答案 0 :(得分:0)

我假设您已将图块存储在列表中。您可以对事件坐标进行分区以获取列表中区块的索引。例如,如果单击(164,97)并将地板除以tileize(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()