Python Forum
[PyGame] 2D BoardGame Pygame
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[PyGame] 2D BoardGame Pygame
#4
Example. Grid using math.
import pygame
from types import SimpleNamespace

class Grid:
    @staticmethod
    def point(item):
        return SimpleNamespace(x=item[0], y=item[1])

    def __init__(self, rect, size, gap=(0, 0)):
        self.rect = rect
        self.size = Grid.point(size)
        self.gap = Grid.point(gap)
        self.cut = Grid.point((self.size.x + self.gap.x, self.size.y + self.gap.y))

    # Returns None for invalid position
    def get_position(self, x, y):
        if (self.rect.left < x < self.rect.right and
            self.rect.top < y < self.rect.bottom):

            return ((x - self.rect.x) // self.cut.x,
                    (y - self.rect.y) // self.cut.y)

    # Returns None for invalid position
    def get_rect(self, x, y):
        if (self.rect.left < x < self.rect.right and
            self.rect.top < y < self.rect.bottom):

            return pygame.Rect(
                (x - self.rect.x) // self.cut.x * self.cut.x + self.rect.x,
                (y - self.rect.y) // self.cut.y * self.cut.y + self.rect.y,
                self.size.x, self.size.y)

def main():
    rect = pygame.Rect(0, 0, 800, 600)
    grid = Grid(rect, (40, 40))
    print(grid.get_position(12, 22))
    print(grid.get_rect(12, 22))
    print(grid.get_position(83, 58))
    print(grid.get_rect(83, 58))
    print(grid.get_position(100, 700))
    print(grid.get_rect(100, 700))

main()
99 percent of computer problems exists between chair and keyboard.
Reply


Messages In This Thread
2D BoardGame Pygame - by Josh_Python890 - Aug-13-2019, 11:59 AM
RE: 2D BoardGame Pygame - by metulburr - Aug-13-2019, 12:32 PM
RE: 2D BoardGame Pygame - by Windspar - Aug-13-2019, 02:18 PM
RE: 2D BoardGame Pygame - by Windspar - Aug-13-2019, 06:25 PM
RE: 2D BoardGame Pygame - by SheeppOSU - Aug-14-2019, 02:32 AM
RE: 2D BoardGame Pygame - by Windspar - Aug-15-2019, 09:02 PM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020