Пигмеи нажимая на плитки - PullRequest
0 голосов
/ 08 июня 2018

Я делаю игру Tower Defense в 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, и мне нужно каким-то образом определить центральное положение плитки, чтобы я мог загрузить свои риты и спрайты в нужном месте.

1 Ответ

0 голосов
/ 08 июня 2018

Я предполагаю, что вы сохранили плитки в списке.Вы можете разделить координаты события на пол, чтобы получить индексы плиток в вашем списке.Например, если вы нажмете на (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()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...