'How to interact with tiled object with python pygame
I'm currently working on a 2D game on Python using pygame library. My maps are made on Tiled. I'have two problems but they're both linked:
- How to interact with object (ex : chest opening) on a Tiled map just one time (but if I restart the game from scratch, I can reopen it)
- How to make something disappear after interaction (ex : if I cut a tree)
Thank you for your answers !
Solution 1:[1]
It would be great to see a code example, to understand how you render the map and objects on the screen.
But I would create a 2D array to store tile-objects information about their type (terrain, obstacle, chest etc.) methods that are called when you click on them (open chest, cut tree). This method will contain logic that you need. For example, when you click on the tile with chest, it calls the method, it generates some loot and changes the tile for "opened chest", that wont open again as doesn't have that logic inside the method, that is called when a tile is clicked.
To find out, which tile is clicked (if you store them in array), you can get mouse position when the mouse button was clicked and from thag position get the coordinates of tile in 2D array. For example, if you have 10x10 tiles, with tile size of 64x64 pisels, then to get which tilex was clicked you just need to devide mouseY and mouseX by 64. I would use something like this code to get coordinates of left mouse button click and call method in object stored in 2d array.
click, _, _ = pygame.mouse.get_pressed()
if click == True:
x, y = pygame.mouse.get_pos()
array[int(y/cellSize)][int(x/cellSize)].clicked()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tikrong |
