def generate_grid(self, surf): """ Generates a new grid with randomized terrain covering the map. :param surf: surface images are displayed to :return: stored data """ row_len = 0 for row in range(self.width // self.block_size): col_len = 0 self.grid.append([]) for col in range(self.height // self.block_size): grass_or_clover = random.randint(0, 5) spot = [ [row_len, col_len, self.block_size, self.block_size], Creature.Creature(""), Terrain.Terrain(""), ] spot[1] = Empty.Empty() if grass_or_clover > 1: spot[2] = Grass.Grass() else: spot[2] = Clover.Clover() spot[2].set_color("alive") spot.append( pygame.draw.rect(surf, spot[2].get_color(), spot[0])) self.grid[row].append(spot) col_len += self.block_size row_len += self.block_size return self.grid
def new(self): # initialize all variables and do all the setup for a new game self.all_sprites = pg.sprite.Group() self.walls = pg.sprite.Group() self.terrain = pg.sprite.Group() self.logicMaze = np.zeros((20, 20), int) for row, tiles in enumerate(self.map_data): for col, tile in enumerate(tiles): if tile == '.': self.setTerrain(col, row) if tile == '1': if (col < 20 and row < 20): self.logicMaze[row][col] = 1 Wall(self, col, row) if tile == 'P': Terrain(self, col, row, 1) for i in range(self.genSize): newPlayer = Player(self, col, row, i) self.generation.append(newPlayer) if i == 1: self.best = newPlayer if tile == 'F': print('Finish Line') for i in range(self.genSize): self.generation[i].configure(self.logicMaze)
def main(): size = (70, 70) food = (3,3) colony = (size[0]-4, 3) initPatrol = 5 step = 1 terrain = Terrain.Terrain(size, colony, food) root = tk.Tk() board = Board.Board(root, terrain) board.pack(side="top", fill="both", expand="true", padx=4, pady=4) terrain.setNewPatrolCount(initPatrol) for i in range(50): terrain.makeObstacle((35, 0+i)) while 1: for i in range(1, step + 1): time.sleep(0.01) if i == step: terrain.iterate() board.update() root.update_idletasks() root.update()
def load(self, level): """Loads in level based on ASCII values""" count_x = 0 count_y = 0 if level == 1: ascii_map = self.level_one_key elif level == 2: ascii_map = self.level_two_key elif level == 3: ascii_map = self.level_three_key for i in ascii_map: if i == '/': self.terrain_objects.append(Terrain(count_x, count_y)) elif i == 'S': pass elif i == 'X': self.enemy_manager.spawn(count_x, count_y) elif i == 'G': # self.objects.append(Gun(count_x, count_y, self.surface) pass count_x += SIZE_BLOCK if count_x == SIZE_SCREEN_X: count_x = 0 count_y += SIZE_BLOCK if count_y == SIZE_SCREEN_Y: break
def behavior(self): self.parent.destroy() maze = m.Maze(window, self.width, self.height, t.Terrain(10, 20, p.Player(), [], barriers=True), path="random") maze.terrain.spawnEnemy() maze.display(next="expand") self.startScreen.rebuild()
def __init__(self, main, size, gravity=Vector2.Vector2()): size = (main.screen.get_width(), main.screen.get_height()) self.terrain = Terrain.Terrain(main.resources, size, self) self.phyEng = PhysEng.PhysEng() self.objects = [] self.toRemove = [] self.gravity = gravity self.main = main self.reset = False self.load = False self.objs = [] self.map_file = [] self.name = "world" self.music = [] self.size = size
def setTerrain(self, col, row): rand = random.randint(0, 100) if (self.difficulty == 1): if (rand <= 80): Terrain(self, col, row, 1) elif (rand > 80 and rand <= 90): Terrain(self, col, row, 2) else: Terrain(self, col, row, 3) if (self.difficulty == 2): if (rand <= 60): Terrain(self, col, row, 1) elif (rand > 60 and rand <= 80): Terrain(self, col, row, 2) else: Terrain(self, col, row, 3)
import pygame import config import Player import Terrain import Inventory import showcoords pygame.init() window = pygame.display.set_mode((config.screen_width, config.screen_height)) pygame.display.set_caption("Minecraft2D") terrain = Terrain.Terrain() player = Player.Player(terrain) equipment = Inventory.Inventory() def update(ev): player.update(ev, terrain, equipment) equipment.update(ev) def draw(): window.fill((0, 0, 0)) terrain.draw(window, player) player.draw(window) equipment.draw(window) showcoords.draw(window, player) terrain.create_terrain()
def initialiserMatch(self, init_string): """ Initialise le robot pour un match. A appeler dans la procédure 'init_pooo(init_string)' exemple : "INIT20ac18ab-6d18-450e-94af-bee53fdc8fcaTO6[2];1;3CELLS:1(23,9)'2'30'8'I,2(41,55)'1'30'8'II,3(23,103)'1'20'5'I;2LINES:1@3433OF2,1@6502OF3" :param init_string: chaîne regroupant les informations envoyées par le serveur pour l'initialisation d'un nouveau match, sous la forme INIT. :type init_string: str """ logging.info("==== initialisation") regex_init = re.compile( r"INIT(?P<id_match>.{8}-.{4}-.{4}-.{4}-.{12})TO(?P<nb_joueurs>[0-9]*)\[(?P<maCouleur>[0-9]*)\];(?P<vitesse>[0-9]*);(?P<nbCellules>[0-9]*)CELLS:(?P<cellules>([0-9]+\([0-9]+,[0-9]+\)'[0-9]+'[0-9]+'[0-9]+'I+,?)*);(?P<nbLines>[0-9]*)LINES:(?P<lignes>([0-9]+@[0-9]+OF[0-9]+,?)*)" ) informations = regex_init.match(init_string) if (not informations): raise Exception( "la chaine entrée est invalide (ne correspond pas à la regex)") # on récupère autant d'informations que possible sur la chaine d'origine self.vitesse = int(informations.group('vitesse')) self.id_match = informations.group('id_match') self.maCouleur = int(informations.group('maCouleur')) self.nbJoueursInitial = int(informations.group('nb_joueurs')) self.nbJoueurs = self.nbJoueursInitial # création d'un terrain vide, que l'on remplira au fur et à mesure self.terrain = te.Terrain() nbCellules = informations.group("nbCellules") # on trouve toutes les correspondances au pattern correspondant à la description d'une cellule # et pour chaque correspondance, on en extrait les informations de la cellule regex_cellules = re.compile( r"[0-9]+\([0-9]+,[0-9]+\)'[0-9]+'[0-9]+'[0-9]+'I+") regex_uneCellule = re.compile( r"(?P<id_cellule>[0-9]+)\((?P<x>[0-9]+),(?P<y>[0-9]+)\)'(?P<rayon>[0-9]+)'(?P<maxATT>[0-9]+)'(?P<maxDEF>[0-9]+)'(?P<production>I+)" ) # on ne peut pas séparer ici pas un "," => donc on n'utilise pas re.split() for chaine in regex_cellules.findall(informations.group('cellules')): ifs = regex_uneCellule.match(chaine) try: numero = int(ifs.group('id_cellule')) attaque, defense, couleurJoueur = 0, 0, -1 # cellule neutre, n'a ni attaque, ni defense attaqueMax = int(ifs.group('maxATT')) defenseMax = int(ifs.group('maxDEF')) production = len( ifs.group('production')) # on compte le nombre de I x = int(ifs.group('x')) y = int(ifs.group('y')) rayon = int(ifs.group('rayon')) cellule = ce.Cellule(numero, attaque, defense, attaqueMax, defenseMax, production, couleurJoueur, x, y, rayon) self.terrain.ajouterCellule(cellule) except Exception as e: logging.info( "======== /!\ IMPOSSIBLE DE CREER UNE CELLULE (initialiserMatch) : " + e) nbLines = informations.group("nbLines") # on fait de même pour les liens entres les cellules regex_unLien = re.compile( r"(?P<id_cellule_u>[0-9]+)@(?P<distance>[0-9]+)OF(?P<id_cellule_v>[0-9]+)" ) for chaine in re.split(",", informations.group("lignes")): try: ifs = regex_unLien.match(chaine) numero_u = int(ifs.group('id_cellule_u')) numero_v = int(ifs.group('id_cellule_v')) distance = int(ifs.group('distance')) lien = li.Lien(self.terrain.getCellule(numero_u), self.terrain.getCellule(numero_v), distance) self.terrain.ajouterLien(lien) except Exception as e: logging.info("======== /!\ IMPOSSIBLE DE CREER LE LIEN : " + e) self.peut_jouer = True self.partie_en_cours = True pass
def __init__(self): pygame.init() pygame.display.set_caption("PySmallIsoExample") screen = pygame.display.set_mode( (1024, 768), pygame.RESIZABLE | pygame.DOUBLEBUF | pygame.HWSURFACE) self.screen = screen input = Input() scene = Scene() scene.addLayer("Land", 0) scene.addLayer("Overlays", 1) scene.addLayer("Overground", 2) viewport = Viewport(screen, scene) self.viewport = viewport scroller = Scroller(viewport, input) scroller.enable() updater = Updater() self.updater = updater sprite_picker = SpritePicker(input, viewport) sprite_picker.enable() sprite_grabber = SpriteGrabber(input, viewport) sprite_grabber.enable() img = loadImage("assets/truck.png") spr = Sprite(img) scene.addSprite("Overground", spr) img = loadImage("assets/aircraft.png") spr = Sprite(img) spr.setLocation(Vector3D(0.5, 0, 0)) scene.addSprite("Overground", spr) img = loadImage("assets/forklift.png") spr = Sprite(img) spr.setLocation(Vector3D(0.5, 0.5, 0)) scene.addSprite("Overground", spr) hm = SimplexHeightmap(200, 200) terrain = Terrain(hm) tiles = terrain.create() for tile in tiles: scene.addSprite("Land", tile) done = False clock = pygame.time.Clock() while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True else: input.handleEvent(event) self.redraw() self.update() pygame.display.flip() clock.tick(60)
from tkinter import * import time import Terrain as t import Player as p WIDTH = 900 HEIGHT = 600 ROWS = 15 COLS = 15 BLOCKx = WIDTH / COLS BLOCKy = HEIGHT / ROWS exp = t.Terrain(ROWS, COLS, p.Player()) exp.randomPath() window = Tk() def leftKey(event): if exp.player.move(3): exp.player.loc.updateImage(area) area.move(exp.player.image, -BLOCKx, 0) def rightKey(event): if exp.player.move(1): exp.player.loc.updateImage(area) area.move(exp.player.image, BLOCKx, 0)
def blank(self): return t.Terrain(5, 10, p.Player(), [], barriers=0)
def loadBattle(battle, nbSave): file = io.open("Battles/" + battle + ".txt", "r", encoding="UTF-8") lines = file.readlines() file.close() size = (int(lines[0].split("x")[0]), int(lines[0].split("x")[1])) cases = [] for y in range(size[1]): for x in range(size[0]): cases.append(Case.Case(x, y, int(lines[y + 1][x]))) terrain = Terrain.Terrain(size[0], size[1]) terrain.setCases(cases) margin = 1 + size[1] nbEnemies = int(lines[margin].split(":")[1]) enemies = [] for i in range(nbEnemies): infos = lines[margin + 1 + i].split(",") #infos : # 0 - Classe # 1 - PosX # 2 - PosY # 3 - MAX HP # 4 - Attaque # 5 - Defense # 6 - Agilité # 7 - Chance # 8 - Deplacement # 9 - Vitesse # 10 - Magie # 11 - Resistance # 12 - Arme # 13 - Lvl # 14 - Boss characteristics = [ int(infos[3]), int(infos[4]), int(infos[5]), int(infos[6]), int(infos[7]), int(infos[8]), int(infos[9]), int(infos[10]), int(infos[11]) ] inventory = [Weapon.getWeapon(int(infos[12]))] print(infos[14]) isBoss = "True" in infos[14] if infos[0] == "0": # Barbare enemies.append( Characters.Barbare(int(infos[1]), int(infos[2]), characteristics, terrain, inventory, int(infos[13]), 0, isBoss)) elif infos[0] == "1": # Archer enemies.append( Characters.Archer(int(infos[1]), int(infos[2]), characteristics, terrain, inventory, int(infos[13]), 0, isBoss)) elif infos[0] == "2": # Fredegonde enemies.append( Characters.Fredegonde(int(infos[1]), int(infos[2]), characteristics, terrain, inventory, int(infos[13]), 0, True, isBoss, False)) margin += nbEnemies + 1 # On part du principe que le reste sera la position de base des personnages et finalement la suite de l'histoire posChars = [] for line in lines[margin:margin + 7]: pos = (int(line.split(",")[0]), int(line.split(",")[1])) posChars.append(pos) nextScene = lines[margin + 7].split(";") # Type, Nom nextScene.append(1) return [ terrain, enemies, loadCharacters(nbSave, terrain, posChars), nextScene ]
tile.updateImage() main_window.update() time.sleep(SLEEPTIME) timer = timer % (DECAYRATE) WIDTH = 1400 HEIGHT = 900 LANDX = 3 LANDY = 3 SLEEPTIME = .0001 DECAYRATE = int(m.sqrt((WIDTH/LANDY)**2+(HEIGHT/LANDX)**2)/3) # LANDX = int(input("How many rows would you like?")) # LANDY = int(input("How many columns would you like?")) main_window = Tk() frame = Canvas(main_window, width=WIDTH, height=HEIGHT) new = t.Terrain(frame, WIDTH, HEIGHT, LANDX, LANDY) Button(main_window, text="Add Ant", command=moreAnts).grid(row=0) Button(main_window, text="Go", command=go).grid(row=0, column=1) frame.grid(row=1, columnspan=2) for row in new.land: for col in row: col.createImage() main_window.mainloop()
def loadObjects(self): self.airplane = Airplane() self.terrain = Terrain(self.width, self.height)
def loadBackground(self): self.terrain = Terrain(self)
def __init__(self, screen_ratio, food_spawn_rate, number_of_scores, update_time, terrain_file, num_directions, shappy_speed, squary_speed, squary_run_distance, learning_rate, epochs, display_on): self.shappy_group = pygame.sprite.Group() self.squary_group = pygame.sprite.Group() self.wall_group = pygame.sprite.Group() self.shappy_speed = shappy_speed self.squary_speed = squary_speed self.squary_run_distance = squary_run_distance self.display_on = display_on self.screen_ratio = screen_ratio self.terrain_file = terrain_file self.terrain = Terrain(terrain_file) self.screen_width = self.terrain.width * self.screen_ratio self.screen_height = self.terrain.height * self.screen_ratio self.screen = pygame.display.set_mode( [self.screen_width, self.screen_height]) self.fov_radius = 100 # create initial squary for squary_boy in self.terrain.initial_squary_list: squary = Squary(squary_boy[1] * self.screen_ratio, squary_boy[0] * self.screen_ratio, self.squary_speed, self.squary_speed, self, num_directions, self.squary_run_distance) self.squary_group.add(squary) # create initial shappy for shappy_boy in self.terrain.initial_shappy_list: shappy = sha.Shappy(shappy_boy[0], shappy_boy[2] * self.screen_ratio, shappy_boy[1] * self.screen_ratio, self.shappy_speed, self.shappy_speed, self, num_directions, learning_rate, epochs, shappy_boy[3]) self.shappy_group.add(shappy) #create walls for line in range(len(self.terrain.matrix)): for column in range(len(self.terrain.matrix[0])): #print("Line: ", line) #print(self.world.terrain.matrix[line]) #print("Column: ", column) #print(self.world.terrain.matrix[line][column]) if (self.terrain.matrix[line][column] == 1): wall = Wall("Wall", self.screen, column * self.screen_ratio, line * self.screen_ratio, self.screen_ratio, self.screen_ratio) self.wall_group.add(wall) self.font = pygame.font.SysFont("Times New Roman", 18) self.last_update = None self.last_food = time.time() self.food_spawn_rate = food_spawn_rate self.number_of_scores = number_of_scores self.red_blue_score = 0 self.red_score = 0 self.blue_score = 0 self.iteration = 0 self.update_time = update_time