Example #1
0
    def __init__(self,
                 model_config,
                 game_config,
                 player1_model=None,
                 player1_mode='model_training',
                 player2_model=None,
                 player2_mode='random',
                 model_dir='.'):

        self.model_config = model_config
        self.game_config = game_config
        self.device = torch.device(
            'cuda:0') if torch.cuda.is_available() else torch.device('cpu')

        self.player1_mode = player1_mode
        self.player2_mode = player2_mode

        self.player1_model = player1_model
        self.player2_model = player2_model

        if player1_mode.startswith('model'):
            if player1_model is None:
                self.player1_model = GameModel(game_config)
            self.player1_model.to(self.device)

        if player2_mode.startswith('model'):
            if player2_model is None:
                self.player2_model = GameModel(game_config)
            self.player2_model.to(self.device)

        self.model_dir = model_dir
        self.vis = Visdom(env=self.model_config.model_name)
Example #2
0
class ColonistGame(object):
    def __init__(self):
        pass

    def initialize_game(self):
        #initialize model instances
        print "initialize game"
        self.model_instance = GameModel()
        for colonist in self.model_instance.colonistlist:
            print colonist.get_name()

        self.root = Tk()
        self.app = GameScreen(self.root, game_instance)
        self.root.mainloop()
        self.app.update_screen()

    def next_turn(self):
        """
        Model update
        """
        self.model_instance.resolve_turn_phase()

        """
        Screen update
        """
        self.app.update_screen()

        print "Next turn"
Example #3
0
class GameInstance:
    def __init__(self):
        self.game = GameModel()
        self.game.king_captured = self.king_captured
        self.game.init()
        self.game.mode = 'play'
        self.game.add_message = print
        self.net_engine = NetEngine(self.game)
        self.init_net_engine_socket()

    def king_captured(self, who):
        if self.game.mode != 'replay':
            self.net_engine.start_replay()

    def init_net_engine_socket(self):
        while True:
            self.port = random.randint(1024, 65535)
            try:
                self.net_engine.socket = socket.socket(socket.AF_INET,
                                                       socket.SOCK_DGRAM)
                self.net_engine.socket.bind(('127.0.0.1', self.port))
            except socket.error:
                print('retrying establishing server')
                continue
            break
Example #4
0
 def __init__(self):
     self.game = GameModel()
     self.game.king_captured = self.king_captured
     self.game.init()
     self.game.mode = 'play'
     self.game.add_message = print
     self.net_engine = NetEngine(self.game)
     self.init_net_engine_socket()
Example #5
0
    def __init__(self, **kwargs):
        super(Game, self).__init__(**kwargs)
        self.game_model = GameModel()
        self.game_model.king_captured = self.king_captured
        self.game_model.on_message.append(self.update_label)
        self.net_engine = NetEngine(self.game_model)

        self.score = [0, 0]

        self.board_view = BoardView(self.game_model)
        self.add_widget(self.board_view)
        self.game_model.on_init.append(self.board_view.reset)

        self.info_pane = BoxLayout(orientation='vertical', size_hint_min_y=500)
        self.add_widget(self.info_pane)

        row_args = {'size_hint': (1, 0), 'size_hint_min_y': 70}

        if not env.is_mobile:
            self.info_pane.add_widget(WrappedLabel(halign='center', text=self.game_title, **row_args))

        self.button_pane = BoxLayout(orientation='vertical', size_hint=(1, .4))
        self.info_pane.add_widget(self.button_pane)

        self.button_pane.add_widget(WrappedButton(
            halign='center',
            text='Tutorial: How to play',
            on_press=self.start_tutorial))
        self.button_pane.add_widget(WrappedButton(
            halign='center',
            text='Start Game' if env.is_mobile else 'Start Game: Play with friends',
            on_press=self.start_game))

        self.score_label = WrappedLabel(
            halign='center',
            **row_args)
        self.info_pane.add_widget(self.score_label)

        self.label = WrappedLabel(halign='center', valign='bottom')
        self.info_pane.add_widget(self.label)

        self.text_input = TextInput(
            multiline=False,
            text_validate_unfocus=env.is_mobile,
            **row_args)
        self.text_input.bind(on_text_validate=self.handle_text_input)
        if not env.is_mobile:
            def steal_focus(*_args):
                if not self.text_input.focus:
                    self.text_input.focus = True
            self.text_input.bind(focus=steal_focus)
        self.info_pane.add_widget(self.text_input)

        self.game_model.add_message('')
        self.game_model.add_message(self.game_title if env.is_mobile else 'Welcome to Chess 2!')

        self.bind(size=self.resized)
        Clock.schedule_interval(self.on_clock, 1/30)
Example #6
0
def main():
    model = GameModel()
    view = GameView(800, 600)
    controller = GameController(model, view)
    # ---
    while (True):
        controller.update()
 def __init__(self):
     self.__model = GameModel()
     self.__sprites = pg.sprite.Group()
     self.__attacks = pg.sprite.Group()
     self.__view = GameView(self.__model.player,
                            self.__model.level,
                            self.__sprites,
                            self.__attacks)
     self.__player = self.__model.player
     self.__level = self.__model.level
     self.__clock = pg.time.Clock()
     # inicializa os modulos do pygame e retorna uma tupla com resultados
     self.__modules = pg.init()
     self.__running = True
     self.__menu = True
     self.__game_over = False
     self.__start_playing = False
     self.__win = False
Example #8
0
    def initialize_game(self):
        #initialize model instances
        print "initialize game"
        self.model_instance = GameModel()
        for colonist in self.model_instance.colonistlist:
            print colonist.get_name()

        self.root = Tk()
        self.app = GameScreen(self.root, game_instance)
        self.root.mainloop()
        self.app.update_screen()
def main():

    pygame.init()

    event_manager = EventManager()
    game_model = GameModel(event_manager)
    keyboard_controller = KeyboardController(event_manager)
    time_controller = TimeController(event_manager)
    game_view = GameView(
        event_manager, game_model,
        time_controller)  # sollte von GameModel aufgemacht werden

    time_controller.run()
Example #10
0
def get_newgame():
    '''returns the game scene'''
    scene = Scene()

    # model
    model = GameModel()

    # controller
    controller = GameController(model)

    # view
    view = GameView(model)

    # set controller in model
    model.set_controller(controller)

    # add controller
    scene.add(controller, z=1, name="controller")

    # add view
    #scene.add(BackgroundLayer(), z=0, name="background")
    scene.add(view, z=2, name="view")

    return scene
Example #11
0
def get_newgame():
    '''returns the game scene'''
    scene = Scene()

    # model
    model = GameModel()

    # controller
    controller = GameController(model)

    # view
    view = GameView(model)

    # set controller in model
    model.set_controller(controller)

    # add controller
    scene.add(controller, z=1, name="controller")

    # add view
    #scene.add(BackgroundLayer(), z=0, name="background")
    scene.add(view, z=2, name="view")

    return scene
Example #12
0
def main():
    pygame.init()

    pygame.display.set_caption("The 15 Puzzle")
    win = pygame.display.set_mode((WIN_WIDTH, WIN_HEIGHT))
    clock = pygame.time.Clock()
    event_manager = EventManager()
    game_board = GameModel()
    game_view = GameView(win)
    spinner = CPUSpinnerController(event_manager, clock)
    game_controller = GameController(game_board, game_view)

    event_manager.registerListener(TickEvent(), game_controller)
    event_manager.registerListener(QuitEvent(), spinner)

    spinner.run()

    pygame.quit()
Example #13
0
File: main.py Project: yonlif/Snake
from controller import BasicController, UserController
from ai_controller import AIController
from game_model import GameModel
from view import GameView

if __name__ == '__main__':
    model = GameModel(board_size=30)
    view = GameView(model.board_size)
    # controller = UserController(model, view)
    controller = AIController(model, view, delay=0)
    controller.play()
Example #14
0
class Trainer:
    def __init__(self,
                 model_config,
                 game_config,
                 player1_model=None,
                 player1_mode='model_training',
                 player2_model=None,
                 player2_mode='random',
                 model_dir='.'):

        self.model_config = model_config
        self.game_config = game_config
        self.device = torch.device(
            'cuda:0') if torch.cuda.is_available() else torch.device('cpu')

        self.player1_mode = player1_mode
        self.player2_mode = player2_mode

        self.player1_model = player1_model
        self.player2_model = player2_model

        if player1_mode.startswith('model'):
            if player1_model is None:
                self.player1_model = GameModel(game_config)
            self.player1_model.to(self.device)

        if player2_mode.startswith('model'):
            if player2_model is None:
                self.player2_model = GameModel(game_config)
            self.player2_model.to(self.device)

        self.model_dir = model_dir
        self.vis = Visdom(env=self.model_config.model_name)

    def collect_game_data(self):
        win_num = 0
        game_data = []
        start_time = time.time()

        for game_round in range(self.model_config.round_num):
            # initialize game
            deck1 = [
                c[1] for c in self.game_config.card_config.cards_list[1:] * 4
            ]
            player1 = HearthStoneGod('Player1',
                                     deck1,
                                     CardClass.MAGE.default_hero,
                                     self.game_config,
                                     game_model=self.player1_model,
                                     mode=self.player1_mode,
                                     device=self.device)

            deck2 = [
                c[1] for c in self.game_config.card_config.cards_list[1:] * 4
            ]
            player2 = HearthStoneGod('Player2',
                                     deck2,
                                     CardClass.MAGE.default_hero,
                                     self.game_config,
                                     game_model=self.player2_model,
                                     mode=self.player2_mode,
                                     device=self.device)

            game = Game(players=[player1, player2])
            game.start()

            # play game
            # mulligan
            player1.mulligan(skip=True)
            player2.mulligan(skip=True)

            try:
                while True:
                    player = game.current_player
                    player.play_turn(game)

            except GameOver:
                if player2.hero.dead:
                    win_num += 1
                    game_data.append((player1.replay, player1.hero.health))
                else:
                    game_data.append((player1.replay, -player2.hero.health))

        end_time = time.time()
        win_rate = win_num / self.model_config.round_num

        return game_data, win_rate

    def train(self):
        # set seed
        random.seed(self.model_config.seed)
        torch.manual_seed(self.model_config.seed)
        np.random.seed(self.model_config.seed)

        device = self.device

        if self.model_config.optim == 'Adam':
            optimizer = torch.optim.Adam(self.player1_model.parameters(),
                                         self.model_config.learning_rate)
        elif self.model_config.optim == 'SGD':
            optimizer = torch.optim.SGD(self.player1_model.parameters(),
                                        self.model_config.learning_rate)
        else:
            raise NotImplementedError(self.model_config.optim +
                                      " is not implemented!")

        best_win_rate = 0

        win_rates = []

        for epoch in range(self.model_config.epoch):
            game_data, win_rate = self.collect_game_data()

            # plot win rates
            win_rates.append(win_rate)
            self.vis.line(win_rates,
                          np.arange(epoch + 1),
                          win='win rates',
                          opts={'title': 'win rates'})

            # save
            if win_rate > best_win_rate or epoch % 10 == 0:
                self.save(epoch + 1, win_rate)
                best_win_rate = win_rate

            print(f'epoch {epoch} win rate:', win_rate)

            # dataloader
            dataset = HearthStoneDataset(game_data)
            dataloader = torch.utils.data.DataLoader(
                dataset, batch_size=self.model_config.batch_size, shuffle=True)

            # train
            for step, data in enumerate(dataloader):
                optimizer.zero_grad()

                hand, hero, current_minions, opponent, opponent_minions, \
                    action_mask, targets_mask, action, target, reward = data

                hand, hero, current_minions = hand.to(device), hero.to(
                    device), current_minions.to(device)
                opponent, opponent_minions = opponent.to(
                    device), opponent_minions.to(device)
                action_mask, targets_mask = action_mask.to(
                    device), targets_mask.to(device)
                action, target, reward = action.to(device), target.to(
                    device), reward.to(device)

                # actions
                action_policy, action_logits, game_state = self.player1_model.get_action(
                    hand, hero, current_minions, opponent, opponent_minions,
                    action_mask)
                action_loss = -(reward * action_policy.log_prob(action)).mean()

                # targets
                targets_policy = self.player1_model.get_target(
                    action_logits, game_state, targets_mask)
                target_loss = -(reward *
                                targets_policy.log_prob(target)).mean()

                # total loss
                loss = action_loss + target_loss

                if step % 100 == 0:
                    print(loss.item())

                loss.backward()
                torch.nn.utils.clip_grad_norm_(
                    self.player1_model.parameters(),
                    self.model_config.grad_clip,
                    norm_type=self.model_config.grad_norm_type)
                optimizer.step()

    def save(self, epoch, win_rate):
        save_data = {
            'game_config': self.game_config,
            'model_config': self.model_config,
            'state_dict': self.player1_model.state_dict(),
            'epoch': epoch,
            'win_rate': win_rate
        }

        save_dir = os.path.join(self.model_dir, self.model_config.model_name)
        if not os.path.exists(save_dir):
            os.makedirs(save_dir)

        save_path = os.path.join(save_dir, f'{epoch}_{win_rate}.pth')
        torch.save(save_data, save_path)
Example #15
0
def main():
    pygame.init()
    screen = pygame.display.set_mode((800, 600))
    pygame.display.set_caption("SlippyPants")
    game = GameModel("levels/graphic_test.json", 800, 600)
    game.run(screen)
class GameController:
    def __init__(self):
        self.__model = GameModel()
        self.__sprites = pg.sprite.Group()
        self.__attacks = pg.sprite.Group()
        self.__view = GameView(self.__model.player,
                               self.__model.level,
                               self.__sprites,
                               self.__attacks)
        self.__player = self.__model.player
        self.__level = self.__model.level
        self.__clock = pg.time.Clock()
        # inicializa os modulos do pygame e retorna uma tupla com resultados
        self.__modules = pg.init()
        self.__running = True
        self.__menu = True
        self.__game_over = False
        self.__start_playing = False
        self.__win = False

    def run(self):
        self.__modules
        self.load_level()
        self.__view.music("The_Mandalorian_OST_Main_Theme.wav", -1)  # view
        while self.__running:
            self.__clock.tick(self.__model.FPS)
            # logica de game over
            while self.__game_over:
                self.events()
                self.warning("GAME OVER")
                pg.display.flip()
                sleep(3)
                self.__game_over = False
                self.__model.data(True, False)
                self.__menu = True
            while self.__win:
                self.events()
                self.warning("YOU WIN")
                pg.display.flip()
                sleep(3)
                self.__win = False
                self.__menu = True
            while self.__menu:
                self.events()  # Vou passar para dentro de update *
                self.menu()
                pg.display.flip()
            # sincroniza o loop de eventos com o clock
            self.events()
            self.update()
            self.__view.draw()

    # funcao de saida do pygame chamada em caso de fechamento de janela
    def quit(self):
        self.__running = False
        pg.quit()

    def events(self):
        for event in pg.event.get():
            # se fecha a janela termina o programa
            if event.type == pg.QUIT:
                self.__model.data(True, True)
                self.quit()

            self.commands(event)

            # logica de comportamento dos inimigos
            if self.__start_playing == True:
                for enemy in self.__level.enemies:
                    enemy.follow_rect(self.__player)
                    self.enemy_attack(enemy)

    def update(self):
        self.physics()
        self.kill_the_dead()
        self.__view.update_scene()

    def load_level(self):
        # posicao do jogador, deve ser carregada de level
        self.__player.pos = self.__level.spawn_point

    def button(self, msg, x, y, w, h, inactive, active, action=None):
        mouse = pg.mouse.get_pos()
        click = pg.mouse.get_pressed()

        if (x+w) > mouse[0] > x and (y+h) > mouse[1] > (h):
            pg.draw.rect(self.__view.screen, active, (x, y, w, h))
            if click[0] == 1 and action != None:
                if action == "start":
                    self.__menu = False
                if action == "quit":
                    self.__model.data(True, True)
                    self.__quit()
                if action == "load":
                    self.__model.data(False, False)
                    self.__menu = False
                if action == "menu":
                    self.__menu = True
        else:
            pg.draw.rect(self.__view.screen, inactive, (x, y, w, h))

        self.__button, self.__button_rect = self.__view.message(
            BLACK, msg, None, 20, (x+(w/2)), (y+(h/2)))
        self.__view.screen.blit(self.__button, self.__button_rect)

    def menu(self):
        self.__message, self.__message_rect = self.__view.message(
            BLUE, "Baby Yoda's Rescue", None, 100, (WIDTH/2), (HEIGHT/2))
        self.__bg = pg.image.load(data + "background-1.png")
        self.__view.screen.blit(self.__bg, self.__bg.get_rect())
        self.__view.screen.blit(self.__message, self.__message_rect)

        self.button("START", (HEIGHT/4)+30, (WIDTH/2), 100, 50,
                    AZUL_BONITO, AZUL_BONITO_CLARO, "start")
        self.button("LOAD", (HEIGHT/4)+200, (WIDTH/2), 100,
                    50, AZUL_BONITO, AZUL_BONITO_CLARO, "load")
        self.button("QUIT", (HEIGHT/4)+(WIDTH/2)-30,
                    (WIDTH/2), 100, 50, RED, LIGHT_RED, "quit")

    def pause(self):
        pass

    def warning(self, warning):  # "GAME OVER" ou "YOU WIN"
        self.__message, self.__message_rect = self.__view.message(
            RED, warning, None, 100, (WIDTH/2), (HEIGHT/2))

        self.__view.screen.blit(self.__bg, self.__bg.get_rect())
        self.__view.screen.blit(self.__message, self.__message_rect)

    def physics(self):
        self.collisions()
        self.lazer_movement()
        self.attack_collision()

        self.__player.char_physics()

        for enemy in self.__level.enemies:
            enemy.char_physics()

    def lazer_movement(self):
        for lazer in self.__attacks.sprites():
            lazer.pos.x += math.cos(lazer.angle) * lazer.vel
            lazer.pos.y += math.sin(lazer.angle) * lazer.vel
            lazer.rect.center = lazer.pos
        # criar funcao pra destruir lazers
            out_of_border = (lazer.rect.right >= WIDTH or lazer.rect.left <= 0
                             or lazer.rect.bottom >= HEIGHT or lazer.rect.top <= 0)
            if out_of_border:
                lazer.kill()

    def kill_the_dead(self):
        for sprite in self.__level.enemies:

            if sprite.health <= 0:
                sprite.kill()

        if self.__player.health <= 0.0:
            self.__game_over = True
            self.__player.kill()

    def collisions(self):  # Causa a colisão

        def collisions_rect(rect):
            collision_tolerance = 10

            hits_platforms = pg.sprite.spritecollide(
                rect, self.__level.platforms, False, False)

            for platform in hits_platforms:
                if abs(rect.rect.bottom - platform.rect.top) < collision_tolerance:
                    rect.collisions["bottom"] = platform.rect.top
                else:
                    rect.collisions["bottom"] = False

                if abs(rect.rect.top - platform.rect.bottom) < collision_tolerance:
                    rect.collisions["top"] = platform.rect.bottom

                if (abs(rect.rect.left - platform.rect.right) < collision_tolerance):
                    rect.collisions["left"] = platform.rect.right
                else:
                    rect.collisions["left"] = False

                if (abs(rect.rect.right - platform.rect.left) < collision_tolerance):
                    rect.collisions["right"] = platform.rect.left
                else:
                    rect.collisions["right"] = False

            if not hits_platforms:
                rect.collisions["bottom"] = False
                rect.collisions["top"] = False
                rect.collisions["right"] = False
                rect.collisions["left"] = False

        collisions_rect(self.__player)

        for enemy in self.__level.enemies:
            collisions_rect(enemy)

        # Colisao com itens:
        hits_items = pg.sprite.spritecollide(
            self.__player, self.__level.items, True)
        if hits_items:
            self.__player.key = True

        # Colisao com a saida:
        hits_exit = pg.sprite.spritecollide(
            self.__player, self.__level.exit, False)
        if hits_exit and self.__player.key == True:
            self.__win = True

    # define a colisao de ataques
    def attack_collision(self):

        hits = pg.sprite.groupcollide(self.__attacks,
                                      self.__level.enemies, False, False)
        # destroi lazers que batem na plataforma
        pg.sprite.groupcollide(
            self.__attacks, self.__level.platforms, True, False)

        hits_player = pg.sprite.spritecollide(
            self.__player, self.__attacks, False)

        # adiciona eventuais colisoes em player
        for item in hits_player:
            hits.update({item: [self.__player]})

        # itera sobre dict
        for attack, sprite in hits.items():
            # se o ataque nao e do atacante
            if attack.shooter != sprite[0]:
                # diminui vida do sprite atingido
                sprite[0].health -= attack.damage * (random.randint(1, 10)/10)
                attack.kill()

    def enemy_attack(self, enemy):
        random_attack = random.randint(0, 15)
        trooper_imprecision = random.randint(-100, 100)
        if random_attack < 2:
            lazer = self.__model.gen_lazer(
                enemy, self.__player.pos + (trooper_imprecision, trooper_imprecision))
            self.__attacks.add(lazer)
            self.__view.update_attacks()

    def commands(self, event):

        # logica de comandos
        keys = pg.key.get_pressed()

        # Se player se movimentar ou atirar: está jogando
        if self.__player.acc.x != 0 or self.__player.vel.y == self.__player.jump_acc:
            self.start_playing = True

        # seta esquerda
        if keys[pg.K_a]:  # and not self.__player.collisions["left"]:
            self.__player.animation("left")
            self.__player.acc.x = -1 * self.__player.std_acc

        # seta direita
        if keys[pg.K_d]:  # and not self.__player.collisions["right"]:
            self.__player.animation("right")
            self.__player.acc.x = self.__player.std_acc

        if not keys[pg.K_d] and not keys[pg.K_a]:
            self.__player.acc.x = 0

        # logica de salto
        if (keys[pg.K_SPACE] or keys[pg.K_w]) and self.__player.air_timer < 10:
            self.__player.vel.y = self.__player.jump_acc

        # clique de mouse mais posicao
        if event.type == pg.MOUSEBUTTONDOWN:
            lazer = self.__model.gen_lazer(self.__player, pg.mouse.get_pos())
            self.__attacks.add(lazer)
            self.__view.update_attacks()

    @ property
    def running(self):
        return self.__running

    @ running.setter
    def running(self, new_value):
        self.__running = new_value

    @ property
    def sprites(self):
        return self.__sprites

    @ property
    def start_playing(self):
        return self.__start_playing

    @ start_playing.setter
    def start_playing(self, new_value):
        self.__start_playing = new_value
Example #17
0
from fireplace import cards
from fireplace.game import Game
from fireplace.exceptions import GameOver
from hearthstone.enums import CardClass

from agent import HearthStoneGod
from game_model import GameModel

cards.db.initialize('zhCN')

if __name__ == "__main__":
    model_data = torch.load('./models/model1.1/105_0.99.pth',
                            map_location='cpu')
    game_config = model_data['game_config']

    game_model = GameModel(game_config)

    deck1 = [c[1] for c in game_config.card_config.cards_list[1:] * 4]
    player1 = HearthStoneGod('Player1',
                             deck1,
                             CardClass.MAGE.default_hero,
                             game_config,
                             mode='manual')

    deck2 = [c[1] for c in game_config.card_config.cards_list[1:] * 4]
    player2 = HearthStoneGod('Player2',
                             deck2,
                             CardClass.MAGE.default_hero,
                             game_config,
                             game_model=game_model,
                             mode='model_play')
Example #18
0
import csv
from game_model import GameModel
from board import Board

games = []
WHITE = "white"
BLACK = "black"

with open('games.csv') as csvfile:
    gamereader = csv.reader(csvfile)
    for row in gamereader:
        game = GameModel(row)
        games.append(game)

for game in games:
    white_turn = True
    board = Board()
    moves = game.moves.split(" ")
    for move in moves:
        if white_turn:
            board.execute_move(move, WHITE, True)
        else:
            board.execute_move(move, BLACK, True)
Example #19
0
class Game(BoxLayout):
    tutorial_messages: typing.List[str]
    game_title = 'Chess 2: No turns, no sight!'

    def __init__(self, **kwargs):
        super(Game, self).__init__(**kwargs)
        self.game_model = GameModel()
        self.game_model.king_captured = self.king_captured
        self.game_model.on_message.append(self.update_label)
        self.net_engine = NetEngine(self.game_model)

        self.score = [0, 0]

        self.board_view = BoardView(self.game_model)
        self.add_widget(self.board_view)
        self.game_model.on_init.append(self.board_view.reset)

        self.info_pane = BoxLayout(orientation='vertical', size_hint_min_y=500)
        self.add_widget(self.info_pane)

        row_args = {'size_hint': (1, 0), 'size_hint_min_y': 70}

        if not env.is_mobile:
            self.info_pane.add_widget(WrappedLabel(halign='center', text=self.game_title, **row_args))

        self.button_pane = BoxLayout(orientation='vertical', size_hint=(1, .4))
        self.info_pane.add_widget(self.button_pane)

        self.button_pane.add_widget(WrappedButton(
            halign='center',
            text='Tutorial: How to play',
            on_press=self.start_tutorial))
        self.button_pane.add_widget(WrappedButton(
            halign='center',
            text='Start Game' if env.is_mobile else 'Start Game: Play with friends',
            on_press=self.start_game))

        self.score_label = WrappedLabel(
            halign='center',
            **row_args)
        self.info_pane.add_widget(self.score_label)

        self.label = WrappedLabel(halign='center', valign='bottom')
        self.info_pane.add_widget(self.label)

        self.text_input = TextInput(
            multiline=False,
            text_validate_unfocus=env.is_mobile,
            **row_args)
        self.text_input.bind(on_text_validate=self.handle_text_input)
        if not env.is_mobile:
            def steal_focus(*_args):
                if not self.text_input.focus:
                    self.text_input.focus = True
            self.text_input.bind(focus=steal_focus)
        self.info_pane.add_widget(self.text_input)

        self.game_model.add_message('')
        self.game_model.add_message(self.game_title if env.is_mobile else 'Welcome to Chess 2!')

        self.bind(size=self.resized)
        Clock.schedule_interval(self.on_clock, 1/30)

    def stop_net_engine(self):
        if not self.net_engine:
            return
        self.net_engine.should_stop = True

    def restart_net_engine(self):
        self.stop_net_engine()
        self.net_engine = NetEngine(self.game_model)

    def start_game(self, _):
        self.game_model.mode = 'connect'
        self.score = [0, 0]
        self.restart_net_engine()
        self.game_model.messages.clear()
        self.game_model.add_message('Establishing server connection...')
        self.game_model.init()
        self.net_engine.start()

    def start_tutorial(self, _i):
        self.game_model.mode = 'tutorial'
        self.restart_net_engine()
        self.game_model.messages.clear()
        self.game_model.add_message('Move the chess pieces and see what happens!')
        self.game_model.tutorial_messages = [
            'Keep moving the pieces at your own pace.',
            'Each piece has its own color, and the board is painted to show where it can move.',
            'You only see where your pieces can move',
            'You will also see any piece that threatens the king.',
            'Note that unlike classic chess, the king can move to a threatened position!',
            'There are no turns!',
            'There are cool-downs (rate limits) instead.',
            'You win the game by capturing the opponent king',
            'The game is played with friends over the internet.',
            'To start a game both you and your friend need to click "Start Game".',
            'Then either you or the friend should type the game identifier that the other was given.',
            'This concludes our tutorial!',
            ]
        self.game_model.init()
        self.net_engine.iter_actions = {}

    def update_label(self):
        self.score_label.text = 'White: %d   Black: %d' % tuple(self.score)
        self.label.text = '\n'.join(self.game_model.messages[-num_msg_lines:])

    def resized(self, _widget, size):
        self.orientation = 'horizontal' if size[0] > size[1] else 'vertical'
        if self.orientation == 'horizontal':
            self.button_pane.orientation = 'vertical'
            self.button_pane.size_hint = (1, .4)
            self.button_pane.size_hint_min_y = 140
        else:
            self.button_pane.orientation = 'horizontal'
            self.button_pane.size_hint = (1, .4)
            self.button_pane.size_hint_min_y = 70
        p = 1/3
        self.info_pane.size_hint = (p, 1) if self.orientation == 'horizontal' else (1, p)

    def handle_text_input(self, entry):
        command = entry.text
        entry.text = ''
        if not command:
            return
        if command[:1] == '/':
            if command == '/help':
                self.game_model.add_message('commands: /help | /reset | /credits')
                return
            self.game_model.add_action(*command[1:].split())
            return
        if self.game_model.active():
            # Chat
            self.game_model.add_action('msg', command)
            return
        self.net_engine.connect(command)

    def king_captured(self, who):
        if self.game_model.mode == 'replay':
            return
        winner = 1 - who%2
        self.score[winner] += 1
        self.game_model.add_message('')
        self.game_model.add_message('%s King Captured!' % self.game_model.player_str(who))
        self.game_model.add_message('%s wins!' % self.game_model.player_str(winner))
        self.net_engine.start_replay()

    def on_clock(self, _interval):
        self.net_engine.iteration()
        self.board_view.update_dst()
        self.board_view.show_board()
Example #20
0
class GameController:
    def __init__(self):
        pygame.init()
        self.__GameModel = GameModel(self)
        self.__GameView = GameView(self, self.__GameModel)
        self.__sounds = Sound()

    def start_screen(self):
        self.__sounds.princess_hit_sound()
        self.__sounds.background_sound()
        waiting = True
        while waiting:
            self.__GameView.draw_start_screen()
            self.start_events()

    def game_over_screen(self):
        self.__sounds.orc_sound()
        waiting = True
        new_highscore = False
        if self.__GameModel.score > self.__GameModel.highscore.data:
            self.__GameModel.highscore.new_hs(self.__GameModel.score)
            new_highscore = True

        self.__GameView.draw_game_over(new_highscore)
        #time.sleep para fazer com que a tela não desapareça mto rápido
        #um draw antes pra paralisar na tela correta
        time.sleep(1.1)
        while waiting:
            self.__GameView.draw_game_over(new_highscore)
            for sprite in self.__GameModel.all_sprites:
                sprite.kill()
            self.start_events()

    def win_screen(self):
        waiting = True
        new_highscore = False
        if self.__GameModel.score > self.__GameModel.highscore.data:
            self.__GameModel.highscore.new_hs(self.__GameModel.score)
            new_highscore = True

        self.__GameView.draw_win_screen(new_highscore)
        #time.sleep para fazer com que a tela não desapareça mto rápido
        #um draw antes pra paralisar na tela correta
        time.sleep(1.1)
        while waiting:
            self.__GameView.draw_win_screen(new_highscore)
            for sprite in self.__GameModel.all_sprites:
                sprite.kill()
            self.start_events()

    def start_game(self):
        self.__GameModel.score = 0
        self.__GameModel.load_map()

        playing = True
        while playing:
            self.game_events()
            self.__GameModel.update_positions()
            self.__GameView.draw_game()

            enemy_hits = pygame.sprite.spritecollide(
                self.__GameModel.princess, self.__GameModel.enemies, False,
                pygame.sprite.collide_mask)
            door_found = pygame.sprite.collide_rect(self.__GameModel.princess,
                                                    self.__GameModel.door_tile)

            if enemy_hits or door_found:
                if enemy_hits:
                    self.game_over_screen()
                if door_found:
                    self.win_screen()

    def game_events(self):
        # Eventos do jogo
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()

    def start_events(self):
        #self.__sounds.background_sound()
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYUP:
                self.start_game()
Example #21
0
def main():
    # MVC pattern (Model View Controller)
    model = GameModel()
    controller = GameController(model)
    view = GameView(model, controller)
Example #22
0
 def __init__(self):
     pygame.init()
     self.__GameModel = GameModel(self)
     self.__GameView = GameView(self, self.__GameModel)
     self.__sounds = Sound()
from game_model import GameModel, GameState, ActionProperties, GameAction, Game
from graph_model import GraphModel
from pg import ppo

import numpy as np
import tensorflow as tf


n_blocks = 4
max_moves = 20
block_names = [chr(i+65) for i in range(n_blocks)]


blocks_world = GameModel(
    global_enums={'filler': [0]},
    object_enums={'label': block_names},
    action_enums={'move': {'on_top_of': ActionProperties(n_nodes=2),
                           'to_table': ActionProperties(n_nodes=1)}},
    edge_enums={'position': ['above', 'below'], 'role': ['from', 'to']})


class BlocksWorldGame(Game):
    """Basic blocks world game"""

    def __init__(self):
        self._stacks = []
        shuffled = [name for name in block_names]
        random.shuffle(shuffled)
        for name in shuffled:
            maximum = len(self._stacks)
            i = random.randrange(maximum+1)
            if i == maximum:
Example #24
0
 def _build_new_game(self):
     self.model = GameModel()
     self.sprites = pg.sprite.LayeredDirty()
     self.enc = EncounterRenderer(self.model, (0, 100, 800, 500))
     self.hud = Hud(self.model, (0, 0, 800, 100))