Example #1
0
def run(sample_number, resolution):
    global engine, screen
    print("hi")
    screen = pygame.display.set_mode(resolution if resolution else (600, 600))
    engine = Engine(screen)
    globals()[f"sample_{sample_number}"]()
    engine.start()
Example #2
0
    def __init__(self, datafile, db, log):
        with open(datafile, 'rb') as src:
            self.data = Data(src)

        self.engine = Engine(self.data, log=log)
        self.db = db
        self.log = log
Example #3
0
 def __init__(self,max_moves,ai_config,opponent_config,param_ranges,n_iter,n_games,init_params,n_batches = 1):
     self.ai_config = ai_config
     self.opponent_config = opponent_config
     self.param_ranges = param_ranges
     self.n_iter = n_iter
     self.n_games = n_games
     self.max_moves = max_moves
     self.engine = Engine(self.max_moves,self.ai_config, self.opponent_config)
     self.params = init_params
     self.n_batches = n_batches
     self.score_history = []
     self.the_good_ones = []
    def setUp(self):
        self.cleaner = Mock()
        self.cleaner.position = MagicMock(return_value=(1, 1))

        self.environment = Mock()

        self.touch_sensor = Mock()
        self.photo_sensor = Mock()
        self.infrared_sensor = Mock()

        self.engine = Engine(
            self.cleaner, self.environment, self.touch_sensor, self.photo_sensor, self.infrared_sensor,
        )
Example #5
0
def main(datafile):
    ''' Text Adventure CLI

        DATAFILE - Path to ScottFree data file
    '''
    data = Data(datafile)
    state = StateFromGameData(data)
    engine = Engine(data)

    state = engine.start_game(state)
    click.echo(state.last_message)

    repl = REPL(engine, state)
    repl.cmdloop()
Example #6
0
def main(datafile):
    ''' Text Adventure CLI

        DATAFILE - Path to ScottFree data file
    '''
    data = Data(datafile)
    state = StateFromGameData(data)
    engine = Engine(data)

    state = engine.start_game(state)
    click.echo(state.last_message)

    repl = REPL(engine, state)
    repl.cmdloop()
Example #7
0
    def __init__(self, datafile, db, log):
        with open(datafile, 'rb') as src:
            self.data = Data(src)

        self.engine = Engine(self.data, log=log)
        self.db = db
        self.log = log
Example #8
0
class Server(object):
    def __init__(self, datafile, db, log):
        with open(datafile, 'rb') as src:
            self.data = Data(src)

        self.engine = Engine(self.data, log=log)
        self.db = db
        self.log = log

    def play(self, player, command):
        self.log.debug('Searching for player %s in DB', player)
        db_player = self.db.session.query(User).filter_by(
            sender_id=player).all()

        if db_player:
            self.log.debug('Found player; loading state')
            state = StateFromDatabase(db_player[0])
            self.log.debug('Location: %s', state.current_location)
            self.log.debug('Flags: %s', state.bitflags)
        else:
            self.log.debug('New player; take initial state from game data')
            state = StateFromGameData(self.data)
            new_state = self.engine.start_game(state)
            self._save_to_db(player, new_state)
            return new_state.last_message

        self.log.debug('Command: %s', command)
        new_state = self.engine.process(state, command)

        self._save_to_db(player, new_state)

        return new_state.last_message

    def _save_to_db(self, player, state):
        self.log.debug('Bitflags: %s', state.bitflags)

        item_string = ','.join(str(item.location) for item in state.items)

        db_state = User(
            sender_id=player,
            game_id=self.data.version['game_id'],
            bitflags=state.serialise_bitflags(),
            items=item_string,
            current_location=state.current_location,
        )
        self.db.session.merge(db_state)
        self.db.session.commit()
    def __init__(self, start=None, n_games=10, start_temp=1024, factor=2):
        self.start = start
        if start == None:
            self.start = get_random_start()

        self.delta = 0.00001
        self.n_games = n_games
        #make both of them random, but the simpel start state
        self.player_config = {
            Settings.AI.value: True,  #should this be Ai or person
            Settings.START_TYPE.value:
            StartType.SIMPLE.value,  #what kind of start state
            Settings.START_PARAMS.value: [],  #any parameters for the stater
            Settings.SEARCH_TYPE.value:
            SearchType.RANDOM.value,  #what kind of search is happening
            Settings.SEARCH_PARAMS.value: [],  #any parameters for the search
            Settings.AI_TYPE.value: AIType.NONE.value,  # what is the AI
            Settings.AI_PARAMS.value: []  #any params for the ai
        }
        self.opponent_config = {
            Settings.AI.value: True,  #should this be Ai or person
            Settings.START_TYPE.value:
            StartType.CHAMPION.value,  #what kind of start state
            Settings.START_PARAMS.value: [],  #any parameters for the stater
            Settings.SEARCH_TYPE.value:
            SearchType.RANDOM.value,  #what kind of search is happening
            Settings.SEARCH_PARAMS.value: [],  #any parameters for the search
            Settings.AI_TYPE.value: AIType.NONE.value,  # what is the AI
            Settings.AI_PARAMS.value: []  #any params for the ai
        }

        self.engine = Engine(1000)
        self.best, stats = self.simulated_annealing(start_temp, factor)
        print(self.best)
        f = open("train/simulated_annealing_results.txt", "a")
        t = open("train/simulated_annealing_factors.txt", "a")
        s = open("train/simuated_annealing_start_state.txt", "a")
        g = open("train/simulated_annealing_stats.txt", "a")
        f.write("{}\n".format(self.best))
        t.write("{}\n".format([start_temp, factor]))
        s.write("{}\n".format(self.start))
        g.write("{}\n".format(stats))
        g.close()
        s.close()
        t.close()
        f.close()
Example #10
0
class Server(object):
    def __init__(self, datafile, db, log):
        with open(datafile, 'rb') as src:
            self.data = Data(src)

        self.engine = Engine(self.data, log=log)
        self.db = db
        self.log = log

    def play(self, player, command):
        self.log.debug('Searching for player %s in DB', player)
        db_player = self.db.session.query(User).filter_by(sender_id=player).all()

        if db_player:
            self.log.debug('Found player; loading state')
            state = StateFromDatabase(db_player[0])
            self.log.debug('Location: %s', state.current_location)
            self.log.debug('Flags: %s', state.bitflags)
        else:
            self.log.debug('New player; take initial state from game data')
            state = StateFromGameData(self.data)
            new_state = self.engine.start_game(state)
            self._save_to_db(player, new_state)
            return new_state.last_message

        self.log.debug('Command: %s', command)
        new_state = self.engine.process(state, command)

        self._save_to_db(player, new_state)

        return new_state.last_message

    def _save_to_db(self, player, state):
        self.log.debug('Bitflags: %s', state.bitflags)

        item_string = ','.join(str(item.location) for item in state.items)

        db_state = User(sender_id=player,
                        game_id=self.data.version['game_id'],
                        bitflags=state.serialise_bitflags(),
                        items=item_string,
                        current_location=state.current_location,
                        )
        self.db.session.merge(db_state)
        self.db.session.commit()
    def test_should_set_home_when_engine_init(self):
        home_position = (1, 1)
        self.cleaner.position = MagicMock(return_value=home_position)
        environment = Mock()

        Engine(
            self.cleaner, environment, self.touch_sensor, self.photo_sensor, self.infrared_sensor,
        )

        environment.set_home.assert_called_once_with(home_position)
Example #12
0
    def __init__(self, menu, players):
        super().__init__()

        self.menu = menu

        self.setWindowTitle('Code with Fire')
        self.setGeometry(200, 50, 800, 650)

        self.player_names = players
        self.alive_players = len(players)

        self.game_engine = Engine()
        self.game_screen = Screen(self.game_engine)
        self.score_manager = ScoreManager(self.game_screen)

        self.setCentralWidget(self.game_screen)
        self.create_menu_bar()

        self.start_game(players)
Example #13
0
    def __init__(self, config, max_moves):
        self.ai_configs = []
        for filename in config[AI_FIELD][AIType.REACHABLE.value]:
            self.ai_configs += read_file_into_configs(filename,
                                                      reachable_config)
        for filename in config[AI_FIELD][AIType.MODIFIED_REACHABLE.value]:
            self.ai_configs += read_file_into_configs(filename,
                                                      mod_reachable_config)
        for filename in config[AI_FIELD][AIType.PIECE_BASED_ADD.value]:
            self.ai_configs += read_file_into_configs(filename,
                                                      piecebased_config_add)
        for filename in config[AI_FIELD][AIType.PIECE_BASED_MUL.value]:
            self.ai_configs += read_file_into_configs(filename,
                                                      piecebased_config_mul)

        self.start_configs = []

        for filename in config[START_FIELD]:
            self.start_configs += read_file_into_configs(
                filename, flexible_start_config)

        self.engine = Engine(max_moves, None, None)

        self.max_moves = max_moves
Example #14
0
def lint_and_run_game(pylint_args, fullscreen, resolution):
    """Run pylint, get the output, parse it, initialize the game and run it."""
    animal_groups = create_animals(parse(lint(pylint_args)))
    flags = pygame.FULLSCREEN if fullscreen else 0
    if not resolution and not fullscreen:
        resolution = (600, 600)
    screen = pygame.display.set_mode((0, 0) if fullscreen else resolution,
                                     flags)
    organize_groups(screen, animal_groups)
    engine = Engine(screen)
    for animal_group in animal_groups:
        engine.add_animals(*animal_group)
    engine.start()
Example #15
0
def test_game():
    animal1 = Animal(shape="Y", max_health=2, size=40)
    animal2 = Animal(shape="X", max_health=2, size=40)

    animal1.also_likes_to_eat(animal2)
    animal2.also_likes_to_eat(animal1)

    screen = pygame.display.set_mode((600, 600))

    animal1.put_relative(30, 30, screen)
    animal2.put_relative(60, 60, screen)

    engine = Engine(screen)
    engine.add_animals(animal1, animal2)
    engine.start()
Example #16
0
def test_is_human():
    engine = Engine()
    player = Player(True, engine)
    assert player.is_human()
Example #17
0
"""
// Filename : Instances
// Created by: @ngeorgj

This file holds the base instances for the game, don't change anything!
"""

from game.engine import Engine
from game.cgame import Game

game_engine = Engine()

rpg = Game()
rpg.engine = game_engine
class EngineTestCase(unittest.TestCase):

    def setUp(self):
        self.cleaner = Mock()
        self.cleaner.position = MagicMock(return_value=(1, 1))

        self.environment = Mock()

        self.touch_sensor = Mock()
        self.photo_sensor = Mock()
        self.infrared_sensor = Mock()

        self.engine = Engine(
            self.cleaner, self.environment, self.touch_sensor, self.photo_sensor, self.infrared_sensor,
        )

    def test_should_get_score(self):
        score = self.engine.score()

        self.assertEqual(score, 0)

    def test_should_lose_score_when_take_action(self):
        self.engine.push_action("go_forward")

        score = self.engine.score()

        self.assertEqual(score, -1)

    def test_should_get_score_when_successfully_clean_up(self):
        self.cleaner.position = MagicMock(return_value=(1, 1))
        self.environment.grids = MagicMock(return_value=[
            [1, 1],
            [0, 1],
        ])
        self.engine.push_action("clean")

        score = self.engine.score()

        self.assertEqual(score, 100 - 1)

    def test_should_do_nothing_and_terminate_when_turn_off_at_the_home_location(self):
        self.environment.home = MagicMock(return_value=(1, 1))
        self.cleaner.position = MagicMock(return_value=(1, 1))

        self.engine.push_action("turn_off")
        score = self.engine.score()

        self.assertEqual(score, -1)

    def test_should_reduce_score_and_terminate_when_turn_off_at_the_different_location(self):
        self.engine.push_action("turn_off")
        self.environment.home = MagicMock(return_value=(2, 2))
        self.cleaner.position = MagicMock(return_value=(1, 1))

        score = self.engine.score()

        self.assertEqual(score, - 1000 - 1)

    def test_should_not_get_score_when_clean_up_empty_tile(self):
        self.cleaner.position = MagicMock(return_value=(0, 0))
        self.environment.grids = MagicMock(return_value=[
            [1, 1],
            [0, 1],
        ])
        self.engine.push_action("clean")

        score = self.engine.score()

        self.assertEqual(score, -1)

    def test_should_set_home_when_engine_init(self):
        home_position = (1, 1)
        self.cleaner.position = MagicMock(return_value=home_position)
        environment = Mock()

        Engine(
            self.cleaner, environment, self.touch_sensor, self.photo_sensor, self.infrared_sensor,
        )

        environment.set_home.assert_called_once_with(home_position)

    def test_should_act_and_update_when_move(self):
        next_cleaner = Mock()
        self.cleaner.act = MagicMock(return_value=next_cleaner)

        self.engine.push_action("go_forward")

        self.cleaner.act.assert_called_with("go_forward")
        self.assertEqual(self.engine._latest_cleaner, next_cleaner)
        self.touch_sensor.set_cleaner.assert_called_with(next_cleaner)
        self.photo_sensor.set_cleaner.assert_called_with(next_cleaner)
        self.infrared_sensor.set_cleaner.assert_called_with(next_cleaner)
        self.assertIn(next_cleaner, self.engine._history)

    def test_should_call_sensors_to_retrieve_information(self):
        self.touch_sensor.run = MagicMock(return_value=1)
        self.photo_sensor.run = MagicMock(return_value=0)
        self.infrared_sensor.run = MagicMock(return_value=1)

        results = self.engine.sensors()

        self._assertSensors(results, (1, 0, 1))

    def test_should_clean_room_and_set_new_grids(self):
        self.cleaner.position = MagicMock(return_value=(1, 1))
        self.environment.grids = MagicMock(return_value=[
            [1, 1],
            [0, 1],
        ])

        self.engine.push_action("clean")

        self.environment.set_grids.assert_called_once_with([
            [1, 0],
            [0, 1],
        ])

    def _assertSensors(self, results, expectations):
        touch_sensor, photo_sensor, infrared_sensor = results
        self.assertEqual(touch_sensor, expectations[0])
        self.assertEqual(photo_sensor, expectations[1])
        self.assertEqual(infrared_sensor, expectations[2])
Example #19
0
def test_constructor():
    #simple test to make sure that the constructor runs
    my_engine = Engine()
Example #20
0
    #        get_image_data())
    #game_window.set_icon(icon)


    class Score:
        def __init__(self):
            self.meters = 0
            self.top = 0

        def __iadd__(self, value):
            self.meters += value
            if self.meters > self.top:
                self.top = self.meters
            return self

    score = Score()

    title = Title(assets, score)
    engine = Engine(assets, score)
    director = Director(constants.VWIDTH * 2,
                        constants.VHEIGHT * 2,
                        caption="Fuel4TheLight",
                        vwidth=constants.VWIDTH,
                        vheight=constants.VHEIGHT)
    director.set_background_color(0., 0., 0.)
    Director.add_scene("title", title)
    Director.add_scene("engine", engine)
    Director.set_scene("title")

    pyglet.app.run()
Example #21
0
import game.chapter_one.main
import game.chapter_two.main
from game.engine import Engine, SceneMap

print("Starting the engine...")
a_map = SceneMap()
a_game = Engine(a_map)
a_game.play()
Example #22
0
class GUI:
    def ind_map_click(self, i, j):
        def map_click(throw_me_away):
            #ignore if the current player ia an Ai
            print("click")
            if self.player1_turn and self.player1_config[Settings.AI.value]:
                return None
            if not self.player1_turn and self.player2_config[
                    Settings.AI.value]:
                return None

            if self.button_counter % 2 is 0:
                self.clicked_buttons.append((i, j))
                self.button_counter += 1
            else:
                self.clicked_buttons.append((i, j))
                self.button_counter += 1
                p = self.e.player1
                if not self.player1_turn:
                    p = self.e.player2
                print(self.clicked_buttons)
                p.set_move(self.clicked_buttons)
                turn = self.e.make_move()
                #print(self.curselection())
                print(i, j)
                if turn == self.player1_turn:
                    self.clicked_buttons = []
                    self.button_counter = 0
                else:
                    self.clicked_buttons = []
                    self.button_counter = 0
                    self.player1_turn = not self.player1_turn
                    self.update()
                    if ((self.player1_turn
                         and self.player1_config[Settings.AI.value])
                            or (not self.player1_turn
                                and self.player2_config[Settings.AI.value])):
                        print("manual move setting up next move")
                        self.master.after(MS_BETWEEN_MOVES, self.ai_move)

        return map_click

    def __init__(self, master):
        self.tiles = []
        self.textids = []
        self.master = master
        self.frame = Frame(master)
        self.canvas = Canvas(self.frame, width=510, height=510)

        Grid.rowconfigure(master, 0, weight=1)
        Grid.columnconfigure(master, 0, weight=1)
        self.frame.grid(row=0, column=0)

        # self.player1_config = {
        #         Settings.AI.value : True, #should this be Ai or person
        #         Settings.START_TYPE.value : StartType.RANDOM.value, #what kind of start state
        #         Settings.START_PARAMS.value : [], #any parameters for the stater
        #         Settings.SEARCH_TYPE.value : SearchType.RANDOM.value, #what kind of search is happening
        #         Settings.SEARCH_PARAMS.value : [], #any parameters for the search
        #         Settings.AI_TYPE.value : AIType.NONE.value, # what is the AI
        #         Settings.AI_PARAMS.value : [] #any params for the ai
        #     }
        self.player1_config = {
            'ai parameters': [
                -1, 1, 0, 0, 0, 0, -1, 1, -1, 0, 1, -1, -1, 1, 0, -1, 0, 0, 1,
                1, 0
            ],
            'eval_type':
            'modified_reachable',
            'search_parmeters': [],
            'FILENAME':
            'train/good_modified_reachable.txt',
            'params_for_start_state': [],
            'type_of_start_state':
            'champion',
            'is an ai':
            True,
            'type_of_search':
            'no searcher'
        }

        self.player2_config = {
            Settings.AI.value: True,  #should this be Ai or person
            Settings.START_TYPE.value:
            StartType.RANDOM.value,  #what kind of start state
            Settings.START_PARAMS.value: [],  #any parameters for the stater
            Settings.SEARCH_TYPE.value:
            SearchType.RANDOM.value,  #what kind of search is happening
            Settings.SEARCH_PARAMS.value: [],  #any parameters for the search
            Settings.AI_TYPE.value: AIType.NONE.value,  # what is the AI
            Settings.AI_PARAMS.value: []  #any params for the ai
        }

        self.tile_colors = [[
            "#DBE0FF", "#C7CCF7", "#B3B9EF", "#9FA6E8", "#8C92E0", "#787FD9",
            "#646CD1", "#5059CA", "#3D45C2", "#2932BB", "#151FB3", "#020CAC"
        ],
                            [
                                "#FFDBE0", "#F7C7CD", "#EFB3BB", "#E89FA8",
                                "#E08C96", "#D97884", "#D16471", "#CA505F",
                                "#C23D4D", "#BB293A", "#B31528", "#AC0216"
                            ]]

        self.hidden_color = ["#787FD9", "#D97884"]

        self.e = Engine(1000, self.player1_config, self.player2_config, False)
        self.e.setup_board()
        if not self.player1_config[Settings.AI.value]:
            board = self.e.get_board(1, True)
        else:
            board = self.e.get_board(None, True)
        self.win = False  #winner trigger
        self.player1_turn = True  #player 1 turn trigger
        self.winning_player = 0
        self.button_counter = 0
        self.clicked_buttons = []
        # board setup
        #print(board)
        for i in range(10):
            for j in range(10):
                tag = i * 10 + j
                if board[i][j] == 111:
                    text_item = ""
                    tile_color = "white"
                    tile_outline = "white"
                elif board[i][j] == 0:
                    text_item = ""
                    tile_outline = "black"
                    tile_color = "grey"
                elif board[i][j] % 1000 == piece_diplay_map[
                        pieces.HIDDEN.value]:
                    text_item = ""
                    tile_outline = "black"
                    tile_color = self.hidden_color[board[i][j] / 1000 - 2]
                else:
                    text_item = str(board[i][j] % 100)
                    tile_outline = "black"
                    #print(board[i][j])
                    #print(board[i][j]/100 - 2)
                    #print(board[i][j]%100 - 1)
                    tile_color = self.tile_colors[board[i][j] / 100 -
                                                  2][board[i][j] % 100 - 1]
                tile = self.canvas.create_rectangle(j * 50 + 10,
                                                    i * 50 + 10,
                                                    j * 50 + 50,
                                                    i * 50 + 50,
                                                    outline=tile_outline,
                                                    fill=tile_color,
                                                    activefill="cyan",
                                                    tags=tag)
                textid = self.canvas.create_text(j * 50 + 30,
                                                 i * 50 + 30,
                                                 text=text_item,
                                                 tags=str(tag) + "text")

                rect_handler = self.ind_map_click(9 - i, j)

                self.tiles.append(tile)
                self.textids.append(textid)
                self.canvas.tag_bind(tile, "<Button-1>", rect_handler)
        self.canvas.grid(row=0, column=0)

    def ai_move(self):
        print("ai_move called")
        if self.player1_turn and not self.player1_config[Settings.AI.value]:
            return None
        if not self.player1_turn and not self.player2_config[
                Settings.AI.value]:
            return None

        self.player1_turn = self.e.make_move()
        self.update()

        winner = self.e.get_winner()
        if winner:
            #what do we want to happen on win
            pass
        else:
            if ((self.player1_turn and self.player1_config[Settings.AI.value])
                    or (not self.player1_turn
                        and self.player2_config[Settings.AI.value])):
                print("ai move setting up next move")
                self.master.after(MS_BETWEEN_MOVES, self.ai_move)

    def update(self):
        #two ais playing
        if (self.player2_config[Settings.AI.value]
                and self.player1_config[Settings.AI.value]):

            board = self.e.get_board(None, True)

        #player 1 is manual and 2 is an ai
        elif (self.player2_config[Settings.AI.value]
              and not self.player1_config[Settings.AI.value]):

            board = self.e.get_board(1, True)

        #player 1 is an ai and 2 is manual
        elif (not self.player2_config[Settings.AI.value]
              and self.player1_config[Settings.AI.value]):

            board = self.e.get_board(2, True)

        else:  #both are manual players
            if self.player1_turn:
                board = self.e.get_board(1, True)
            else:
                board = self.e.get_board(2, True)

        for i in range(10):
            for j in range(10):
                if board[i][j] == 111:
                    text_item = ""
                    tile_color = "white"
                elif board[i][j] == 0:
                    text_item = ""
                    tile_color = "grey"
                elif board[i][j] % 1000 == piece_diplay_map[
                        pieces.HIDDEN.value]:
                    text_item = ""
                    tile_color = self.hidden_color[board[i][j] / 1000 - 2]
                else:
                    text_item = str(board[i][j] % 100)
                    tile_color = self.tile_colors[board[i][j] / 100 -
                                                  2][board[i][j] % 100 - 1]
                self.canvas.itemconfig(self.tiles[i * 10 + j], fill=tile_color)
                self.canvas.itemconfig(self.textids[i * 10 + j],
                                       text=text_item)
Example #23
0
class Tournement:
    def __init__(self, config, max_moves):
        self.ai_configs = []
        for filename in config[AI_FIELD][AIType.REACHABLE.value]:
            self.ai_configs += read_file_into_configs(filename,
                                                      reachable_config)
        for filename in config[AI_FIELD][AIType.MODIFIED_REACHABLE.value]:
            self.ai_configs += read_file_into_configs(filename,
                                                      mod_reachable_config)
        for filename in config[AI_FIELD][AIType.PIECE_BASED_ADD.value]:
            self.ai_configs += read_file_into_configs(filename,
                                                      piecebased_config_add)
        for filename in config[AI_FIELD][AIType.PIECE_BASED_MUL.value]:
            self.ai_configs += read_file_into_configs(filename,
                                                      piecebased_config_mul)

        self.start_configs = []

        for filename in config[START_FIELD]:
            self.start_configs += read_file_into_configs(
                filename, flexible_start_config)

        self.engine = Engine(max_moves, None, None)

        self.max_moves = max_moves

    def play_against(self, config1, config2, n_games=5):
        player1_wins = 0
        player2_wins = 0
        for i in range(n_games):
            self.engine.restart(self.max_moves, config1, config2)
            winner = self.engine.run()
            if winner == 1:
                player1_wins += 1
            elif winner == 2:
                player2_wins += 1

        if player1_wins > player2_wins:
            return 1
        elif player1_wins < player2_wins:
            return 2
        else:
            return 0

    def playoff_helper(self, param_lst, num):
        this_round = param_lst
        next_round = []

        i = 1
        while len(this_round) > num:
            print("round {}, {} configurations left".format(
                i, len(this_round)))
            i += 1
            random.shuffle(this_round)
            for i in range(int(len(this_round) / 2)):
                config1 = param_lst[i]
                config2 = param_lst[i + 1]
                # do a playoff and the winner goes to the next round
                winner = self.play_against(config1, config2)
                if winner == 1:
                    next_round.append(config1)
                elif winner == 2:
                    next_round.append(config2)
                else:
                    #in the event of a tie, play again with twice the number of
                    #moves to try to determine the winner
                    self.engine.restart(2 * self.max_moves, config1, config2)
                    winner = self.engine.run()
                    if winner == 1:
                        next_round.append(config1)
                    elif winner == 2:
                        next_round.append(config2)
                    else:
                        #double tie indicates the configs are about the same
                        #so its safe to just randomly pick one to move on to
                        #the next round
                        if random.random() < 0.5:
                            next_round.append(config1)
                        else:
                            next_round.append(config2)
            if (len(this_round) % 2 != 0):
                next_round.append(this_round[-1])

            this_round = next_round
            next_round = []

        return this_round

    def playoff(self, num=1):
        print('finding the best ai configurations')
        best_ai = self.playoff_helper(self.ai_configs, num)
        print('finding the best start state')
        best_start = self.playoff_helper(self.start_configs, num)
        return best_ai, best_start
Example #24
0
import game.chapter_two.main
import game.chapter_one.main
from game.engine import Engine, SceneMap

print("Starting the engine...")
a_map = SceneMap()
a_game = Engine(a_map)
a_game.play()
Example #25
0
File: test.py Project: and3rson/gs
#!/usr/bin/env python2

# from network import Channel
# import socket
# import time
# from ctypes import cdll
import platform
# import sys
# import os

# sys.path.append(os.path.abspath())

from game.engine import Engine
engine = Engine()
engine.start()

def init_steam():
#     arch, _ = platform.architecture()
#     if arch == '64bit':
#         i9c = cdll.LoadLibrary('./i9c_64.so')
#     else:
#         i9c = cdll.LoadLibrary('./i9c_32.so')
#
#     i9c.api_init()
#     i9c.api_request_ticket()
#     #time.sleep(3)
#     #i9c.api_get_ticket()
    libsteam_api = cdll.LoadLibrary('old/libsteam_api.so')
    libsteam_api.SteamAPI_Init()
#     steam_
    # steam_user = libsteam_api.SteamUser()
 def main(self):
     Engine(filename=self.params.file).play()
Example #27
0
File: test.py Project: PlumpMath/gs
#!/usr/bin/env python2

# from network import Channel
# import socket
# import time
# from ctypes import cdll
import platform
# import sys
# import os

# sys.path.append(os.path.abspath())

from game.engine import Engine
engine = Engine()
engine.start()


def init_steam():
    #     arch, _ = platform.architecture()
    #     if arch == '64bit':
    #         i9c = cdll.LoadLibrary('./i9c_64.so')
    #     else:
    #         i9c = cdll.LoadLibrary('./i9c_32.so')
    #
    #     i9c.api_init()
    #     i9c.api_request_ticket()
    #     #time.sleep(3)
    #     #i9c.api_get_ticket()
    libsteam_api = cdll.LoadLibrary('old/libsteam_api.so')
    libsteam_api.SteamAPI_Init()
class LSStartStateTrainer:
    def __init__(self, start=None, n_games=10, start_temp=1024, factor=2):
        self.start = start
        if start == None:
            self.start = get_random_start()

        self.delta = 0.00001
        self.n_games = n_games
        #make both of them random, but the simpel start state
        self.player_config = {
            Settings.AI.value: True,  #should this be Ai or person
            Settings.START_TYPE.value:
            StartType.SIMPLE.value,  #what kind of start state
            Settings.START_PARAMS.value: [],  #any parameters for the stater
            Settings.SEARCH_TYPE.value:
            SearchType.RANDOM.value,  #what kind of search is happening
            Settings.SEARCH_PARAMS.value: [],  #any parameters for the search
            Settings.AI_TYPE.value: AIType.NONE.value,  # what is the AI
            Settings.AI_PARAMS.value: []  #any params for the ai
        }
        self.opponent_config = {
            Settings.AI.value: True,  #should this be Ai or person
            Settings.START_TYPE.value:
            StartType.CHAMPION.value,  #what kind of start state
            Settings.START_PARAMS.value: [],  #any parameters for the stater
            Settings.SEARCH_TYPE.value:
            SearchType.RANDOM.value,  #what kind of search is happening
            Settings.SEARCH_PARAMS.value: [],  #any parameters for the search
            Settings.AI_TYPE.value: AIType.NONE.value,  # what is the AI
            Settings.AI_PARAMS.value: []  #any params for the ai
        }

        self.engine = Engine(1000)
        self.best, stats = self.simulated_annealing(start_temp, factor)
        print(self.best)
        f = open("train/simulated_annealing_results.txt", "a")
        t = open("train/simulated_annealing_factors.txt", "a")
        s = open("train/simuated_annealing_start_state.txt", "a")
        g = open("train/simulated_annealing_stats.txt", "a")
        f.write("{}\n".format(self.best))
        t.write("{}\n".format([start_temp, factor]))
        s.write("{}\n".format(self.start))
        g.write("{}\n".format(stats))
        g.close()
        s.close()
        t.close()
        f.close()

    def evaluate(self, last_start, next_start):
        wins = 0
        self.player_config[Settings.START_PARAMS.value] = next_start
        self.opponent_config[Settings.START_PARAMS.value] = last_start

        for i in range(self.n_games):
            self.engine.restart(1000, self.player_config, self.opponent_config)
            res = self.engine.run()
            if res == 0:
                wins += 0.5
            else:
                wins += (res == 1)

        print(float(self.n_games - wins) / self.n_games)
        return float(self.n_games - wins) / self.n_games

    def get_random_next(self, last_start):
        i = int(random.random() * len(last_start))
        j = i
        while j == i:
            j = random.random() * len(last_start)

        next_start = copy.copy(last_start)
        temp = next_start[i]
        next_start[i] = next_start[j]
        next_start[j] = temp
        return next_start

    def get_similar_random_next(self, last_start):
        #want to swap two neighboring pieces
        s1 = int(random.random() * len(last_start))
        i1, j1 = s1 / 10, s1 % 10
        s2 = s1

        valid = False
        while (not valid):
            n = int(random.random() * 8)
            count = 0
            for i2 in range(i1 - 1, i1 + 2):
                if valid: break
                for j2 in range(j1 - 1, j1 + 2):
                    if valid: break
                    if (i1 == i2 and j1 == j2): continue
                    s2 = 10 * i2 + j2
                    if (count == n):
                        if (not s2 < 0) and (not s2 >= len(last_start)):
                            #print(s2)
                            valid = True

                    count += 1

        next_start = copy.copy(last_start)

        #print("s1 : {}".format(s1))
        #print("s2 : {}".format(s2))

        temp = next_start[s1]
        next_start[s1] = next_start[s2]
        next_start[s2] = temp
        return next_start

    def simulated_annealing(self, start_temp, factor):
        cur = self.start
        temp = start_temp
        stats = []
        while True:
            if temp <= self.delta: return cur, stats
            next_start = self.get_similar_random_next(cur)
            e = self.evaluate(cur, next_start)
            stats.append(e)
            if (e > 0.5):
                cur = next_start
            else:
                should_use_anyways = random.random()
                p = np.exp((e - 0.5) / temp)
                if (should_use_anyways < p):
                    cur = next_start
            temp = temp / factor
Example #29
0
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     self.engine = Engine(consumer=self)
Example #30
0
class GBRTTrainer(): #trains using Bayesian global optimization with GBRT against random play
    def __init__(self,max_moves,ai_config,opponent_config,param_ranges,n_iter,n_games,init_params,n_batches = 1):
        self.ai_config = ai_config
        self.opponent_config = opponent_config
        self.param_ranges = param_ranges
        self.n_iter = n_iter
        self.n_games = n_games
        self.max_moves = max_moves
        self.engine = Engine(self.max_moves,self.ai_config, self.opponent_config)
        self.params = init_params
        self.n_batches = n_batches
        self.score_history = []
        self.the_good_ones = []

    def objective(self,params):
        self.ai_config[Settings.AI_PARAMS.value] = params
        wins = 0
        for i in range(self.n_games):
            self.engine.restart(self.max_moves,self.ai_config,self.opponent_config)
            winner = self.engine.run()
            if winner == 1:
                wins += 1.0
            elif winner == 0:
                wins += 0.5
        print wins / self.n_games
        self.score_history.append(wins / self.n_games)
        if(wins / self.n_games) >= .99:
            #print(params)
            self.the_good_ones.append(params)
        #return 1 - (wins / self.n_games)
        return - self.engine.get_value(1, 100, -1, 500)
        #res = 0
        #for i in range(self.n_games):
        #    self.engine.restart(self.max_moves,self.ai_config,self.opponent_config)
        #    self.engine.run()
        #    val = self.engine.get_value(1,100,-1,500)
        #    res += val
        #print res
        #self.score_history.append(res)
        #return -res


    def train(self):
        opt = Optimizer(self.param_ranges,"GP")
        r = opt.run(self.objective,n_iter=self.n_iter)
        self.params = r.x
        #print("trained paramaters are: ")
        #print(r.x)

    def objective_batchwise(self,params):
        full_params = self.params[:self.training_param_range[0]] + params + self.params[self.training_param_range[1]:]
        self.ai_config[Settings.AI_PARAMS.value] = full_params
        wins = 0
        for i in range(self.n_games):
            self.engine.restart(self.max_moves,self.ai_config,self.opponent_config)
            self.engine.run()
            val = self.engine.get_value(1,100,-1,500)
            res += val
        print res
        return -res

    def train_batchwise(self):
        opt = Optimizer(self.param_ranges,"GP")
        for batch in range(self.n_batches):
            print("starting a batch")
            for start in range(10):
                print("starting a round of optimization")
                self.training_param_range = [start*10, start*10 + 10]
                opt = Optimizer(self.param_ranges[start*10:start*10 + 10],"GP")
                r = opt.run(self.objective,n_iter=self.n_iter)
                self.params[start*10:start*10 + 10] = r.x

    def evaluate(self):
        wins = 0.0
        for i in range(self.n_games):
            self.engine.restart(self.max_moves,self.ai_config,self.opponent_config)
            winner = self.engine.run()
            if winner == 1:
                wins += 1.0
            elif winner == 0:
                wins += 0.5
            print winner
        return wins / (self.n_games)
Example #31
0
def test_contructor():
    #simple test to make sure that the constructor runs
    engine = Engine()
    player = Player(True, engine)
Example #32
0
 def main(self):
     Engine(no_player=self.params.no_player).play()
Example #33
0
    # Run game options
    elif action in ['run', 'r']:
        # Additional args
        quiet = False

        if par_args.debug is not None:
            if par_args.debug >= 0:
                game.config.Debug.level = par_args.debug
            else:
                print('Valid debug input not found, using default value')

        if par_args.q_bool:
            quiet = True

        engine = Engine(quiet)
        engine.loop()

    # Boot up the scrimmage server client
    elif action in ['scrimmage', 's']:
        cl = Client()

    elif action in ['visualizer', 'v']:
        # Check operating system and run corresponding visualizer
        if plat == "win32":
            print("You're running Windows")
            subprocess.call(["./visualizer.exe"])
        elif plat == "linux":
            print("You're a linux man I see.")
            subprocess.call(["./visualizer.x86_64"])
        elif plat == "darwin":
Example #34
0
    def __init__(self, master):
        self.tiles = []
        self.textids = []
        self.master = master
        self.frame = Frame(master)
        self.canvas = Canvas(self.frame, width=510, height=510)

        Grid.rowconfigure(master, 0, weight=1)
        Grid.columnconfigure(master, 0, weight=1)
        self.frame.grid(row=0, column=0)

        # self.player1_config = {
        #         Settings.AI.value : True, #should this be Ai or person
        #         Settings.START_TYPE.value : StartType.RANDOM.value, #what kind of start state
        #         Settings.START_PARAMS.value : [], #any parameters for the stater
        #         Settings.SEARCH_TYPE.value : SearchType.RANDOM.value, #what kind of search is happening
        #         Settings.SEARCH_PARAMS.value : [], #any parameters for the search
        #         Settings.AI_TYPE.value : AIType.NONE.value, # what is the AI
        #         Settings.AI_PARAMS.value : [] #any params for the ai
        #     }
        self.player1_config = {
            'ai parameters': [
                -1, 1, 0, 0, 0, 0, -1, 1, -1, 0, 1, -1, -1, 1, 0, -1, 0, 0, 1,
                1, 0
            ],
            'eval_type':
            'modified_reachable',
            'search_parmeters': [],
            'FILENAME':
            'train/good_modified_reachable.txt',
            'params_for_start_state': [],
            'type_of_start_state':
            'champion',
            'is an ai':
            True,
            'type_of_search':
            'no searcher'
        }

        self.player2_config = {
            Settings.AI.value: True,  #should this be Ai or person
            Settings.START_TYPE.value:
            StartType.RANDOM.value,  #what kind of start state
            Settings.START_PARAMS.value: [],  #any parameters for the stater
            Settings.SEARCH_TYPE.value:
            SearchType.RANDOM.value,  #what kind of search is happening
            Settings.SEARCH_PARAMS.value: [],  #any parameters for the search
            Settings.AI_TYPE.value: AIType.NONE.value,  # what is the AI
            Settings.AI_PARAMS.value: []  #any params for the ai
        }

        self.tile_colors = [[
            "#DBE0FF", "#C7CCF7", "#B3B9EF", "#9FA6E8", "#8C92E0", "#787FD9",
            "#646CD1", "#5059CA", "#3D45C2", "#2932BB", "#151FB3", "#020CAC"
        ],
                            [
                                "#FFDBE0", "#F7C7CD", "#EFB3BB", "#E89FA8",
                                "#E08C96", "#D97884", "#D16471", "#CA505F",
                                "#C23D4D", "#BB293A", "#B31528", "#AC0216"
                            ]]

        self.hidden_color = ["#787FD9", "#D97884"]

        self.e = Engine(1000, self.player1_config, self.player2_config, False)
        self.e.setup_board()
        if not self.player1_config[Settings.AI.value]:
            board = self.e.get_board(1, True)
        else:
            board = self.e.get_board(None, True)
        self.win = False  #winner trigger
        self.player1_turn = True  #player 1 turn trigger
        self.winning_player = 0
        self.button_counter = 0
        self.clicked_buttons = []
        # board setup
        #print(board)
        for i in range(10):
            for j in range(10):
                tag = i * 10 + j
                if board[i][j] == 111:
                    text_item = ""
                    tile_color = "white"
                    tile_outline = "white"
                elif board[i][j] == 0:
                    text_item = ""
                    tile_outline = "black"
                    tile_color = "grey"
                elif board[i][j] % 1000 == piece_diplay_map[
                        pieces.HIDDEN.value]:
                    text_item = ""
                    tile_outline = "black"
                    tile_color = self.hidden_color[board[i][j] / 1000 - 2]
                else:
                    text_item = str(board[i][j] % 100)
                    tile_outline = "black"
                    #print(board[i][j])
                    #print(board[i][j]/100 - 2)
                    #print(board[i][j]%100 - 1)
                    tile_color = self.tile_colors[board[i][j] / 100 -
                                                  2][board[i][j] % 100 - 1]
                tile = self.canvas.create_rectangle(j * 50 + 10,
                                                    i * 50 + 10,
                                                    j * 50 + 50,
                                                    i * 50 + 50,
                                                    outline=tile_outline,
                                                    fill=tile_color,
                                                    activefill="cyan",
                                                    tags=tag)
                textid = self.canvas.create_text(j * 50 + 30,
                                                 i * 50 + 30,
                                                 text=text_item,
                                                 tags=str(tag) + "text")

                rect_handler = self.ind_map_click(9 - i, j)

                self.tiles.append(tile)
                self.textids.append(textid)
                self.canvas.tag_bind(tile, "<Button-1>", rect_handler)
        self.canvas.grid(row=0, column=0)
Example #35
0
class GameWindow(QMainWindow):
    def __init__(self, menu, players):
        super().__init__()

        self.menu = menu

        self.setWindowTitle('Code with Fire')
        self.setGeometry(200, 50, 800, 650)

        self.player_names = players
        self.alive_players = len(players)

        self.game_engine = Engine()
        self.game_screen = Screen(self.game_engine)
        self.score_manager = ScoreManager(self.game_screen)

        self.setCentralWidget(self.game_screen)
        self.create_menu_bar()

        self.start_game(players)

    def start_game(self, players):
        if len(players) == 1:
            start_one_player_game(self, self.game_engine, self.game_screen,
                                  self.score_manager)
        elif len(players) == 2:
            start_two_player_game(self, self.game_engine, self.game_screen,
                                  self.score_manager)

        self.game_engine.start()

    def create_menu_bar(self):
        pause_button = QAction(QIcon(None), '&Pausar Juego', self)
        pause_button.setShortcut('Ctrl+P')
        pause_button.triggered.connect(self.game_engine.toggle_pause)

        quit_button = QAction(QIcon(None), '&Cerrar Juego', self)
        quit_button.setShortcut('Ctrl+E')
        quit_button.triggered.connect(self.quit_game)

        actions = self.menuBar().addMenu('&Menú')
        actions.addAction(pause_button)
        actions.addAction(quit_button)

    # I pass the key events to the game screen widget.
    def keyPressEvent(self, event):
        self.game_screen.keyPressEvent(event)

    def keyReleaseEvent(self, event):
        self.game_screen.keyReleaseEvent(event)

    def player_death(self, player_death_event):
        player_score = (self.player_names[player_death_event.player],
                        player_death_event.score)
        HighScores.add_and_save_highscore(list(HighScores.get_highscores()),
                                          player_score)

        self.alive_players -= 1

        if self.alive_players <= 0:
            self.end_game()

    def quit_game(self):
        player_score = (self.player_names[0], self.score_manager.score)
        HighScores.add_and_save_highscore(list(HighScores.get_highscores()),
                                          player_score)

        self.end_game()

    def end_game(self):
        self.game_engine.stop = True
        self.hide()

        QWidget().setLayout(
            self.menu.layout()
        )  # Simple hack to empty the current layout - https://stackoverflow.com/a/10439207
        self.menu.initialize()
        self.menu.show()
        self.menu.open_highscores()
Example #36
0
def main():
    
    #####Initializations
    pygame.init()
    pygame.font.init()
    
    pygame.mixer.init()
    font = pygame.font.Font(None,25)
    
    ###Fonts
    cmcsams = pygame.font.SysFont('comicsansms', 50, True, True)
    superFont = pygame.font.SysFont('comicsansms',100,True,True)
   
    
    FPS = 30
    FPS_CLOCK = pygame.time.Clock()
    
    SCREEN = pygame.display.set_mode(game.constants.WINDOW_SIZE)
    SCREEN.set_colorkey(game.constants.WHITE)
    
    ##UI setup
    playerAmmo = ammo()
    hpBar = healthBar()
    
    mobList =[]
    
    engine = Engine(mobList)
    pygame.mouse.set_visible(False)
    timer = 0
    seconds = 0
    minutes=0
    frame_count=0
    
     ########Game Loop##################
    while True:
        
        
        for event in pygame.event.get():
            if event.type==QUIT:
                pygame.quit()
                sys.exit()
            #player shoots
            if event.type==pygame.MOUSEBUTTONUP and event.button==LEFTBUTTON:
            
                #Play the shot sound
                shootSound=pygame.mixer.Sound("../media/shoot.wav")
                shootSound.play()
                mob = engine.shoot(pygame.mouse.get_pos())
                #go through and check collisions
                if mob is None:
                   
                    playerAmmo.shoot()
                    
                else:
                    if mob.name=='reload':
                        
                        playerAmmo.reload()
                        
                    else:
                        if playerAmmo.bullets>0:
                            
                            playerAmmo.shoot()
                            mob.isDead=True
                            mob.die()
                            
            if pygame.mouse.get_focused():
                pos = pygame.mouse.get_pos()
                
            if event.type==pygame.KEYUP:
                if event.key==pygame.K_DOWN:
                    hpBar.update()
                ###reload bird got triggered
                if event.key==pygame.K_r:
                    
                    
                    mobList.append(reloadBird())
                if event.key==pygame.K_a:
                    mobList.append(bossBird(0,0,2,0))  
        engine.turn(hpBar)
        
        
        draw(SCREEN)
        
        #Draw the Mobs
        for mob in mobList:
           
            mob.draw(SCREEN)
        
        playerAmmo.draw(SCREEN)    
        hpBar.draw(SCREEN)
         
        
        frame_count+=1
        total_seconds=frame_count//FPS
        minutes=total_seconds//FPS
        seconds=total_seconds%FPS
        output_string=" {0:02}:{1:02}".format(minutes, seconds)
        
        text = font.render(output_string,True,game.constants.SALMON)
            
        SCREEN.blit(text,(game.constants.WIDTH-60,game.constants.HEIGHT-25))
        text = cmcsams.render(str(engine.score),True,game.constants.CORAL)
        SCREEN.blit(text,(game.constants.WIDTH/2,game.constants.HEIGHT-80))
        if hpBar.width<1:
            drawEnd(SCREEN,engine.score,output_string,superFont)
            pygame.quit()
            sys.exit() 
        pygame.display.flip()
        FPS_CLOCK.tick(FPS)