Example #1
0
def display(genome, config):
    fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10,5))

    x = randint(-7, 7)
    y = randint(-7, 7)

    game = Game(Ponyo(genome, config), Shark(), (x, y))

    im1 = ax1.imshow(game.board(100), cmap=cmap, norm=norm, interpolation='none')
    im2 = ax2.imshow(game.ponyo_vision(), cmap=cmap, norm=norm, interpolation='none')
    # Helper function that updates the board and returns a new image of
    # the updated board animate is the function that FuncAnimation calls
    def update(frame):
        game.move_ponyo()
        game.move_shark()

        # print(game.shark_position)

        if game.catched():
            game.finished = True
        im1.set_data(game.board(50))
        im2.set_data(game.ponyo_vision())

        ax1.title.set_text(f'frame: {game.frame} energy: {game.ponyo.energy}')
        return ax1, ax2


    ani = animation.FuncAnimation(fig, update, frames=game.generator, blit=False, repeat = False)
    plt.show()
Example #2
0
 def tree_sim(self, state, player_names):
     players = []
     for name in player_names:
         players.append(CNNPlayer(name, tree=self.tree, model=self.model))
     game = Game(players)
     game.set_state(state)
     for player in game.play():
         yield game
Example #3
0
    def opened(self):
        # req = '{"event":"subscribe", "channel":"eth_usdt.deep"}'
        # self.send(req)
        print("连接成功")
        # 第一步随机下
        self.send('1')

        self.agent = MinMaxAgent(env=Game())
Example #4
0
 def random_sim(self, state, player_names):
     players = []
     for name in player_names:
         players.append(RandomPlayer(name, tree=self.tree))
     game = Game(players)
     game.set_state(state)
     game.next_player()
     for player in game.play():
         pass
     return game.winner().name
Example #5
0
 def test_move_one_step(self):
     """ This map can be done in one step.
     #####  01110
     ##@##  01@10
     #####  01110
     """
     mine_map = Map(5, 5, mine_pos_list=[(2, 2)])
     game = Game(mine_map)
     state = game._sweep((0, 0))
     self.assertEqual(state, 2)
Example #6
0
    def createGame(cls, name, description, private, lat, lon):
        game = Game()
        game.name = name
        game.description = description
        game.private = private
        game.center = ndb.GeoPt(lat, lon)

        gameController = BasicGameController()
        gameController.put()
        game.gameControllerId = gameController.key.id()

        game.put()
        return game
Example #7
0
def play():
    players = (Player(), Player())
    game = Game(15, 15)

    while True:
        for player in players:
            move = player.random_search(game)
            game.make_move(move)
            game.display()

            if game.terminal_test():
                print("Game over")
                return

            sleep(1)
Example #8
0
 def test_move_a(self):
     mine_map = Map(3, 4, mine_pos_list=[(0, 0)])
     test_data_cases = [{
         'click_trace': [(0, 1), (1, 0)],
         'state': 1,
         'cur_step': 2
     }, {
         'click_trace': [(0, 1), (1, 0), (1, 1), (1, 2)],
         'state': 2,
         'cur_step': 4
     }]
     for data in test_data_cases:
         game = Game(mine_map)
         self.batch_click(game, data['click_trace'])
         self.assertEqual(game.state, data['state'])
         self.assertEqual(game.cur_step, data['cur_step'])
Example #9
0
def eval_genomes(genomes, config):

    games = []

    sharks = []

    for i in range(10):
        x = randint(-7, 7)
        y = randint(-7, 7)

        if (x, y) != (0, 0):
            sharks.append((x, y))

    for genome_id, genome in genomes:
        genome.fitness = 0

        for shark_position in sharks:
            games.append(Game(Ponyo(genome, config), Shark(), shark_position))

    frame = 0
    while len(games) > 0:

        frame += 1

        if frame == 500:
            print("Aborted")

            for x, game in enumerate(games):
                game.ponyo.genome.fitness += 0.1

            break

        for x, game in enumerate(games):
            game.move_ponyo()
            game.move_shark()

        for x, game in enumerate(games):
            if game.catched():
                game.ponyo.genome.fitness -= 1
                games.pop(x)

            if game.escaped():
                game.ponyo.genome.fitness += 1
                games.pop(x)
Example #10
0
    def post(self):
        try:
            card_set_indices = map(int, self.request.arguments['card_sets'])
        except ValueError as exc:
            raise APIError(Codes.NOT_AN_INTEGER, exc)
        if min(card_set_indices) < 0 or \
           max(card_set_indices) >= len(self.application.card_sets):
            raise APIError(Codes.ILLEGAL_RANGE, card_set_indices)
        card_sets = [self.application.card_sets[i] for i in card_set_indices]

        password = self.get_argument('password', '')  # not yet implemented
        if password:
            password = hash_obj(password)
        name = self.get_argument('name', '')
        if not name:
            name = 'Jogo %d' % (len(self.application.games) + 1)

        max_score = self.get_argument('max_score')
        if not max_score:
            max_score = INFINITY
        try:
            max_score = int(max_score)
            max_players = int(self.get_argument('max_players'))
            max_clue_length = int(self.get_argument('max_clue_length'))
        except ValueError as exc:
            raise APIError(Codes.NOT_AN_INTEGER, exc)

        if (not Limits.MIN_NAME <= len(name) <= Limits.MAX_NAME) or \
           (not Limits.MIN_PLAYERS <= max_players <= Limits.MAX_PLAYERS) or \
           (not Limits.MIN_SCORE <= max_score <= Limits.MAX_SCORE) or \
           (not Limits.MIN_CLUE_LENGTH <= max_clue_length <= Limits.MAX_CLUE_LENGTH):
            raise APIError(Codes.ILLEGAL_RANGE)

        auto = self.get_argument('auto')
        if not auto:
            auto = 0

        game = Game(self.user, card_sets, password, name,
                    max_players, max_score, max_clue_length,
                    int(self.get_argument('auto')), int(self.get_argument('time_clue')), int(self.get_argument('time_choose')), int(self.get_argument('time_vote')))
        self.application.games.append(game)
        self.write(str(len(self.application.games) - 1))
Example #11
0
    def __init__(self, rect: Rect, color: Optional[Color], sock,
                 connection_list, receive_list, parent_conn, child_conn,
                 send_process, nicks):
        mod_loader.import_mods()

        super().__init__(rect, color)

        fps_font = Font('assets/fonts/arial.ttf', 20)

        sub_elem = UIElement(Rect(50, 50, 50, 50), None)
        sub_elem.append_child(FPSCounter(Rect(50, 50, 0, 0), fps_font))
        self.append_child(sub_elem)

        self.sock = sock
        self.connection_list = connection_list
        self.receive_list = receive_list
        self.child_conn = child_conn
        self.parent_conn = parent_conn
        self.send_process = send_process

        self.game = Game(Game.Side.SERVER,
                         mod_loader,
                         self.parent_conn,
                         nicks,
                         -1,
                         connection_list=self.connection_list)

        self.minimap_elem = UIImage(
            Rect(0, config['screen']['size'][1] - 388, 0, 0),
            'assets/sprite/minimap.png')

        self.minimap = Minimap(self.game)
        self.minimap_elem.append_child(self.minimap)

        self.append_child(self.minimap_elem)
        self.game.create_unit('warrior', (0, 0))
        self.game.create_unit('fortress', (500, 0))
        self.game.create_unit('fortress', (-500, 0))
        self.game.create_unit('archer', (-25, -25))
        self.game.create_unit('archer', (25, -25))
        self.game.create_unit('archer', (-25, 25))
        self.game.create_unit('archer', (25, 25))
Example #12
0
    def __init__(self, rect: Rect, color: Optional[Color], sock, receive_list,
                 socket_process, parent_conn, child_conn, send_process, nicks,
                 team_id):
        super().__init__(rect, color)

        self.sock = sock
        self.receive_list = receive_list
        self.socket_process = socket_process
        self.parent_conn = parent_conn
        self.child_conn = child_conn
        self.send_process = send_process

        mod_loader.import_mods()

        config.reload()

        fps_font = Font('assets/fonts/arial.ttf', 20)

        sub_elem = UIElement(Rect(50, 50, 50, 50), None)
        sub_elem.append_child(FPSCounter(Rect(50, 50, 0, 0), fps_font))
        self.append_child(sub_elem)

        self.game = Game(Game.Side.CLIENT, mod_loader, self.parent_conn, nicks,
                         team_id)

        self.minimap = Minimap(self.game)
        self.minimap_elem = UIImage(
            Rect(0, config['screen']['size'][1] - 388, 0, 0),
            'assets/sprite/minimap.png')
        self.minimap_elem.append_child(self.minimap)

        self.minimap_elem.append_child(
            ResourceMenu(self.game.current_player, Rect(45, 108, 0, 0),
                         Font('assets/fonts/arial.ttf', 25)))

        menu_parent = UIElement(Rect(0, 0, 0, 0), None)
        self.append_child(menu_parent)
        menu_parent.append_child(self.minimap_elem)
        menu_parent.append_child(BuildMenu(self.relative_bounds, self.game))
        menu_parent.append_child(ProduceMenu(self.relative_bounds, self.game))
Example #13
0
# -*- coding:utf-8 -*-
import random
import time
from core import Game, Grid
from agents import RandomAgent, MinMaxAgent

if __name__ == '__main__':
    env = Game()
    # agent = RandomAgent(action_num=4, env=env)
    agent = MinMaxAgent(env=env, maxSearchTime=100)

    while not env.isOver:
        act, move = agent.step()
        print("当前下法:", move)
        env.step(act)
        print("当前棋盘:\n{}".format(env.state))
        print("当前最大值:{}\n".format(env.maxValue))
    print("最终得分:", env.score)
Example #14
0
import json
import sys
import os

import pygame

from core import Game
import settings

if __name__ == "__main__":
    output = sys.stdin.read()
    data = json.loads(output)
    screen_size = settings.get_screen_size(data['grid_size'])
    os.environ['SDL_VIDEO_CENTERED'] = '1'
    pygame.init()
    pygame.display.set_mode(screen_size)
    game = Game(data)
    game.main_loop()
    pygame.quit()
    sys.exit()
Example #15
0
 def __init__(self, size=8, max_episodes=100, gen_proba=0.5, collide='sym'):
     self.viewer = None
     self.done = None
     self.game = Game(max_episodes, gen_proba, size, collide)
     self.action_space = spaces.Discrete(4)
     self.observation_space = spaces.Box(0, 1, shape=(4, ), dtype=np.uint8)
Example #16
0
    def post(self):
        global totalGames

        tp = int(self.get_argument('type'))
        username = self.get_argument('nickname')
        roomname = self.get_argument('room')
        password = self.get_argument('password')

        if tp == Commands.createRoom:  #To create a new room

            notFound = -1
            for i, gm in self.application.games.items():
                if gm.name == roomname:
                    notFound = i
                    break

            if notFound != -1:
                #Room already exists
                self.write(json.dumps({'game': 'exists'}))
            else:
                game = Game(self.user, [self.application.card_sets[0]],
                            password, roomname, 12, 40, 100)

                self.user.set_name(username)
                self.user.gid = totalGames

                game.add_player(self.user, 'RED')
                self.application.games[totalGames] = game
                self.write(json.dumps({'game': str(totalGames)}))
                totalGames += 1

                #ADDING EXTRA PLAYERS TO HELP TEST
                #x1 = self.application.users.add_user('2dfsgsdfg', '2dsgsdfg')
                #x2 = self.application.users.add_user('3dfgsfdfg', '3dfgdfgd')
                #x3 = self.application.users.add_user('4dsfgsdfg', '4fsfoias')
                #game.add_player(x1, display.BunnyPalette.allColors[1])
                #game.add_player(x2, display.BunnyPalette.allColors[2])
                #game.add_player(x3, display.BunnyPalette.allColors[3])

        elif tp == Commands.enterRoom:  #He is trying to enter room

            print(roomname, password)

            notFound = -1
            for i, gm in self.application.games.items():
                if gm.name == roomname and gm.password == password:
                    print('game exists, add him in', i, gm.name, gm.password)
                    notFound = i
                    break

            if notFound == -1:
                self.write(json.dumps({'game': 'na'}))
            else:
                #add into game given by totalGames = i
                blob = {'game': str(notFound)}

                self.user.set_name(username)
                self.user.gid = notFound

                i = 0
                for col in display.BunnyPalette.allColors:
                    if col not in list(
                            self.application.games[notFound].colours.values()):
                        i = col

                self.application.games[notFound].add_player(self.user, i)

                #players = {}

                #for i in self.application.games[notFound].players:
                #    players.update({'name': i.name , 'color': i})

                #blob.update({'players':players})

                self.write(json.dumps(blob))
        else:
            print(self.request.arguments)
Example #17
0
def main():
    # initialize the pygame module
    pygame.init()
    pygame.display.set_caption("Learning car")

    # create a surface on screen that has the size of 720 x 480
    screen = pygame.display.set_mode((1000, 500))

    # initialize game
    game = Game()
    force = pygame.math.Vector2()

    # initialize rendering
    input_state = DRAWING
    checkpoint_start = None

    # variables
    # update_buttons = True
    # update_track = False
    # update_background = False

    segoe_print = pygame.font.SysFont('segoe print', 25)
    text_buttons = [
        segoe_print.render(t, True, (127, 127, 127)) for t in
        ['Save current track', 'Load track 0', 'Clear active track', 'Start']
    ]
    text_cycler = [
        segoe_print.render(t, True, (127, 127, 127))
        for t in ['Drawing', 'Checkpoints', 'Start', 'Idle']
    ]

    buttons = []
    right_bar_x = screen.get_rect().width * 0.75
    right_bar_width = screen.get_rect().width * 0.25
    button_height = 50
    for index, line in enumerate(text_buttons):
        buttons.append(
            Button(
                pygame.Rect(right_bar_x, (index + 1) * button_height,
                            right_bar_width, button_height), line))
    cycler_buttons = [
        Button(pygame.Rect(right_bar_x, 0, right_bar_width, button_height),
               line) for line in text_cycler
    ]
    input_state_cycler = Cycler(cycler_buttons)

    # main loop
    running = True
    while running:
        # event handling, gets all event from the event queue
        for event in pygame.event.get():
            # red cross handling
            if event.type == pygame.QUIT:
                # change the value to False, to exit the main loop
                running = False

            # mouse presses handling
            if event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == pygame.BUTTON_LEFT:
                    # if it is LMB pressed
                    if event.pos[0] < right_bar_x:
                        if input_state == DRAWING:
                            update_track = True
                            game.track_m.active_track.add_vertex(
                                pygame.math.Vector2(event.pos))
                        elif input_state == CHECKPOINTS:
                            if checkpoint_start:
                                game.track_m.active_track.add_checkpoint(
                                    checkpoint_start,
                                    pygame.math.Vector2(event.pos))
                                checkpoint_start = None
                            else:
                                checkpoint_start = pygame.math.Vector2(
                                    event.pos)
                        elif input_state == START:
                            game.track_m.active_track.set_start(
                                pygame.math.Vector2(event.pos))
                    else:
                        # update_buttons = True
                        if input_state_cycler.is_inside(event.pos):
                            input_state = (input_state + 1) % 4
                        if buttons[0].is_inside(event.pos):
                            print('saved')
                            game.track_m.save_active_track()
                        if buttons[1].is_inside(event.pos):
                            print('loaded')
                            # update_background = True
                            # update_track = True
                            game.track_m.load_to_active_track('track_0.pickle')
                        if buttons[2].is_inside(event.pos):
                            # update_background = True
                            game.track_m.clear_active_track()
                        if buttons[3].is_inside(event.pos):
                            game.start()

            # controls handling
            if event.type == pygame.KEYDOWN:
                # print('down a key')
                if event.key == pygame.K_RIGHT:
                    force.x += 1
                if event.key == pygame.K_LEFT:
                    force.x -= 1
                if event.key == pygame.K_DOWN:
                    force.y += 1
                if event.key == pygame.K_UP:
                    force.y -= 1

            if event.type == pygame.KEYUP:
                # print('up a key')
                if event.key == pygame.K_RIGHT:
                    force.x -= 1
                if event.key == pygame.K_LEFT:
                    force.x += 1
                if event.key == pygame.K_DOWN:
                    force.y -= 1
                if event.key == pygame.K_UP:
                    force.y += 1

        if force.length() > 0:
            force_ = force.normalize()
            force_.scale_to_length(0.0001)
            game.agent.add_force(force_, 0)

        game.update()
        # print(int(game.agent.pos.x), int(game.agent.pos.y))

        # drawing
        pygame.draw.rect(screen, (0, 0, 0), screen.get_rect())
        draw_track(screen, game.track_m.active_track)
        draw_button(screen, input_state_cycler.get_active_button())
        for button in buttons:
            draw_button(screen, button)
        pygame.draw.circle(screen, (255, 255, 0),
                           (int(game.agent.pos.x), int(game.agent.pos.y)), 12)
        pygame.display.flip()
Example #18
0
from core import Game
from players.trivial_player import TrivialPlayer
from players.random_player import RandomPlayer


players = [TrivialPlayer(), TrivialPlayer(), RandomPlayer()]
result = Game(players).play(with_prints=True)
Example #19
0
def main():

    # For avoiding sound delay - thanks to BigglesW at StackOverflow
    pygame.mixer.pre_init(44100, -16, 1, 512)

    # Initialization ======================
    pygame.init()

    # frames per second setting
    FPS = 60
    fpsClock = pygame.time.Clock()

    # set up the window
    screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
    pygame.display.set_caption('CometZ')

    # Setting window icon
    icon = pygame.image.load("iconShip.png")
    pygame.display.set_icon(icon)

    # gameState
    # States available:
    # menu, pause, game, gameOver

    # Create game instance
    game = Game()

    # =====================================

    # Main game loop
    while True:

        # ===========================================================
        # EVENTS     ================================================
        # ===========================================================

        # check all events in event list
        for event in pygame.event.get():
            game.handle(event)

        # for continuously pressed keys
        keys = pygame.key.get_pressed()
        game.keys(keys)

        # ===========================================================
        # GAME LOGIC ================================================
        # ===========================================================

        # update game
        game.update()

        # ===========================================================
        # DRAWING    ================================================
        # ===========================================================

        # draw to the screen
        game.draw(screen)
        pygame.display.update()

        # ===========================================================
        # OTHER      ================================================
        # ===========================================================

        fpsClock.tick(FPS)
Example #20
0
from core import Game

if __name__ == '__main__':
    Game().play()
Example #21
0
 def test_one_step_success(self):
     click_list = [(0, 0), (0, 4), (4, 0), (4, 4)]
     for click_pos in click_list:
         game = Game(self.mine_map)
         state = game._sweep(click_pos)
         self.assertEqual(state, 2)
Example #22
0
def run(size, player):
    game = Game(size)
    while not game.is_over():
        move = player.make_move(game)
        game.move(move)
    return game.first_wins()
Example #23
0
from core import Game

start = Game(lang="en_English", category="colors")
start.play_rounds(10)