PinmikPanik/gamedata/objects/ingame/tiles.py

62 lines
2.3 KiB
Python
Raw Normal View History

2021-09-11 15:12:53 +02:00
from gamedata.objects.base import BaseObject
from math import sqrt
import random
# Tiles object, displaying and managing the play grid
class Tiles(BaseObject):
def __init__(self,x,y,game,nbcells=20,cellsize=30):
super().__init__(x,y,game,nbcells*cellsize,nbcells*cellsize)
self.nbcells = nbcells
self.cellsize = cellsize
2021-09-13 10:53:42 +02:00
self.saferadius = 2
2021-09-11 15:12:53 +02:00
2021-09-13 10:53:42 +02:00
self.grid = self.gengrid(nbcells,nbcells,minsize=self.saferadius*2+1)
self.spawns = self.getspawnpoints(self.grid,saferadius=self.saferadius)
def gengrid(self,w,h,minsize=3,randrange=4):
2021-09-11 15:12:53 +02:00
# Generating various rectangles on a map
grid = [ [0 for x in range(w)] for y in range(h) ]
nb_rects = int(sqrt(w*h)/1.5+0.5)
for i in range(nb_rects):
# Generating the rects
2021-09-13 10:53:42 +02:00
rectw = random.randint(0,randrange)+minsize
recth = random.randint(0,randrange)+minsize
2021-09-11 15:12:53 +02:00
rectx = random.randint(0,w-rectw)
recty = random.randint(0,h-recth)
for offx in range(rectw):
for offy in range(recth):
grid[offy+recty][offx+rectx]=1
return grid
2021-09-13 07:41:32 +02:00
def getspawnpoints(self,grid,saferadius=2):
spawns = []
for y in range(saferadius,len(grid)-saferadius):
for x in range(saferadius,len(grid[y])-saferadius):
canspawn = True
for safey in range(-saferadius,saferadius+1):
for safex in range(-saferadius,saferadius+1):
if grid[y+safey][x+safex]==0: # If a pit is inside the radius, can't spawn here
canspawn = False
if canspawn:
2021-09-13 10:34:34 +02:00
spawns.append([self.rect[0]+(x+0.5)*self.cellsize,self.rect[1]+(y+0.5)*self.cellsize])
2021-09-13 07:41:32 +02:00
return spawns
2021-09-11 15:12:53 +02:00
def draw(self):
# Drawing the grid
for y in range(len(self.grid)):
for x in range(len(self.grid[y])):
if self.grid[y][x]==1:
self.game.pygame.draw.rect(self.game.window,[255]*3,[self.rect[0]+x*self.cellsize,self.rect[1]+y*self.cellsize,self.cellsize,self.cellsize])
2021-09-13 07:41:32 +02:00
# Draw spawn points
if self.game.globals["debug"]:
2021-09-13 10:34:34 +02:00
for point in self.spawns:
2021-09-13 07:41:32 +02:00
self.game.pygame.draw.circle(self.game.window,[100,100,0],point,radius=3)