Пример #1
0
    def __init__(self):
        # init pygame
        self.clock = pygame.time.Clock()
        self.screen = Screen()
        self.gamemap = GameMap()

        # create player paddle and inventory
        self.player = Player(100, 50, 50)
        self.inventory = Inventory()

        # create sprite Groups for game logic
        self.player_list = pygame.sprite.Group()
        self.bullet_list = pygame.sprite.Group()
        self.sword_list = pygame.sprite.Group()
        self.expReward_list = pygame.sprite.Group()

        # define default weapon type
        self.weapon_type = 'ranged'

        self.player_list.add(self.player)

        # sword swing int
        self.sword_count = 0

        # invulnerability timer
        self.invuln_count = 0

        # create rooms
        # there has to be a better way
        self.rooms = self.gamemap.get_rooms()

        self.current_room_num = 0
        self.current_room = self.rooms[self.current_room_num]

        self.run()
Пример #2
0
def doMapGenerationComparison():
    # Init economy
    economy = Economy(500);
    # Init messaging
    output = ConsoleOutput();
    # Set colors
    sAttackerColor = "white";

    gameMap = GameMap(economy, 10, 10, 0.1, 0.1, 0.05, 0.05);
    # Create an army
    army = Game.selectArmy(economy, gameMap, "white", output)

    # For this army, create 3 maps (1 easy, 1 average, 1 difficult)
    for pParams in [(0.01, 0.15, 0.01, 0.01, "easy"), (0.05, 0.15, 0.11, 0.08, "medium"),
                    (0.03, 0.01, 0.12, 0.08, "difficult")]:
        gameMap = GameMap(economy, 10, 10, pParams[0], pParams[1], pParams[2], pParams[3]);
        # Run the easy 10 times
        allScores = []
        for iCnt in range(10):
            score = runGameMap(economy, gameMap, army, output)
            allScores += [score]

        os.rename("GameTimeline.json", "GameTimeline%s.json"%(pParams[4]))

        print str(pParams) + ":" + str(allScores)
Пример #3
0
 def loadMap(self, map_name):
     """Load a new map.
        @type map_name: string
        @param map_name: Name of the map to load
        @return: None"""
     if not map_name in self.game_state.maps:  
         map_file = self.map_files[map_name]
         new_map = GameMap(self.engine, self)
         self.game_state.maps[map_name] = new_map
         new_map.load(map_file)    
Пример #4
0
def run():
    print('running')

    red_dot_imgf = "img/red_dot.png"
    background_imgf = "img/background.jpg"
    test_tile_imgf = "img/test_tile.png"


    pygame.init()

    
    gm = GameMap()

    background = pygame.image.load(background_imgf).convert()
    mouse_c = pygame.image.load(red_dot_imgf).convert()
    test_tile = pygame.image.load(test_tile_imgf).convert()
    x,y = 0,0

    while True:
        x, y = pygame.mouse.get_pos()
        
        for event in pygame.event.get():
            if event.type ==  QUIT:
                pygame.quit()
                sys.exit()
            if event.type == MOUSEBUTTONUP:
                x, y = pygame.mouse.get_pos()
                tile = gm.get_tile(x,y)
                if tile is not None:
                    tile.visible = False
            if event.type == pygame.KEYDOWN:
                pass
        press = pygame.key.get_pressed()
        if press[pygame.K_LEFT]:
            gvars.offset_x -= 8
        if press[pygame.K_RIGHT]:
            gvars.offset_x += 8
        if press[pygame.K_UP]:
            gvars.offset_y -= 3
        if press[pygame.K_DOWN]:
            gvars.offset_y += 3


        #print(x)
        #background = pygame.transform.scale(background, (200,200))
        gvars.screen.blit(background, (0,0))
        gm.render()
        pygame.display.update()
Пример #5
0
def deserializeMap(inputString):
    splitString = inputString.split(" ")

    m = GameMap(_width, _height)

    y = 0
    x = 0
    counter = 0
    owner = 0
    while y != m.height:
        counter = int(splitString.pop(0))
        owner = int(splitString.pop(0))
        for a in range(0, counter):
            m.contents[y][x].owner = owner
            x += 1
            if x == m.width:
                x = 0
                y += 1

    for a in range(0, _height):
        for b in range(0, _width):
            m.contents[a][b].strength = int(splitString.pop(0))
            m.contents[a][b].production = _productions[a][b]

    return m
Пример #6
0
def generate(specs_dict, player_dict, monsters_dict):
    """Create map, monsters and player based on dicts."""
    map = GameMap(specs_dict)
    map.makemap(specs_dict, monsters_dict)
    entities = []
    map.place_entities(specs_dict, monsters_dict, player_dict, entities)
    map.place_door(entities)
    player = entities[-1]
    return map, entities, player
Пример #7
0
	def __init__(self, player, setting, room_num, ai):
		self.player = player
		self.setting = Setting(setting)
		#self.room_num = random.randint(3, 5) # randomly sets number of rooms in game map 
		self.gamemap = GameMap(room_num, self.setting)
		# self.itemmap = Item_Map(self,room_num)
		self.cur_location = self.gamemap.start_room
		self.ai = ai
def main():
    economy = Economy()
    output = Output()
    curmap = GameMap(economy)
    myevol = RandomUnitEvolution()
    print(
        myevol.evolveEachUnit(
            economy, curmap, Game.selectArmy(economy, curmap, "white",
                                             output)))
Пример #9
0
 def load(self):
     gameMap = GameMap.getGameMap(self.mapId)
     self.game = Game(self.id, self.name, gameMap, self.myNickName)
     serverSocket.write(
         pickle.dumps({
             'action': 'getGameMemberInfo',
             'game_id': self.id
         }))
     serverSocket.flush()
Пример #10
0
def doAgentTrainingComparison():
    # Init economy
    economy = Economy(500);
    # Init messaging
    output = ConsoleOutput();
    # Set colors
    sAttackerColor = "white";

    # A medium map
    gameMap = GameMap(economy, 10, 10, 0.05, 0.15, 0.11, 0.08);

    # Create an army
    # Select an army
    army = Game.selectArmy(economy, gameMap, "white", output)

    # Run game on map 10 times
    allScores = []
    for iCnt in range(10):
        score = runGameMap(economy, gameMap, army, output)
        allScores += [score]

    # Record avg performance
    os.rename("GameTimeline.json", "GameTimeline%s.json" % ("Untrained"))
    print str("Scores for Untrained") + ":" + str(allScores)

    # Evolve army RANDOM
    myevol = RandomUnitEvolution()
    myevol.evolveEachUnit(economy, gameMap, army)

    # Reset scores
    allScores = []

    # Run game on map 10 times
    # Record avg performance
    for iCnt in range(10):
        score = runGameMap(economy, gameMap, army, output)
        allScores += [score]

    os.rename("GameTimeline.json", "GameTimeline%s.json" % ("TrainedRandom"))
    print str("Scores for TrainedRandom") + ":" + str(allScores)

    # Reset scores
    allScores = []

    # Evolve army GENETIC
    MapBuilder.unit_evolver.getArmy(army, gameMap, economy)

    # Run game on map 10 times
    # Record avg performance
    for iCnt in range(10):
        score = runGameMap(economy, gameMap, army, output)
        allScores += [score]

    # Record avg performance
    os.rename("GameTimeline.json", "GameTimeline%s.json" % ("TrainedGenetic"))
    print str("Scores for TrainedGenetic") + ":" + str(allScores)
Пример #11
0
 def moveto(self, map, x, y):
     if not isinstance(x, int) or not isinstance(y, int):
         try:
             x = int(x)
             y = int(y)
         except:
             return
     if not map.tile(x,y).canenter():
         return
     current = self.location()
     if current.get('map') and x and y:
         gamemap = GameMap(load_yaml('maps', current['map']))
         gamemap.removefromtile(current['x'], current['y'],self,'player')
     self.put('location/x', x)
     self.put('location/y', y)
     self.put('location/map', map.get_hash())
     map.addtotile(x, y, 'player', True)
     messages.warning('%s moves to %sx%s' %(self.displayname(),x, y))
     map.reveal(x, y, self.lightradius)
Пример #12
0
    def createchar(self):
        def value(key):
            return self.frontend.sprites[key].value

        self.player.put('personal/name/first', value('firstname'))
        self.player.put('personal/name/last', value('lastname'))
        self.player.put('personal/portrait', self.portrait)
        self.player.put('personal/sex', value('sex'))
        playerclass = value('playerclass') or choice(PLAYER_CLASSES) 
        playerclass = playerclass.split(':')
        debug(playerclass)
        self.player.put('class/parent', playerclass[0])
        self.player.put('class/class', playerclass[1])
        template = load_yaml('rules','template_character.yaml')
        for key in template:
            k = None
            if key.startswith('conditional/class.parent=%s/' %playerclass[0]):
                k = key.replace('conditional/class.parent=%s/' %playerclass[0],'')
            elif key.startswith('conditional/class.class=%s/' %playerclass[1]):
                k = key.replace('conditional/class.class=%s/' %playerclass[1],'')
            if k is not None and k != 'class.class':
                self.player.put(k, template[key])
            if key.startswith('inventory'):
                self.player.put(key, template[key])
            if key.startswith('__Yinventory'):
                k = key.replace('__Y', '')
                self.player.put(k, template[key])
        slot = str(len(os.listdir(self.homedir)))
        self.setsavedir(slot)
        armor = Item(load_yaml('items', 'ab7ed2a7e93bae020aeaab893902702fc0727b0079ecd3a14aa4a57c.yaml'))
        armor = self.player.acquire_item(armor)
        self.player.equip_item(armor)
        debug(self.player())
        firstmap = GameMap(load_yaml('maps', 'f1440bb0f6826a470c385218d19515ad937c1d7ab4ad3e0c71206238'))
        self.player.moveto(firstmap, 18, 1)
        firstmap.savetoslot('maps')
        animations = load_yaml('rules', 'default_sprites')
        for k,v  in animations[playerclass[0]].items():
            self.player.put(k, v)
        self.player.savetoslot()
        self.journal.write('Prison')
        self._rmtemp()
Пример #13
0
 def minimap(self, filename):
     gamemap = GameMap(load_yaml('maps', filename))
     name = gamemap.name()
     surface = pygame.Surface((128,128))
     for x in range(0,20):
         for y in range(0,20):
             tilepath = gamemap.tile(x,y).background()
             if tilepath:
                 tileimage = self.frontend.tilemaps.get_by_path(tilepath)
                 tileimage = pygame.transform.smoothscale(tileimage, (6,6))
             else:
                 tileimage = pygame.Surface((6,6))
                 tileimage.fill((0,0,0))
             surface.blit(tileimage,(x*6, y*6))
     text = render_text(name, size=20, color=(0,0,0), font=pygame.font.Font(None,20))
     textrect = text.get_rect()
     textblock = pygame.Surface((textrect.w, textrect.h))
     textblock.fill((255,255,255))
     textblock.blit(text, (0,0))
     surface.blit(textblock, (0,60))
     return (surface, filename)
Пример #14
0
def main():
    ## SETUP ##
    screen_width = 80
    screen_height = 65
    fps_limit = 10

    libtcod.console_set_custom_font(
        'arial10x10.png',
        libtcod.FONT_TYPE_GREYSCALE | libtcod.FONT_LAYOUT_TCOD)
    libtcod.console_init_root(screen_width, screen_height, 'The Game of Life',
                              False)
    libtcod.sys_set_fps(fps_limit)

    con = libtcod.console_new(screen_width, screen_height)
    key = libtcod.Key()
    mouse = libtcod.Mouse()
    map = GameMap(screen_width, screen_height)

    ## GAME LOOP ##
    while not libtcod.console_is_window_closed():

        ## ENTITY UPDATES AND RENDERING ##
        entities = map.get_entities()
        libtcod.sys_check_for_event(libtcod.EVENT_KEY_PRESS, key, mouse)
        render_all(con, entities, screen_width, screen_height)
        libtcod.console_flush()
        clear_all(con, entities)
        map.update_tiles()

        ## CALLS TO INPUT HANDLING ##
        input = handle_keys(key)
        exit = input.get('exit')
        fullscreen = input.get('fullscreen')

        if exit:
            return True

        if fullscreen:
            libtcod.console_set_fullscreen(not libtcod.console_is_fullscreen())
Пример #15
0
def on_player_connect(client, packet):
    if decode4(packet) != 0xdeadbeef:
        return client.close()

    serv.s.player = client
    char = client.s.char = mutil.create_character()

    print 'player connected'
    _player_login_event.set()

    client.send('char_connect', char, get_server_time())
    client.send('send_keymap', char)
    client.s.map = GameMap(char.map, client)
Пример #16
0
 def loadmap(self, data, reload=False):
     if reload:
         self._rmtemp()
     self.registerclickevent()
     self.gamemap = GameMap(data)
     self.gamemap.initialize(data=data)
     if self.frontend.mode == 'editor':
         self.maploadsavename()
     for x in range(0,20):
         for y in range(0,20):
             scn_x = 50+(self.tilesize*x)
             scn_y = 65+(self.tilesize*y)
             self.image.blit(self.tileimage(x,y, self.tilesize),(self.tilesize*x, self.tilesize*y))
             self.tileicons(x,y, scn_x, scn_y, self.tilesize)
Пример #17
0
def deserialize(data):
    if "x" in data and "y" in data:
        return Point(data["x"], data["y"])
    elif "Name" in data:
        return Player(data["Health"], data["MaxHealth"],
                      data["CarriedResources"], data["CarryingCapacity"],
                      data["CollectingSpeed"], data["TotalResources"],
                      data["AttackPower"], data["Defence"], data["Position"],
                      data["HouseLocation"], data["CarriedItems"],
                      data["Score"], data["Name"], data["UpgradeLevels"])
    elif "CustomSerializedMap" in data:
        data["GameMap"] = GameMap(data["CustomSerializedMap"], data["xMin"],
                                  data["yMin"])
    return data
Пример #18
0
def startProgram(monster_count):
	# Create an empty map object
	game_map = GameMap()

	# Fill empty map object from file
	is_success= Utils.loadMapFromFile(game_map, DEFAULT_MAP_PATH)
	print "File parsing completed. Success status:", is_success

	# Start only if loading a map file is successful
	if is_success:
		print "Game is started!"
		game_obj = Game(game_map, monster_count, ITERATION_COUNT)
		game_obj.startGame()
		print "Game is ended!"
	else:
		print "Not starting because loading map file is failed"
Пример #19
0
    def __init__(self, gamemap=GameMap()):
        self.actors = []
        self.turn_to_take = []

        self.gamemap = gamemap
        self.highlighted_cases = []

        self.event_queue = []
        self.message_queue = []

        self.unit_turn = None

        self.re_render = True

        self.under_mouse = None

        self.map_offset = Point(MAP_PANEL.x, MAP_PANEL.y)

        self.init_game()

        self.game_state = 'menu'
        self.game_state = 'playing'
Пример #20
0
	def __init__(self):
		# init pygame and abstract classes
		self.clock = pygame.time.Clock()
		self.screen = Screen()
		self.gamemap = GameMap()

		# init game state
		self.game_state = 'PREPARING'
	
		# create player paddle and inventory
		self.player = Player(100, 50, 50)
		self.inventory = Inventory()

		# create sprite Groups for game logic
		self.player_list = pygame.sprite.Group()
		self.weapon_list = pygame.sprite.Group()
		self.expReward_list = pygame.sprite.Group()

		self.player_list.add(self.player)	

		# sword swing int
		self.sword_count = 0
	
		# invulnerability timer
		self.invuln_count = 0
		
		# create rooms
		# there has to be a better way
		self.rooms = self.gamemap.get_rooms()
		
		self.current_room_num = 0
		self.current_room = self.rooms[self.current_room_num]

		# define default weapon type
		self.combat = Combat(self.player,self.weapon_list,self.current_room.wall_list,
			self.current_room.enemy_list, self.current_room.treasure_list, self.expReward_list)
		
		self.run()
Пример #21
0
class Game(object):
	## MAIN GAME CLASS
	def __init__(self):
		# init pygame and abstract classes
		self.clock = pygame.time.Clock()
		self.screen = Screen()
		self.gamemap = GameMap()

		# init game state
		self.game_state = 'PREPARING'
	
		# create player paddle and inventory
		self.player = Player(100, 50, 50)
		self.inventory = Inventory()

		# create sprite Groups for game logic
		self.player_list = pygame.sprite.Group()
		self.weapon_list = pygame.sprite.Group()
		self.expReward_list = pygame.sprite.Group()

		self.player_list.add(self.player)	

		# sword swing int
		self.sword_count = 0
	
		# invulnerability timer
		self.invuln_count = 0
		
		# create rooms
		# there has to be a better way
		self.rooms = self.gamemap.get_rooms()
		
		self.current_room_num = 0
		self.current_room = self.rooms[self.current_room_num]

		# define default weapon type
		self.combat = Combat(self.player,self.weapon_list,self.current_room.wall_list,
			self.current_room.enemy_list, self.current_room.treasure_list, self.expReward_list)
		
		self.run()

	def terminate(self):
		pygame.quit()
		sys.exit()

	def run(self):
		self.screen.to_screen(self.current_room.wall_list, self.screen.mapSurf)

		self.game_state = 'RUNNING'	
		while 1:		
			self.clock.tick(60)
			# event processing
		
			for event in pygame.event.get():
				if event.type == pygame.QUIT:
					self.terminate()
			
				if event.type == pygame.KEYDOWN:
					self.keyboardDown(event)
						
				if event.type == pygame.KEYUP:
					self.keyboardUp(event)
					
			# game logic

			if self.game_state == 'RUNNING':
		
				self.gameplay_modelUpdate()
				self.gameplay_viewerUpdate(self.screen)
			
		pygame.quit()

	def add_treasure(self, treasure):
		text = 'You found %s. %s' % (treasure.title, treasure.desc)
		self.inventory.add_to_inventory(treasure, self.player)
	#	self.screen.draw_alert(text)

	def blit_alpha(self, target, source, location, opacity):
		x = location[0]
		y = location[1]
		temp = pygame.Surface((source.get_width(), source.get_height())).convert()
		temp.blit(target, (-x, -y))
		temp.blit(source, (0, 0))
		temp.set_alpha(opacity)        
		target.blit(temp, location)
		
	def keyboardDown(self, evt):
		if evt.key == pygame.K_ESCAPE:
			self.doMenu()
		if self.game_state == 'RUNNING':
			if evt.key == pygame.K_LCTRL:
				self.combat.weaponSelect()
			if evt.key == pygame.K_LEFT:
				self.player.change_speed(-5, 0)
			if evt.key == pygame.K_RIGHT:
				self.player.change_speed(5, 0)
			if evt.key == pygame.K_UP:
				self.player.change_speed(0, -5)
			if evt.key == pygame.K_DOWN:
				self.player.change_speed(0, 5)
			
			if self.combat.weapon_type == 'ranged':
				self.combat.weaponAttack(evt,self.player.rect,'arrah',3)
				
			if self.combat.weapon_type == 'melee':
				self.combat.weaponAttack(evt,self.player.rect,'swadia',40)

	def doMenu(self):
		if self.game_state == 'RUNNING':
			self.game_state = 'PAUSED'
		else: self.game_state = 'RUNNING'
					
	def keyboardUp(self, evt):
		if evt.key == pygame.K_LEFT:
			self.player.change_speed(5, 0)
		if evt.key == pygame.K_RIGHT:
			self.player.change_speed(-5, 0)
		if evt.key == pygame.K_UP:
			self.player.change_speed(0, 5)
		if evt.key == pygame.K_DOWN:
			self.player.change_speed(0, -5)
			
	def gameplay_modelUpdate(self):
		self.player.move(self.current_room.wall_list)

		for w in self.weapon_list:
			self.combat.weaponLogic(w)
			
		for m in self.current_room.enemy_list:
			self.monsterLogic(m)

		for l in self.current_room.treasure_list:
			self.lootLogic(l)

		for r in self.expReward_list:
			r.counter -= 1
			if r.counter == 0:
				self.expReward_list.remove(r)
	
	
	def swingSword(self, evt):
		if evt.key == pygame.K_w:
			sword = Weapon('up',self.player.rect.centerx,
						self.player.rect.centery-50,'swadia',40)
			sword.attk(0,1)
			self.sword_count = 5
			self.sword_list.add(sword)
		elif evt.key == pygame.K_a:
			sword = Weapon('left',self.player.rect.centerx-55,
						self.player.rect.centery,'swadia',40)
			sword.attk(-1,0)
			self.sword_count = 5
			self.sword_list.add(sword)
		elif evt.key == pygame.K_s:
			sword = Weapon('down',self.player.rect.centerx,
						self.player.rect.centery+6,'swadia',40)
			sword.attk(0,-1)
			self.sword_count = 5
			self.sword_list.add(sword)
		elif evt.key == pygame.K_d:
			sword = Weapon('right',self.player.rect.centerx+6,
						self.player.rect.centery,'swadia',40)
			sword.attk(1,0)
			self.sword_count = 5
			self.sword_list.add(sword)
	
	def gameplay_viewerUpdate(self, screen):
		# updates visual elements
		screen.screen.fill(BLK)
		
		screen.spriteSurf.fill(screen.bgcolor);
		screen.GUISurf.fill(screen.bgcolor);


		if self.game_state == 'RUNNING':	
			screen.to_screen(self.current_room.enemy_list, screen.spriteSurf)
			screen.to_screen(self.current_room.treasure_list, screen.spriteSurf)
			screen.to_screen(self.expReward_list, screen.spriteSurf)
			screen.to_screen(self.weapon_list, screen.spriteSurf)
			screen.to_screen(self.player_list, screen.spriteSurf)
			screen.GUI_.render()

		
		screen.update()
			
		pygame.display.flip()

	def monsterLogic(self, m):
	
		m.move(self.current_room.wall_list)
		enemy_hit_player = pygame.sprite.spritecollide(self.player,
								self.current_room.enemy_list, False)

		for enemy in enemy_hit_player:
			# deal damage to player
			if self.invuln_count == 0:
				self.player.take_damage(enemy.damage, enemy.rect.x, enemy.rect.y)
				self.invuln_count = 1000
				if self.player.health <= 0:
					pass
			else:
				self.invuln_count -= 1
	
	def lootLogic(self, l):
		treasure_picked_up = pygame.sprite.spritecollide(self.player,
						self.current_room.treasure_list, True)

		for treasure in treasure_picked_up:
			# pick up loot!
			self.add_treasure(treasure)
Пример #22
0
        # Get rid of deep map copy
        del mapInstance

        # Append state - action pair for the View engine
        for action in self.actions:
            self.timeline.appendStateActionPair(viewState, action)
        # self.timeline.appendStateActionPair(viewState, {"text": "Something happened", "pos": {"x": 4, "y": 5}})

        self.actions[:] = []

    def saveToFile(self, sFilename):
        fOut = open(sFilename, 'w')
        fOut.write(self.msg)
        fOut.close()

        self.timeline.export()


if __name__ == "__main__":
    o = Output()
    m = GameMap(10, 10)
    import soldiers
    s = soldiers.SoldierClass()
    s.x = 3
    s.y = 0
    s2 = soldiers.SoldierClass()
    s2.x = 3
    s2.y = 1
    o.drawMap(m, [s], [s2], "green", "red")
Пример #23
0
class Game(object):
    ## MAIN GAME CLASS
    def __init__(self):
        # init pygame
        self.clock = pygame.time.Clock()
        self.screen = Screen()
        self.gamemap = GameMap()

        # create player paddle and inventory
        self.player = Player(100, 50, 50)
        self.inventory = Inventory()

        # create sprite Groups for game logic
        self.player_list = pygame.sprite.Group()
        self.bullet_list = pygame.sprite.Group()
        self.sword_list = pygame.sprite.Group()
        self.expReward_list = pygame.sprite.Group()

        # define default weapon type
        self.weapon_type = 'ranged'

        self.player_list.add(self.player)

        # sword swing int
        self.sword_count = 0

        # invulnerability timer
        self.invuln_count = 0

        # create rooms
        # there has to be a better way
        self.rooms = self.gamemap.get_rooms()

        self.current_room_num = 0
        self.current_room = self.rooms[self.current_room_num]

        self.run()

    def terminate(self):
        pygame.quit()
        sys.exit()

    def run(self):
        self.screen.to_screen(self.current_room.wall_list, self.screen.mapSurf)
        while 1:
            self.clock.tick(60)
            # event processing

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.terminate()

                if event.type == pygame.KEYDOWN:
                    self.keyboardDown(event)

                if event.type == pygame.KEYUP:
                    self.keyboardUp(event)

            # game logic

            self.modelUpdate()
            self.viewerUpdate(self.screen)

        pygame.quit()

    def add_treasure(self, treasure):
        text = 'You found %s. %s' % (treasure.title, treasure.desc)
        self.inventory.add_to_inventory(treasure, self.player)
        self.screen.draw_alert(text)

    def blit_alpha(self, target, source, location, opacity):
        x = location[0]
        y = location[1]
        temp = pygame.Surface(
            (source.get_width(), source.get_height())).convert()
        temp.blit(target, (-x, -y))
        temp.blit(source, (0, 0))
        temp.set_alpha(opacity)
        target.blit(temp, location)

    def keyboardDown(self, evt):
        if evt.key == pygame.K_ESCAPE:
            self.terminate()
        if evt.key == pygame.K_LCTRL:
            self.weaponSelect()
        if evt.key == pygame.K_LEFT:
            self.player.change_speed(-5, 0)
        if evt.key == pygame.K_RIGHT:
            self.player.change_speed(5, 0)
        if evt.key == pygame.K_UP:
            self.player.change_speed(0, -5)
        if evt.key == pygame.K_DOWN:
            self.player.change_speed(0, 5)

        if self.weapon_type == 'ranged':
            self.shootBullet(evt)

        if self.weapon_type == 'melee':
            self.swingSword(evt)

    def keyboardUp(self, evt):
        if evt.key == pygame.K_LEFT:
            self.player.change_speed(5, 0)
        if evt.key == pygame.K_RIGHT:
            self.player.change_speed(-5, 0)
        if evt.key == pygame.K_UP:
            self.player.change_speed(0, 5)
        if evt.key == pygame.K_DOWN:
            self.player.change_speed(0, -5)

    def modelUpdate(self):
        self.player.move(self.current_room.wall_list)

        for b in self.bullet_list:
            self.bulletLogic(b)

        for s in self.sword_list:
            self.swordLogic(s)

        for m in self.current_room.enemy_list:
            self.monsterLogic(m)

        for l in self.current_room.treasure_list:
            self.lootLogic(l)

        for r in self.expReward_list:
            r.counter -= 1
            if r.counter == 0:
                self.expReward_list.remove(r)

        if self.sword_count == 0:
            try:
                self.sword_list.remove(s)
            except UnboundLocalError:
                pass
        else:
            self.sword_count -= 1

    def shootBullet(self, evt):
        if evt.key == pygame.K_w:
            bullet = Bullet('up', self.player.rect.centerx,
                            self.player.rect.centery - 10)
            bullet.fire(0, 1)
            self.bullet_list.add(bullet)
        elif evt.key == pygame.K_a:
            bullet = Bullet('left', self.player.rect.centerx - 10,
                            self.player.rect.centery)
            bullet.fire(-1, 0)
            self.bullet_list.add(bullet)
        elif evt.key == pygame.K_s:
            bullet = Bullet('down', self.player.rect.centerx,
                            self.player.rect.centery)
            bullet.fire(0, -1)
            self.bullet_list.add(bullet)
        elif evt.key == pygame.K_d:
            bullet = Bullet('right', self.player.rect.centerx,
                            self.player.rect.centery)
            bullet.fire(1, 0)
            self.bullet_list.add(bullet)

    def swingSword(self, evt):
        if evt.key == pygame.K_w:
            sword = Sword('up', self.player.rect.centerx,
                          self.player.rect.centery - 10)
            sword.swing(0, 1)
            self.sword_count = 5
            self.sword_list.add(sword)
        elif evt.key == pygame.K_a:
            sword = Sword('left', self.player.rect.centerx - 12,
                          self.player.rect.centery)
            sword.swing(-1, 0)
            self.sword_count = 5
            self.sword_list.add(sword)
        elif evt.key == pygame.K_s:
            sword = Sword('down', self.player.rect.centerx,
                          self.player.rect.centery + 6)
            sword.swing(0, -1)
            self.sword_count = 5
            self.sword_list.add(sword)
        elif evt.key == pygame.K_d:
            sword = Sword('right', self.player.rect.centerx + 6,
                          self.player.rect.centery)
            sword.swing(1, 0)
            self.sword_count = 5
            self.sword_list.add(sword)

    def viewerUpdate(self, screen):
        # updates visual elements
        screen.screen.fill(BLK)

        screen.spriteSurf.fill(screen.bgcolor)
        screen.GUISurf.fill(screen.bgcolor)

        screen.to_screen(self.current_room.enemy_list, screen.spriteSurf)
        screen.to_screen(self.current_room.treasure_list, screen.spriteSurf)
        screen.to_screen(self.expReward_list, screen.spriteSurf)
        screen.to_screen(self.bullet_list, screen.spriteSurf)
        screen.to_screen(self.sword_list, screen.spriteSurf)
        screen.to_screen(self.player_list, screen.spriteSurf)
        screen.draw_stats(self.player)
        screen.draw_gold(self.player.gold)
        screen.draw_inventory(self.inventory)
        screen.draw_equipment(self.player.equipped)

        screen.update()

        pygame.display.flip()

    def weaponSelect(self):
        # allows swapping between weapons
        if self.weapon_type == 'ranged':
            self.weapon_type = 'melee'
        else:
            self.weapon_type = 'ranged'

    def bulletLogic(self, b):

        # collision?
        b.move()
        block_hit_list = pygame.sprite.spritecollide(
            b, self.current_room.wall_list, False)
        enemy_hit_list = pygame.sprite.spritecollide(
            b, self.current_room.enemy_list, False)
        # remove bullet
        for block in block_hit_list:
            self.bullet_list.remove(b)

        for enemy in enemy_hit_list:
            self.bullet_list.remove(b)
            # deal damage to enemy
            self.damageLogic(enemy, self.player, self.player.ranged_damage())

    def damageLogic(self, target, attacker, damage):
        # handles damage dealing
        target.take_damage(damage, attacker.rect.x, attacker.rect.y)
        if target.health <= 0:
            # if dead, removes from visual list
            self.current_room.enemy_list.remove(target)

            # rewards EXP to attacker
            # this function will need to be adjusted
            # to allow player-kill EXP rewards
            attacker.earn_EXP(target.EXP)

            loot_roll = random.randint(0, 30)
            # roll for loot
            if loot_roll > 15:
                loot = Treasure(target.rect.centerx, target.rect.centery)
                self.current_room.treasure_list.add(loot)
            # create EXP reward visual
            self.expReward_list.add(
                EXPReward(target.rect.centerx, target.rect.centery - TILE_SIZE,
                          target.EXP))

    def swordLogic(self, s):

        # collision?
        enemy_hit_list = pygame.sprite.spritecollide(
            s, self.current_room.enemy_list, False)

        for enemy in enemy_hit_list:
            # deal damage to enemy
            if self.sword_count == 5:
                self.damageLogic(enemy, self.player,
                                 self.player.melee_damage())

    def monsterLogic(self, m):

        m.move(self.current_room.wall_list)
        enemy_hit_player = pygame.sprite.spritecollide(
            self.player, self.current_room.enemy_list, False)

        for enemy in enemy_hit_player:
            # deal damage to player
            if self.invuln_count == 0:
                self.player.take_damage(enemy.damage, enemy.rect.x,
                                        enemy.rect.y)
                self.invuln_count = 1000
                if self.player.health <= 0:
                    pass
            else:
                self.invuln_count -= 1

    def lootLogic(self, l):
        treasure_picked_up = pygame.sprite.spritecollide(
            self.player, self.current_room.treasure_list, True)

        for treasure in treasure_picked_up:
            # pick up loot!
            self.add_treasure(treasure)
            self.screen.draw_inventory(self.inventory)
            self.screen.draw_equipment(self.player.equipped)
Пример #24
0
 def __init__(self):
     self.map = GameMap()
     self.player = None
     self.grue = None
     self.turn = 0
Пример #25
0
class Game(object):
    target_gem_count = 5

    def __init__(self):
        self.map = GameMap()
        self.player = None
        self.grue = None
        self.turn = 0

    def new_game(self):
        self.player = Player(self.map)
        self.grue = Grue(self.map, self.player)
        self.turn = 0

    def tick(self, player_direction):
        actions = []

        new_room = self.player.move(player_direction)
        actions.append({
            'action': 'player_move',
            'success': new_room is not None,
            'room': new_room,
            'target': self.map.is_target(self.player.room),
            'direction': player_direction,
        })

        if self.player.room == self.grue.room:
            self.grue.flee()
            self.player.gems += 1
            actions.append({
                'action': 'gem',
                'gem_count': self.player.gems,
                'goal_reached': self.player.gems == self.target_gem_count,
                'room': self.grue.room,
            })

        self.turn += 1

        if self.won():
            actions.append({
                'action': 'won',
            })
        elif self.turn == 3:
            self.turn = 0
            actions.append({
                'action': 'rest',
            })

            self.grue.move()

            if self.grue.room == self.player.room:
                self.player.killed()
                actions.append({
                    'action': 'killed',
                    'room': self.player.room,
                })

        return actions

    def won(self):
        return (self.map.is_target(self.player.room)
                and self.player.gems == self.target_gem_count)
Пример #26
0
    def build(self, track_len: int, use_seed: bool=False, failsafe: bool=True, verbose: bool=True,
            put_finish: bool=True, progress_callback=None, map_size: tuple=(20, 8, 20)):
        '''
        Builds the track according to the parameters.

        Args:
            track_len (int): the track length, in blocks
            use_seed (bool): whether to use a random seed from the seed data
            failsafe (bool): whether to enable various checking heuristics
            verbose (bool): print additional information while building
            put_finish (bool): whether to put a finish as the last block
            progress_callback: a function that is called whenever a new block is placed
            map_size (tuple): the map size to build the track in
        
        Returns:
            list: the resulting track
        '''
        self.running = True

        fixed_y = random.randrange(1, 7)
        if not self.gmap:
            self.gmap = GameMap(Vector3(map_size[0], map_size[1], map_size[2]), Vector3(0, fixed_y, 0))

        if use_seed and self.seed_data:
            self.gmap.track = self.sample_seed(3)
        elif len(self.gmap) == 0:
            self.gmap.add(self.random_start_block())

        self.gmap.update()

        blacklist = []
        current_block_preds = None
        while len(self.gmap) < track_len:
            if not self.running:
                return None

            end = len(self.gmap) == track_len - 1
            if len(blacklist) >= 10 or (len(blacklist) == 1 and end):
                if verbose:
                    print('More than 10 fails, going back.')

                if len(self.gmap) > track_len - 5:
                    back = 5
                elif end:
                    back = 10
                else:
                    back = random.randrange(2, 6)

                end_idx = min(len(self.gmap) - 1, back)
                if end_idx > 0:
                    del self.gmap.track[-end_idx:len(self.gmap)]

                blacklist = []
                current_block_preds = None

            X_block, X_position = self.prepare_inputs()

            block_override = FINISH_LINE_BLOCK if end and put_finish else -1

            next_block, current_block_preds = self.predict_next_block(
                X_block[:], X_position[:], block_override=block_override, blacklist=blacklist, block_preds=current_block_preds
            )

            self.gmap.add(next_block)
            decoded = self.gmap.decoded

            if failsafe:
                # Do not exceed map size
                if self.gmap.exceeds_map_size():
                    blacklist.append(next_block[BID])
                    self.gmap.pop()
                    continue

                occ = occupied_track_vectors([decoded[-1]])
                if len(occ) > 0:
                    min_y_block = min(occ, key=lambda pos: pos.y).y
                else:
                    min_y_block = decoded[-1][BY]

                # If we are above the ground
                if min_y_block > 1 and next_block[BID] in GROUND_BLOCKS:
                    blacklist.extend(GROUND_BLOCKS)
                    self.gmap.pop()
                    continue

                if (intersects(decoded[:-1], decoded[-1]) or  # Overlaps the track
                        (next_block[BID] == FINISH_LINE_BLOCK and not end)):  # Tries to put finish before desired track length
                    blacklist.append(next_block[BID])
                    self.gmap.pop()
                    continue

                if self.score_prediction(self.gmap[-2], next_block) < 5:
                    blacklist.append(next_block[BID])
                    self.gmap.pop()
                    continue

            blacklist = []
            current_block_preds = None

            next_block = (next_block[BID], next_block[BX], next_block[BY],
                          next_block[BZ], next_block[BROT])

            if progress_callback:
                progress_callback(len(self.gmap), track_len)

            if verbose:
                print(len(self.gmap))

        result_track = self.gmap.center()
        result_track = [block for block in result_track if block[BID] != STADIUM_BLOCKS['StadiumGrass']]
        return result_track
Пример #27
0
class Builder(object):
    '''
    The Builder class implements the main building loop that consists of:
        1. predicting the next block type
        2. predicting the position and rotation of the next block that is going to be placed
        3. validating model output with provided pattern data
        4. validating track characteristics such as its size and placement
        5. backtracking if the networks get stuck and cannot predict a good enough outcome
        6. Reporting progress to the user of the class

    Args:
        block_model (keras.models.Sequential): the block model to use
        position_model (keras.models.Sequential): the positionmodel model to use
        lookback (int): how many previous blocks are fed into the network at a time
        seed_data (list): optional sample data to evaluate network preformance
        temperature (float): the temperature to use
    '''
    def __init__(self, block_model: Sequential, position_model: Sequential, lookback: int,
                seed_data: list, pattern_data: dict, scaler: object, temperature: float=1.2):
        self.block_model = block_model
        self.position_model = position_model
        self.lookback = lookback
        self.seed_data = seed_data
        self.pattern_data = pattern_data
        self.scaler = scaler
        self.inp_len = len(STADIUM_BLOCKS) + POS_LEN + ROTATE_LEN
        self.temperature = temperature
        self.running = False
        self.gmap = None

    @staticmethod
    def random_start_block():
        '''
        Returns a start block in a random direction.

        Returns:
            tuple: the randomized start block
        '''
        return (START_LINE_BLOCK, 0, 0, 0, random.randrange(0, 4), 0)

    @staticmethod
    def unpack_position_preds_vector(preds: tuple):
        '''
        Unpacks position and rotation prediction from the model prediction.

        Args:
            preds (tuple): (position_preds: np.array, rotation_preds: np.array)

        Returns:
            tuple: the unpacked position and rotation prediction
        '''
        pos_vec = [int(round(axis)) for axis in preds[0][0]]
        pos_rot = np.argmax(preds[1][0])
        return pos_vec, pos_rot

    # Source:
    # https://github.com/keras-team/keras/blob/master/examples/lstm_text_generation.py#L66
    # Helper function to sample an index from a probability array
    def sample(self, preds):
        preds = np.asarray(preds).astype('float64')
        preds = np.log(preds) / self.temperature
        exp_preds = np.exp(preds)
        preds = exp_preds / np.sum(exp_preds)
        probas = np.random.multinomial(1, preds, 1)
        return np.argmax(probas)

    def predict_next_block(self, X_block: np.array, X_position: np.array, block_override: int=-1,
                        blacklist: list=[], block_preds: np.array=None):
        '''
        Predicts the next block in the main building loop.

        Asks the block model for prediction of the next block type
        based on the encoded previous blocks and then feeds the
        output to the position model.

        Args:
            X_block (np.array): encoded block types of shape (1, lookback, blocks_len)
            X_position (np.array): encoded blocks of shape (1, lookback, inp_len)
            block_override (int): the block type to use instead of predicting it
            blacklist (list): the list containing block IDs that should not 
                              be considered when sampling
            block_preds (list): cached array of block predictions from the previous
                                prediction, used when backtracking
            
            Returns:
                tuple: (predicted_block: tuple, block_preds: np.array)
        '''
        if block_override != -1:
            next_block = block_override
        else:
            if block_preds is None:
                block_preds = self.block_model.predict(X_block)[0]
                block_preds = block_preds * TECH_BLOCK_WEIGHTS

            block_preds[np.asarray(blacklist, dtype=int) - 1] = 0
            next_block = self.sample(block_preds) + 1

        X_position = np.roll(X_position, -1, 1)
        X_position[0, -1] = block_to_vec((next_block, 0, 0, 0, 0), self.inp_len, len(STADIUM_BLOCKS), self.scaler, False)

        pos_preds = self.position_model.predict(X_position)
        pos_vec, pos_rot = self.unpack_position_preds_vector(pos_preds)
        return (next_block, *pos_vec, pos_rot), block_preds

    def sample_seed(self, seed_len: int) -> list:
        '''
        Generates a random sample from seed data. Used for
        evaluating network performance when completing e.g training data samples.

        Args:
            seed_len (int): track length to seed
        
        Returns:
            list: the track from the seed
        '''
        seed_idx = random.randrange(0, len(self.seed_data))
        seed = self.seed_data[seed_idx][1][:seed_len]
        return seed

    def score_prediction(self, prev_block: tuple, next_block: tuple) -> int:
        '''
        Scores the prediction using the previous block and the block that
        was just placed, using pattern data.

        Args:
            prev_block (tuple): the previous block
            next_block (tuple): the block that was just placed

        Returns:
            int: the prediction score
        '''
        prev_block = (prev_block[BID], 0, 0, 0, prev_block[BROT])
        prev_block, next_block = rotate_track_tuples([prev_block, next_block], 4 - prev_block[BROT] % 4)

        next_block = (next_block[BID], next_block[BX] - prev_block[BX], next_block[BY] -
                      prev_block[BY], next_block[BZ] - prev_block[BZ], next_block[BROT])

        target = (prev_block[BID], next_block)
        try:
            return self.pattern_data[target]
        except KeyError:
            return 0

    def prepare_inputs(self):
        '''
        Prepares the block and position vector encodings used by predict_next_block.

        Returns:
            tuple: (X_block: np.array, X_position: np.array)
        '''
        X_block = np.zeros((1, self.lookback, len(STADIUM_BLOCKS)), dtype=np.bool)
        X_position = np.zeros((1, self.lookback, self.inp_len))

        blocks = self.gmap.track[-self.lookback:]
        i = -1
        for block in reversed(blocks):
            X_position[0, i] = block_to_vec(block, self.inp_len, len(STADIUM_BLOCKS), self.scaler, True)
            X_block[0, i] = one_hot_bid(block[BID], len(STADIUM_BLOCKS))
            i -= 1

        return X_block, X_position

    def stop(self):
        '''
        Stops the building process.
        '''
        self.running = False

    def build(self, track_len: int, use_seed: bool=False, failsafe: bool=True, verbose: bool=True,
            put_finish: bool=True, progress_callback=None, map_size: tuple=(20, 8, 20)):
        '''
        Builds the track according to the parameters.

        Args:
            track_len (int): the track length, in blocks
            use_seed (bool): whether to use a random seed from the seed data
            failsafe (bool): whether to enable various checking heuristics
            verbose (bool): print additional information while building
            put_finish (bool): whether to put a finish as the last block
            progress_callback: a function that is called whenever a new block is placed
            map_size (tuple): the map size to build the track in
        
        Returns:
            list: the resulting track
        '''
        self.running = True

        fixed_y = random.randrange(1, 7)
        if not self.gmap:
            self.gmap = GameMap(Vector3(map_size[0], map_size[1], map_size[2]), Vector3(0, fixed_y, 0))

        if use_seed and self.seed_data:
            self.gmap.track = self.sample_seed(3)
        elif len(self.gmap) == 0:
            self.gmap.add(self.random_start_block())

        self.gmap.update()

        blacklist = []
        current_block_preds = None
        while len(self.gmap) < track_len:
            if not self.running:
                return None

            end = len(self.gmap) == track_len - 1
            if len(blacklist) >= 10 or (len(blacklist) == 1 and end):
                if verbose:
                    print('More than 10 fails, going back.')

                if len(self.gmap) > track_len - 5:
                    back = 5
                elif end:
                    back = 10
                else:
                    back = random.randrange(2, 6)

                end_idx = min(len(self.gmap) - 1, back)
                if end_idx > 0:
                    del self.gmap.track[-end_idx:len(self.gmap)]

                blacklist = []
                current_block_preds = None

            X_block, X_position = self.prepare_inputs()

            block_override = FINISH_LINE_BLOCK if end and put_finish else -1

            next_block, current_block_preds = self.predict_next_block(
                X_block[:], X_position[:], block_override=block_override, blacklist=blacklist, block_preds=current_block_preds
            )

            self.gmap.add(next_block)
            decoded = self.gmap.decoded

            if failsafe:
                # Do not exceed map size
                if self.gmap.exceeds_map_size():
                    blacklist.append(next_block[BID])
                    self.gmap.pop()
                    continue

                occ = occupied_track_vectors([decoded[-1]])
                if len(occ) > 0:
                    min_y_block = min(occ, key=lambda pos: pos.y).y
                else:
                    min_y_block = decoded[-1][BY]

                # If we are above the ground
                if min_y_block > 1 and next_block[BID] in GROUND_BLOCKS:
                    blacklist.extend(GROUND_BLOCKS)
                    self.gmap.pop()
                    continue

                if (intersects(decoded[:-1], decoded[-1]) or  # Overlaps the track
                        (next_block[BID] == FINISH_LINE_BLOCK and not end)):  # Tries to put finish before desired track length
                    blacklist.append(next_block[BID])
                    self.gmap.pop()
                    continue

                if self.score_prediction(self.gmap[-2], next_block) < 5:
                    blacklist.append(next_block[BID])
                    self.gmap.pop()
                    continue

            blacklist = []
            current_block_preds = None

            next_block = (next_block[BID], next_block[BX], next_block[BY],
                          next_block[BZ], next_block[BROT])

            if progress_callback:
                progress_callback(len(self.gmap), track_len)

            if verbose:
                print(len(self.gmap))

        result_track = self.gmap.center()
        result_track = [block for block in result_track if block[BID] != STADIUM_BLOCKS['StadiumGrass']]
        return result_track
Пример #28
0
class Builder(object):
    def __init__(self, block_model, position_model, lookback, seed_data, pattern_data, scaler, temperature=1.2, reset=True):
        self.block_model = block_model
        self.position_model = position_model
        self.lookback = lookback
        self.seed_data = seed_data
        self.pattern_data = pattern_data
        self.scaler = scaler
        self.inp_len = len(STADIUM_BLOCKS) + POS_LEN + ROTATE_LEN
        self.temperature = temperature
        self.reset = reset
        self.running = False
        self.gmap = None

    @staticmethod
    def random_start_block():
        return (START_LINE_BLOCK, 0, 0, 0, random.randrange(0, 4), 0)

    # Source:
    # https://github.com/keras-team/keras/blob/master/examples/lstm_text_generation.py#L66
    # Helper function to sample an index from a probability array
    def sample(self, preds):
        preds = np.asarray(preds).astype('float64')
        preds = np.log(preds) / self.temperature
        exp_preds = np.exp(preds)
        preds = exp_preds / np.sum(exp_preds)
        probas = np.random.multinomial(1, preds, 1)
        return np.argmax(probas)

    def unpack_position_preds_vector(self, preds):
        pos_vec = [int(round(axis)) for axis in preds[0][0]]
        pos_rot = np.argmax(preds[1][0])
        return pos_vec, pos_rot

    def predict_next_block(self, X_block, X_position, block_override=-1, blacklist=[], block_preds=None):
        if block_override != -1:
            next_block = block_override
        else:
            if block_preds is None:
                block_preds = self.block_model.predict(X_block)[0]
                block_preds = block_preds * TECH_BLOCK_WEIGHTS

            for bid in blacklist:
                block_preds[bid - 1] = 0

            next_block = self.sample(block_preds) + 1

        for i in range(1, self.lookback):
            X_position[0][i - 1] = X_position[0][i]

        X_position[0][-1] = block_to_vec((next_block, 0, 0, 0, 0), self.inp_len, len(STADIUM_BLOCKS), self.scaler, False)

        pos_preds = self.position_model.predict(X_position)
        pos_vec, pos_rot = self.unpack_position_preds_vector(pos_preds)
        return (next_block, pos_vec[0], pos_vec[1], pos_vec[2], pos_rot), block_preds

    def sample_seed(self, seed_len):
        seed_idx = random.randrange(0, len(self.seed_data))
        seed = self.seed_data[seed_idx][1][:seed_len]
        return seed

    def score_prediction(self, prev_block, next_block):
        prev_block = (prev_block[BID], 0, 0, 0, prev_block[BROT])
        normalized = rotate_track_tuples(
            [prev_block, next_block], 4 - prev_block[BROT] % 4)

        prev_block = normalized[0]
        next_block = normalized[1]
        next_block = (next_block[BID], next_block[BX] - prev_block[BX], next_block[BY] -
                      prev_block[BY], next_block[BZ] - prev_block[BZ], next_block[BROT])

        target = (prev_block[BID], next_block)
        try:
            return self.pattern_data[target]
        except KeyError:
            return 0

    def prepare_inputs(self):
        X_block = np.zeros((1, self.lookback, len(STADIUM_BLOCKS)), dtype=np.bool)
        X_position = np.zeros((1, self.lookback, self.inp_len))

        blocks = self.gmap.track[-self.lookback:]
        i = -1
        for block in reversed(blocks):
            X_position[0][i] = block_to_vec(block, self.inp_len, len(STADIUM_BLOCKS), self.scaler, True)
            X_block[0][i] = one_hot_bid(block[BID], len(STADIUM_BLOCKS))
            i -= 1

        return X_block, X_position

    def stop(self):
        self.running = False

    def build(self, 
        track_len,
        use_seed=False,
        failsafe=True,
        verbose=True,
        save=True,
        put_finish=True,
        progress_callback=None,
        map_size=(20, 8, 20)):

        self.running = True

        fixed_y = random.randrange(1, 7)
        if not self.gmap or self.reset:
            self.gmap = GameMap(
                Vector3(map_size[0], map_size[1], map_size[2]), Vector3(0, fixed_y, 0))

        if use_seed and self.seed_data:
            self.gmap.track = self.sample_seed(3)
        elif len(self.gmap) == 0:
            self.gmap.add(self.random_start_block())

        print(self.gmap.track)
        self.gmap.update()

        blacklist = []
        current_block_preds = None
        while len(self.gmap) < track_len:
            if not self.running:
                return None

            end = len(self.gmap) == track_len - 1
            if len(blacklist) >= 10 or (len(blacklist) == 1 and end) and self.reset:
                if verbose:
                    print('More than 10 fails, going back.')

                if len(self.gmap) > track_len - 5:
                    back = 5
                elif end:
                    back = 10
                else:
                    back = random.randrange(2, 6)

                end_idx = min(len(self.gmap) - 1, back)
                if end_idx > 0:
                    del self.gmap.track[-end_idx:len(self.gmap)]

                blacklist = []
                current_block_preds = None

            X_block, X_position = self.prepare_inputs()

            override_block = FINISH_LINE_BLOCK if end and put_finish else -1

            next_block, current_block_preds = self.predict_next_block(
                X_block[:], X_position[:], override_block, blacklist=blacklist, block_preds=current_block_preds)

            self.gmap.add(next_block)
            decoded = self.gmap.decoded

            if failsafe:
                # Do not exceed map size
                if self.gmap.exceeds_map_size():
                    blacklist.append(next_block[BID])
                    self.gmap.pop()
                    continue

                occ = occupied_track_vectors([decoded[-1]])
                if len(occ) > 0:
                    min_y_block = min(occ, key=lambda pos: pos.y).y
                else:
                    min_y_block = decoded[-1][BY]

                # If we are above the ground
                if min_y_block > 1 and next_block[BID] in GROUND_BLOCKS:
                    blacklist.extend(GROUND_BLOCKS)
                    self.gmap.pop()
                    continue

                if (intersects(decoded[:-1], decoded[-1]) or  # Overlaps the track
                        (next_block[BID] == FINISH_LINE_BLOCK and not end)):  # Tries to put finish before desired track length
                    blacklist.append(next_block[BID])
                    self.gmap.pop()
                    continue

                if self.score_prediction(self.gmap[-2], next_block) < 5:
                    blacklist.append(next_block[BID])
                    self.gmap.pop()
                    continue

            blacklist = []
            current_block_preds = None

            next_block = (next_block[BID], next_block[BX], next_block[BY],
                          next_block[BZ], next_block[BROT])

            if progress_callback:
                progress_callback(len(self.gmap), track_len)

            if verbose:
                print(len(self.gmap))

        result_track = self.gmap.center()
        result_track = [block for block in result_track if block[BID] != STADIUM_BLOCKS['StadiumGrass']]
        return result_track
Пример #29
0
    def build(self, 
        track_len,
        use_seed=False,
        failsafe=True,
        verbose=True,
        save=True,
        put_finish=True,
        progress_callback=None,
        map_size=(20, 8, 20)):

        self.running = True

        fixed_y = random.randrange(1, 7)
        if not self.gmap or self.reset:
            self.gmap = GameMap(
                Vector3(map_size[0], map_size[1], map_size[2]), Vector3(0, fixed_y, 0))

        if use_seed and self.seed_data:
            self.gmap.track = self.sample_seed(3)
        elif len(self.gmap) == 0:
            self.gmap.add(self.random_start_block())

        print(self.gmap.track)
        self.gmap.update()

        blacklist = []
        current_block_preds = None
        while len(self.gmap) < track_len:
            if not self.running:
                return None

            end = len(self.gmap) == track_len - 1
            if len(blacklist) >= 10 or (len(blacklist) == 1 and end) and self.reset:
                if verbose:
                    print('More than 10 fails, going back.')

                if len(self.gmap) > track_len - 5:
                    back = 5
                elif end:
                    back = 10
                else:
                    back = random.randrange(2, 6)

                end_idx = min(len(self.gmap) - 1, back)
                if end_idx > 0:
                    del self.gmap.track[-end_idx:len(self.gmap)]

                blacklist = []
                current_block_preds = None

            X_block, X_position = self.prepare_inputs()

            override_block = FINISH_LINE_BLOCK if end and put_finish else -1

            next_block, current_block_preds = self.predict_next_block(
                X_block[:], X_position[:], override_block, blacklist=blacklist, block_preds=current_block_preds)

            self.gmap.add(next_block)
            decoded = self.gmap.decoded

            if failsafe:
                # Do not exceed map size
                if self.gmap.exceeds_map_size():
                    blacklist.append(next_block[BID])
                    self.gmap.pop()
                    continue

                occ = occupied_track_vectors([decoded[-1]])
                if len(occ) > 0:
                    min_y_block = min(occ, key=lambda pos: pos.y).y
                else:
                    min_y_block = decoded[-1][BY]

                # If we are above the ground
                if min_y_block > 1 and next_block[BID] in GROUND_BLOCKS:
                    blacklist.extend(GROUND_BLOCKS)
                    self.gmap.pop()
                    continue

                if (intersects(decoded[:-1], decoded[-1]) or  # Overlaps the track
                        (next_block[BID] == FINISH_LINE_BLOCK and not end)):  # Tries to put finish before desired track length
                    blacklist.append(next_block[BID])
                    self.gmap.pop()
                    continue

                if self.score_prediction(self.gmap[-2], next_block) < 5:
                    blacklist.append(next_block[BID])
                    self.gmap.pop()
                    continue

            blacklist = []
            current_block_preds = None

            next_block = (next_block[BID], next_block[BX], next_block[BY],
                          next_block[BZ], next_block[BROT])

            if progress_callback:
                progress_callback(len(self.gmap), track_len)

            if verbose:
                print(len(self.gmap))

        result_track = self.gmap.center()
        result_track = [block for block in result_track if block[BID] != STADIUM_BLOCKS['StadiumGrass']]
        return result_track
Пример #30
0
                    if create_successful == 1:
                        game_map.castle.gold -= cost

                    self.mouse_state = True


#

#Init

start = False
disabled_GAME_OVER = False

os.environ['SDL_VIDEO_WINDOW_POS'] = "150, 40"

game_map = GameMap()
draw = DrawHandler(game_map, pygame.display)
cycle = CycleHandler(game_map)
event = EventHandler(game_map, pygame.event, pygame.mouse, pygame.key, draw)
gamespeed = 16  #em milissegundos de duração de cada ciclo

current_time = pygame.time.get_ticks
sleep = pygame.time.wait

pygame.display.set_caption("Slime Wars")
#Main

while not event.quit:

    initial_time = current_time()
    cycle.update(start)
Пример #31
0
 def load(self):
     gameMap = GameMap.getGameMap(self.mapId)
     self.game = Game(self.id, self.name, gameMap, self.myNickName)
     serverSocket.write(pickle.dumps({'action': 'getGameMemberInfo', 'game_id': self.id}))
     serverSocket.flush()
Пример #32
0
class Mapview(pygame.sprite.DirtySprite, Tempsprites):
    def __init__(self, frontend, *args):
        self._layer = 0
        super(pygame.sprite.DirtySprite, self).__init__()
        self.frontend = frontend
        size = self.frontend.mapw
        self.tilesize = self.frontend.mapscale
        self.rect = pygame.Rect(50,65, self.frontend.mapw, self.frontend.mapw)
        self.background = self.frontend.screen.subsurface(self.frontend.screensize).copy()
        self.image  = pygame.Surface((size, size))
        self.backgrounds = {}
        self.mapw = self.frontend.mapw
        Tempsprites.__init__(self)
        self.dialog = FloatDialog(self.frontend.rightwindow_rect, self.frontend, layer=1)
        self._addtemp('rightwindow', self.dialog)
        if self.frontend.mode == 'editor':
            self.loadmap({})
        else:
            loc = self.frontend.game.player.location()
            mapname = loc['map']
            self.loadmap(load_yaml('maps', mapname))


    def tileimage(self, x, y, scale):
        tile = self.gamemap.tile(x,y)
        tileimage = pygame.Surface((16, 16))
        backgroundpath = tile.background()
        if backgroundpath:
            backgroundimage = self.frontend.tilemaps.get_by_path(backgroundpath)
        else:
            backgroundimage = pygame.Surface((scale, scale))
        if backgroundpath and (tile.revealed() or self.frontend.mode == 'editor'):
            tileimage.blit(backgroundimage,(0,0))
            tileimage = pygame.transform.smoothscale(tileimage, (scale, scale))
            if self.frontend.mode == 'editor':
                tileimage.blit(render_text('%sX%s' %(x,y), size=(self.tilesize/2), color=(0,0,0), font=pygame.font.Font(None,16) ), (self.tilesize/2,self.tilesize/2))
        else:
            if self.frontend.mode == 'editor':
                if y%2 == 0 and x%2 == 0 or y%2 == 1 and x%2 == 1:
                    r, t = 255, 0
                else:
                    r, t = 0, 255
                backgroundimage.fill((r,r,r,0))
                backgroundimage.blit(render_text('%sX%s' %(x,y), size=(self.tilesize/2), color=(t,t,t), font=pygame.font.Font(None,16) ), (1,1))
                tileimage =backgroundimage
            else:
                tileimage.fill((0,0,0,0))
        return tileimage

    def tileicons(self, x, y, scn_x, scn_y, scale):
        rect = pygame.Rect(scn_x, scn_y, scale, scale)
        if self.frontend.mode != 'editor':
            if not self.gamemap.tile(x,y).get('revealed', False):
                return
            player = self.frontend.game.player
            loc = player.location()
            if loc['x'] == x and loc['y'] == y and not 'player' in self.frontend.sprites:
                playerbtn = ButtonSprite(
                    self.frontend.tilemaps,
                    rect,
                    self.frontend.eventstack,
                    onclick = self.click,
                    onclick_params = [(scn_x,scn_y)],
                    animations = player.getsubtree('animations'),
                    layer=self._layer+2,
                    fps=5,
                    mouseover=player.displayname(),
                    frontend=self.frontend)
                self.frontend.sprites['player'] = playerbtn
        scn_x = 50+(self.tilesize*x)
        scn_y = 65+(self.tilesize*y)
        npc = None
        animations = {'view':[]}
        for objtype, item in self.gamemap.tile_objects(x,y):
            if objtype != 'npc':
                animations['view'] += item.get('animations/view')
            else:
                npc = ButtonSprite(
                    self.frontend.tilemaps,
                    rect,
                    self.frontend.eventstack,
                    onclick = self.click,
                    onclick_params = [(scn_x,scn_y)],
                    animations = item.getsubtree('animations'),
                    layer=self._layer+2,
                    fps=5,
                    mouseover=item.displayname(),
                    frontend=self.frontend)
        if animations['view'] and npc is None:
            itemsprite = ButtonSprite(
                self.frontend.tilemaps,
                rect,
                self.frontend.eventstack,
                onclick = self.click,
                onclick_params = [(scn_x,scn_y)],
                animations = animations,
                layer=self._layer+1,
                fps=3,
                frontend=self.frontend)
            self._addtemp(make_hash(), itemsprite)
        if npc is not None and not npc.get_hash() in self.frontend.sprites:
            self.frontend.sprites[npc.get_hash()] = npc
            if not npc in self.frontend.game.characters: 
                self.frontend.game.characters.append(npc)

    def update(self):
        self.loadmap(self.gamemap())


    def zoomicons(self, x, y, scn_x, scn_y):
        objlist = list(self.gamemap.tile_objects(x,y))
        n = len(objlist)
        if not n:
            return
        col, row = 0, 0
        if n%2 != 0:
            n += 1
        colcount = n/2
        if n < 4:
            scale = int(128/n)
        else:
            scale = int(128/colcount)
        for objtype,item in objlist:
            s_x = scn_x + col*scale
            s_y = scn_y + row*scale
            rect = pygame.Rect(s_x, s_y, scale, scale)
            if objtype != 'money':
                animations = item.getsubtree('animations')
                name=item.displayname()
            else:
                animations = item
                name='Money'
            itemsprite = ButtonSprite(
            self.frontend.tilemaps,
            rect,
            self.frontend.eventstack,
            onclick = self.targetclick,
            onclick_params = [x,y,objtype, item],
            animations = animations,
            layer=self._layer+2,
            mouseover=name,
            fps=5,
            frontend=self.frontend)
            if objtype == 'npc':
                itemsprite.setanimation('stand')
            else:
                itemsprite.setanimation('view')
            self._addtemp(make_hash(), itemsprite)
            col += 1
            if col == colcount:
                col = 0
                row += 1
    
    def targetclick(self,x,y,objtype, item):
        minx, miny = self.frontend.rightwindow_rect.x + 10, self.frontend.rightwindow_rect.y + 10
        if self.frontend.mode == 'editor':
            rmBtn = Button('Remove',
            self.removefromtile,
            [x,y,objtype,item],
            self.frontend.eventstack,
            self.frontend.imagecache,
            pos=(minx,miny + 185)
            )
            self._addtemp(make_hash(), rmBtn)

    def removefromtile(self,x,y,objtype,item):
        self.gamemap.removefromtile(x,y,item,objtype)
        self.tile = self.gamemap.tile(x,y)
        self._rmtemp()
        self.updatetile(x, y)

    def delete(self):
        self.frontend.eventstack.unregister_event(self.clickhash)
        del self.frontend.sprites['rightwindow']
        self._rmtemp()
        self.kill()
        self.frontend.screen.blit(self.background, (0,0))

    def registerclickevent(self):
        self.clickhash = self.frontend.eventstack.register_event("button1", self, self.click)
        if self.frontend.mode != 'editor':
            self.frontend.eventstack.register_event("keydown", self, self.keydown)
            self.has_focus = True

    def maploadsavename(self):
        name = self.gamemap.get('name','Enter map displayname here')
        self.mapname = TextInput(
            pygame.Rect(50, self.frontend.mapw+70, self.mapw /2,25),
            16, self.frontend.eventstack, 
            prompt=self.gamemap.get('name',name))
        mapload = Button('Load', self.load, [], self.frontend.eventstack,self.frontend.imagecache, pos=(self.mapw/2 + 50,self.frontend.mapw+67))
        mapsave = Button('Save', self.save, [], self.frontend.eventstack,self.frontend.imagecache, pos=(self.mapw/2 + 150,self.frontend.mapw+67))
        self._addtemp('mapname', self.mapname)
        self._addtemp('mapload', mapload)
        self._addtemp('mapsave', mapsave)        

    def loadmap(self, data, reload=False):
        if reload:
            self._rmtemp()
        self.registerclickevent()
        self.gamemap = GameMap(data)
        self.gamemap.initialize(data=data)
        if self.frontend.mode == 'editor':
            self.maploadsavename()
        for x in range(0,20):
            for y in range(0,20):
                scn_x = 50+(self.tilesize*x)
                scn_y = 65+(self.tilesize*y)
                self.image.blit(self.tileimage(x,y, self.tilesize),(self.tilesize*x, self.tilesize*y))
                self.tileicons(x,y, scn_x, scn_y, self.tilesize)

    def load(self):
        self._addtemp('te_mapselector',MapSelector(self.rect, self.frontend, self.loadmap))
        self.frontend.draw() 

    def save(self):
        if self.mapname.text:
            self.gamemap.put('name', self.mapname.text)
        filename = self.gamemap.save_to_file('maps')
        messages.error('Saved to: %s' % os.path.basename(filename))

    def player_can_goto(self, x, y):
        loc = self.frontend.game.player.location()
        xdiff = loc['x'] - x
        ydiff = loc['y'] - y
        distance = hypot(xdiff, ydiff)
        return distance <= 1.5 and self.gamemap.tile(x,y).canenter()

    def player_controls(self, x,y, surface):
        minx, miny = self.frontend.rightwindow_rect.x + 10, self.frontend.rightwindow_rect.y + 10
        maxx, maxy = minx + self.frontend.rightwindow_rect.w - 10, self.frontend.rightwindow_rect.h - 10
        if self.player_can_goto(x, y):
             player_go_here = Button('Go Here', 
                                    self.goto, 
                                    ['player', x, y],
                                    self.frontend.eventstack,
                                    self.frontend.imagecache,
                                    pos=(minx +180,miny + 10))
             self._addtemp('player_go_here', player_go_here)

    def keydown(self, event):
        messages.message('Processing event '+event.unicode)
        loc = self.frontend.game.player.location()
        x = loc['x']
        y = loc['y']
        if event.key == K_LEFT or event.unicode.upper() == 'A':
            x -= 1
        elif event.key == K_RIGHT or event.unicode.upper() == 'D':
            x += 1
        elif event.key == K_UP or event.unicode.upper() == 'W':
            y -= 1
        elif event.key == K_DOWN or event.unicode.upper() == 'S':
            y += 1
        else:
            return False
        if self.player_can_goto(x, y):
            self.goto('player', x, y)
        return True

    def goto(self, charname, x, y):
        sprite = self.frontend.sprites[charname]
        scn_x = 50+(self.tilesize*x)
        scn_y = 65+(self.tilesize*y)
        sprite.onarive = self.arrive_at
        sprite.onarive_params = [charname,x,y]
        sprite.goto = (scn_x, scn_y)

    def arrive_at(self, charname, x, y):
        if charname == 'player':
            self.frontend.game.player.moveto(self.gamemap, x,y)
            self.frontend.game.player.savetoslot()
        else:
            for char in self.frontend.game.characters:
                if char.get_hash() == charname:
                    char.moveto(self.gamemap, x, y)
                    char.savetoslot('characters')
                    break
        self.gamemap.savetoslot('maps')



    def tile_editor(self, x, y, surface):
        surface.blit(render_text('Edit tile', color=(255,0,0)),(280,10))
        minx, miny = self.frontend.rightwindow_rect.x + 10, self.frontend.rightwindow_rect.y + 10
        maxx, maxy = minx + self.frontend.rightwindow_rect.w - 10, self.frontend.rightwindow_rect.h - 10
        te_canenter = checkboxbtn('Player can enter tile ?', self.canenter, (x,y), self.frontend.eventstack,self.frontend.imagecache, pos=(minx + 180,miny + 60))
        te_revealed = checkboxbtn('Tile has been revealed ?', self.revealed, (x,y), self.frontend.eventstack,self.frontend.imagecache, pos=(minx + 180,miny + 90))
        te_canenter.checked = self.gamemap.tile(x,y).canenter()
        te_revealed.checked = self.gamemap.tile(x,y).revealed()
        if self.tile.background():
            self._addtemp('te_rotate', Button('Rotate background', 
                self.rotate, (x,y), self.frontend.eventstack,self.frontend.imagecache, pos=(minx + 180, miny + 120)))
        self._addtemp('te_canenter', te_canenter)
        self._addtemp('te_revealed', te_revealed)
        self._addtemp('te_set_background', Button('Set Background', 
            self.selectbg, (x,y), self.frontend.eventstack,self.frontend.imagecache, pos=(minx + 180, miny + 30)))
        if self.tile.background() and self.tile.canenter():
            te_additem = Button('Add Item', self.additem, [x,y], self.frontend.eventstack,self.frontend.imagecache, pos=(minx,miny + 160))
            te_addnpc = Button('Add NPC', self.addnpc, [x,y], self.frontend.eventstack,self.frontend.imagecache, pos=(minx + 120,miny + 160))
            te_onenter = Button('Events/OnEnter', self.onenter, [x,y], self.frontend.eventstack,self.frontend.imagecache, pos=(minx + 250,miny + 160))
            self._addtemp('te_additem', te_additem)
            self._addtemp('te_addnpc', te_addnpc)
            self._addtemp('te_onenter', te_onenter)
        te_clone_tile = Button('Clone Tile', self.clonetile, [x,y], self.frontend.eventstack,self.frontend.imagecache, pos=(minx,miny + 200))
        self._addtemp('te_clone', te_clone_tile)
        clone_coords = TextInput(
            pygame.Rect(minx + 150,  miny + 200, 100,25),
            16, self.frontend.eventstack, 
            prompt='%sx%s' %(x,y), layer=3)
        self._addtemp('te_clone_coords', clone_coords)
        debug(self.frontend.sprites)

    def clonetile(self, x,y):
        target=self.frontend.sprites['te_clone_coords'].text
        tx, ty = target.split('x')
        tx, ty = int(tx), int(ty)
        for iy in range(y,ty +1):
            for ix in range(x,tx +1):
                self.gamemap.copy_tile(x,y,ix,iy)
        self.updatetile(x, y)

    def selectlist(self, dirname,action, x, y):
        self._rmtemp()
        itemlist = []
        for itemfile in file_list(dirname):
            itemfile = os.path.basename(itemfile)
            itemlist.append(Item(load_yaml(dirname,itemfile)))
        c = ContainerDialog(self.rect,
            self.frontend,
            'Add %s' % dirname,
            self._layer + 1,
            items=itemlist,
            onclose=action,
            onclose_parms=[x,y],
            onselect=action,
            onselect_parms=[x,y],
            animation='view',
            can_add=False,
            can_remove=False)
        self._addtemp('te_listmanager' , c)

    def additem(self, x, y):
        self.selectlist('items', self.newitem, x, y)


    def addnpc(self, x, y):
        self.selectlist('characters', self.newnpc, x, y)

    def onenter(self,x,y):
        default = default_text
        data = self.gamemap.tile(x,y).get('events/onenter', default)
        data = editsnippet('\n'.join(data))
        tile = self.gamemap.tile(x,y)
        tile.put('events/onenter',data.split('\n'))
        self.gamemap.load_tile(x,y,tile)
        self.tile = self.gamemap.tile(x,y)
        self.updatetile(x, y)

    def newnpc(self, item, x,y):
        self._rmtemp()
        if item is not None:
            self.gamemap.addtotile( x, y, item, 'npc')
            debug(self.gamemap())
        self.tile = self.gamemap.tile(x,y)
        self.updatetile(x, y)

    def newitem(self, item,x,y):
        self._rmtemp()
        if item is not None:
            self.gamemap.addtotile( x, y, item, 'items')
        self.tile = self.gamemap.tile(x,y)
        self.updatetile(x, y)

    def selectbg(self, x, y):
        self._addtemp('te_tileselector',TileSelector(self.rect, self.frontend, self.setbg, (x,y)))

    def setbg(self, bgpath, x, y):
        map_x, map_y = x, y
        self.tile = self.gamemap.tile(map_x,map_y)
        self.tile.put('background', bgpath)
        self.updatetile(x,y) 
        x = x*self.tilesize+50
        y = y*self.tilesize+65
        self.click((x,y))

    def rotate(self, x,y):
        bgpath = imagepath(self.tile.background())
        rot = int(bgpath[3])
        if rot == 270:
            rot = 0
        else:
            rot += 90
        bgpath = [bgpath[0], bgpath[1], bgpath[2], str(rot)]
        bgpath = ':'.join([str(I) for I in bgpath])
        self.setbg(bgpath, x, y)


    def canenter(self, x, y):
        self.tile.canenter(self.frontend.sprites['te_canenter'].checked)
        self.updatetile(x, y)

    def revealed(self, x, y):
        self.tile.put('/revealed', self.frontend.sprites['te_canenter'].checked)
        self.updatetile(x, y)

    def updatetile(self, x, y):
        self.gamemap.load_tile(x,y,self.tile)
        self.loadmap(self.gamemap())
        self.dialog = FloatDialog(self.frontend.rightwindow_rect, self.frontend, layer=1)
        self._addtemp('rightwindow', self.dialog)
        zoomimage = self.tileimage(x, y, 128)
        self.dialog.image.blit(zoomimage, (15,15))
        self.zoomicons(x, y, self.frontend.rightwindow_rect.x + 15,self.frontend.rightwindow_rect.y + 15)
        if self.frontend.mode == 'editor':
            self.maploadsavename()
            self.tile_editor(x,y, self.dialog.image)
        else:
            self.player_controls(x,y, self.dialog.image)

    def click(self, pos):
        self._rmtemp()
        x, y = pos
        x = x - 50
        y = y - 65
        map_x = int(x / self.tilesize)
        map_y = int(y / self.tilesize)
        self.tile = self.gamemap.tile(map_x, map_y)
        if self.tile.get('revealed', False) or self.frontend.mode == 'editor':
            self.updatetile(map_x, map_y)
Пример #33
0
"""This file contains the main Game logic for fruitsweeper"""

import time
from gamemap import GameMap
from ai import AI

WIDTH = 10
MINES = 10
game_map = GameMap(MINES, WIDTH)
player = AI()
turns_counter = 0
init_time = time.time()

while not game_map.is_end_game():
    action = player.play(game_map.get_map_format())
    turns_counter += 1
    if action["action"] == "explore":
        game_map.explore(action["X"], action["Y"])
    else:
        if action["action"] == "flag":
            game_map.flag(action["X"], action["Y"])
        else:
            if action["action"] == "unflag":
                game_map.unflag(action["X"], action["Y"])

    print(game_map.to_string())

end_time = time.time()
elapsed_time = end_time - init_time

print("You won! in " + str(turns_counter) + " turns " + "and in " +