コード例 #1
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)
コード例 #2
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()
コード例 #3
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
コード例 #4
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
コード例 #5
0
def main():
    economy = Economy()
    output = Output()
    curmap = GameMap(economy)
    myevol = RandomUnitEvolution()
    print(
        myevol.evolveEachUnit(
            economy, curmap, Game.selectArmy(economy, curmap, "white",
                                             output)))
コード例 #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 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)
コード例 #8
0
ファイル: gameserver.py プロジェクト: Ecoblockchain/maplegym
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)
コード例 #9
0
ファイル: server.py プロジェクト: LHGames-2018/Python-bot
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
コード例 #10
0
ファイル: main.py プロジェクト: enginertas/technical_training
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"
コード例 #11
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())
コード例 #12
0
ファイル: engine.py プロジェクト: Coul33t/iso_tbs
    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'
コード例 #13
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")
コード例 #14
0
ファイル: game.py プロジェクト: mikemill/misc
 def __init__(self):
     self.map = GameMap()
     self.player = None
     self.grue = None
     self.turn = 0
コード例 #15
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
コード例 #16
0
ファイル: builder.py プロジェクト: Czechball/TMTrackNN
    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
コード例 #17
0
ファイル: game.py プロジェクト: lm-sec/csgames_exam_dele_2018
"""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 " +
コード例 #18
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)