Ejemplo n.º 1
0
def run_game():
    pygame.mixer.pre_init(44100, -16, 1, 512)
    pygame.init()
    pygame.display.set_caption("Pacman Portal")

    player_input = PlayerInput()
    settings = Settings()
    screen = pygame.display.set_mode((settings.screen_width, settings.screen_height))
    scene = 0   # Intro

    intro_game_master = IntroGameMaster(player_input, settings, screen)
    game_master = None

    while True:
        player_input.check_events()

        if scene == 0:
            intro_game_master.update()
            if player_input.enter:
                scene = 1
                game_master = GameMaster(player_input, settings, screen)
                del intro_game_master
        elif scene == 1:
            game_master.update()
            if game_master.maze.pacman.end_game:
                scene = 0
                intro_game_master = IntroGameMaster(player_input, settings, screen)
                del game_master

        pygame.display.flip()
Ejemplo n.º 2
0
class GameMasterTests(unittest.TestCase):
    def setUp(self):
        players = [Mock(name='player 0'), Mock(name='player 1')]
        generator = Generator()
        start_states = list(
            generator.generate_start_positions(Mock(), len(players))
        )
        self._start_state = random.choice(start_states)
        self._simulator = self._get_simulator(players)
        self._master = GameMaster(self._simulator, self._start_state)
        self._states = []

    def test_game_master(self):
        while not self._simulator.is_finished:
#            if(len(self._states)>0):
#                print("start "+str(self._states[-1]))
            self._master.tick(self._start_state)
#            self._start_state = self._states[-1]
#            print(self._simulator._states)

#        scores = self._simulator.get_scores()
#        print(scores)
#        scores_values = list(scores.values())
#        players = self._simulator.get_players()
#        self.assertEqual(set(players), set(scores.keys()))
#        print(scores)

    def _get_simulator(self, players):
        simulator = Mock()
        simulator._states = []
        simulator._scores = None
        simulator.get_players.return_value = players
        simulator.get_states.return_value = simulator._states
        simulator.get_scores.side_effect = lambda: simulator._scores
        simulator.is_finished = False

        def report_state(state):
            simulator._states.append(state)

        def get_move(player, state, serialize, deserialize):
            return (0, 0)

        def finish_game(scores):
            simulator._scores = scores
            simulator.is_finished = True

        simulator.report_state.side_effect = report_state
        simulator.get_move.side_effect = get_move
        simulator.finish_game.side_effect = finish_game
        return simulator
Ejemplo n.º 3
0
class GameMasterTests(unittest.TestCase):
    def setUp(self):
        players = [Mock(name='player 0'), Mock(name='player 1')]
        generator = Generator()
        start_states = list(generator.generate_start_positions(Mock(),
                                                               len(players)))
        self._start_state = random.choice(start_states)
        self._controller = self._get_controller(players)
        self._master = GameMaster(self._controller, self._start_state)

    def test_that_in_the_end_of_the_game_we_have_empty_heaps(self):
        self._master.tick(self._start_state)
        last_state = self._controller.get_states()[-1]
        empty_heap_sizes = [0] * len(last_state.heap_sizes)
        self.assertEqual(last_state.heap_sizes, empty_heap_sizes)

    def test_that_only_one_player_wins(self):
        self._master.tick(self._start_state)
        scores = self._controller.get_scores()
        scores_values = list(scores.values())
        players = self._controller.get_players()
        self.assertEqual(set(players), set(scores.keys()))
        self.assertTrue(scores_values == [0, 1] or scores_values == [1, 0])

    def _get_controller(self, players):
        controller = Mock()
        controller._states = []
        controller._scores = None
        controller.get_players.return_value = players
        controller.get_states.return_value = controller._states
        controller.get_scores.side_effect = lambda: controller._scores

        def report_state(state):
            controller._states.append(state)

        def get_move(player, heap_sizes, serialize, deserialize):
            allowed = [i for i, size in enumerate(heap_sizes)
                       if size > 0]
            heap_number = random.choice(allowed)
            removed_stones = random.randint(1, heap_sizes[heap_number])
            return (heap_number, removed_stones)

        def finish_game(scores):
            controller._scores = scores

        controller.report_state.side_effect = report_state
        controller.get_move.side_effect = get_move
        controller.finish_game.side_effect = finish_game
        return controller
Ejemplo n.º 4
0
def main():
    print('''
                         _____
                      .-" .-. "-.
                    _/ '=(0.0)=' \_
                  /`   .='|m|'=.   `\
                  \________________ /
              .--.__///`'-,__~\\\\~`
             / /6|__\// a (__)-\\\\
             \ \/--`((   ._\   ,)))
             /  \\  ))\  -==-  (O)(
            /    )\((((\   .  /)))))
           /  _.' /  __(`~~~~`)__
          //"\\,-'-"`   `~~~~\\~~`"-.
         //  /`"              `      `\        
                   _           _       
                  (_)         | |      
             _ __  _ _ __ __ _| |_ ___ 
            | '_ \| | '__/ _` | __/ _ \
            | |_) | | | | (_| | ||  __/
            | .__/|_|_|  \__,_|\__\___|
            | |                        
            |_|                        
    ''')

    GameMaster().turn()
Ejemplo n.º 5
0
 def setUp(self):
     players = [Mock(name='player 0'), Mock(name='player 1')]
     generator = Generator()
     start_states = list(generator.generate_start_positions(Mock(),
                                                            len(players)))
     self._start_state = random.choice(start_states)
     self._controller = self._get_controller(players)
     self._master = GameMaster(self._controller, self._start_state)
Ejemplo n.º 6
0
def main():
    """This runs the protocol on port 8000"""
    factory = protocol.ServerFactory()
    factory.protocol = Echo
    factory.clients = []
    factory.GM = GameMaster()
    factory.p2c = {}  # (player, game) -> client
    reactor.listenTCP(8000, factory)
    reactor.run()
Ejemplo n.º 7
0
    def makeMove(self, movable_statement):
        """
        Takes a MOVABLE statement and makes the corresponding move. This will
        result in a change of the game state, and therefore requires updating
        the KB in the Game Master.

        The statement should come directly from the result of the MOVABLE query
        issued to the KB, in the following format:
        (movable tile3 pos1 pos3 pos2 pos3)

        Args:
            movable_statement: A Statement object that contains one of the currently viable moves

        Returns:
            None
        """
        ### Student code goes here
        if GameMaster.isMovableLegal(self, movable_statement):
            vars = movable_statement.terms
            currTile = str(vars[0])
            oldX = str(vars[1])
            oldY = str(vars[2])
            newX = str(vars[3])
            newY = str(vars[4])

            q = parse_input('fact: (posn ?t ' + newX + ' ' + newY + ')')
            match = self.kb.kb_ask(q)
            oldTile = match[0].bindings_dict['?t']

            self.kb.kb_retract(
                parse_input('fact: (posn ' + currTile + ' ' + oldX + ' ' +
                            oldY + ')'))
            self.kb.kb_retract(
                parse_input('fact: (posn ' + oldTile + ' ' + newX + ' ' +
                            newY + ')'))

            self.kb.kb_assert(
                parse_input('fact: (posn ' + currTile + ' ' + newX + ' ' +
                            newY + ')'))
            self.kb.kb_assert(
                parse_input('fact: (posn ' + oldTile + ' ' + oldX + ' ' +
                            oldY + ')'))

        pass
Ejemplo n.º 8
0
def run_game():
    # Initialize pygame, settings, and screen object
    pygame.mixer.pre_init(44100, -16, 1, 512)
    pygame.init()
    ai_settings = Settings()
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height)
    )
    game_master = GameMaster(screen)
    title_screen = TitleScreen(screen)
    pygame.display.set_caption("Space Invaders")

    # Make the Play button
    play_button = Button(screen, "Play")

    # Create an instance to store game statistics and create a scoreboard
    stats = GameStats(ai_settings)
    sb = Scoreboard(ai_settings, screen, stats)

    # Make a ship, group of bunkers, a group of bullets, and a group of aliens
    ship = Ship(ai_settings, screen)
    bunkers = Group()
    bullets = Group()
    aliens = Group()
    lasers = Group()

    game_master.last_laser_shot = pygame.time.get_ticks()
    game_master.next_laser_shot = game_master.last_laser_shot + random.randrange(250, 2000)

    gf.create_bunkers(bunkers, screen)
    gf.create_fleet(ai_settings, screen, aliens)

    # Start the main loop for the game
    while True:
        gf.check_events(ai_settings, game_master, screen, stats, sb, play_button, ship, aliens, bullets)

        if stats.game_active:
            ship.update()
            gf.update_bullets(ai_settings, game_master, screen, stats, sb, bunkers, aliens, bullets)
            gf.update_aliens(ai_settings, stats, screen, sb, ship, aliens, bullets)
            gf.update_lasers(ai_settings, screen, game_master, aliens, lasers, ship, bunkers, stats, sb, bullets)
            gf.update_screen(ai_settings, screen, sb, ship, bunkers, aliens, game_master.alien_explosions,
                             lasers, bullets, game_master.ufo)
            game_master.check_ufo_spawn(screen, bullets, stats, sb)
        else:
            gf.update_title_screen(play_button, title_screen)
Ejemplo n.º 9
0
    def makeMove(self, movable_statement):
        """
        Takes a MOVABLE statement and makes the corresponding move. This will
        result in a change of the game state, and therefore requires updating
        the KB in the Game Master.

        The statement should come directly from the result of the MOVABLE query
        issued to the KB, in the following format:
        (movable tile3 pos1 pos3 pos2 pos3)

        Args:
            movable_statement: A Statement object that contains one of the currently viable moves

        Returns:
            None
        """
        ### Student code goes here
        if GameMaster.isMovableLegal(self, movable_statement):
            # general infomation
            movable_tile = str(movable_statement.terms[0].term.element)
            from_x = str(movable_statement.terms[1].term.element)
            from_y = str(movable_statement.terms[2].term.element)
            to_x = str(movable_statement.terms[3].term.element)
            to_y = str(movable_statement.terms[4].term.element)

            # retract fact
            fact = "fact: (addr " + movable_tile + " " + from_x + " " + from_y + ")"
            self.kb.kb_retract(parse_input(fact))

            fact = "fact: (addr empty " + to_x + " " + to_y + ")"
            self.kb.kb_retract(parse_input(fact))

            # assert fact
            fact = "fact: (addr " + movable_tile + " " + to_x + " " + to_y + ")"
            self.kb.kb_assert(parse_input(fact))

            fact = "fact: (addr empty " + from_x + " " + from_y + ")"
            self.kb.kb_assert(parse_input(fact))
Ejemplo n.º 10
0
from PySide2.QtWidgets import (QApplication, QMainWindow)

from player_view import PlayerView
from game_master import GameMaster

app = QApplication([])

window = QMainWindow()
window.setMinimumSize(800, 600)

playerOneView = PlayerView(window)
gameMaster = GameMaster()
# zone1.clicked.connect(log.addEntry)
# QObject.connect(zone1,SIGNAL('clicked()'),log.addEntry)

# window.setCentralWidget(log)

# mylabel.setSizePolicy(QSizePolicy.Expanding,QSizePolicy.Expanding)
window.show()
# mylabel.adjustSize()
app.exec_()
print(str(window.size()))
Ejemplo n.º 11
0
from game_master import GameMaster
import os
import cv2

img_dir = '../image'
gm = GameMaster(os.path.join(img_dir, 'board.png'))
gm.load_image(img_dir)

str = "1A"

ret = (int(str[0]) - 1) * 4

for i in range(0, len(str)):
    print(str[i] - 'A')
Ejemplo n.º 12
0
                raise
            finally:
                self.mutex_lock.release()
        except asyncio.CancelledError:
            raise

    def reset(self):
        self.gm.game_reset()
        if self.scheduled_task is not None:
            self.scheduled_task.cancel()
            self.scheduled_task = None


# init
img_dir = '../image'
bot = GameMaster(os.path.join(img_dir, 'board.png'))
bot.load_image(img_dir)
mtgm = MultiThreadGameMaster(gm=bot)
token = read_token()
active_channel_id = read_active_channel_id()
lock = asyncio.Lock()


# bot を終了するコマンド
async def run_quit(message):
    await message.channel.send('botを終了しました。')
    sys.exit()


def get_cmd_list():
    return """
Ejemplo n.º 13
0
    def makeMove(self, movable_statement):
        """
        Takes a MOVABLE statement and makes the corresponding move. This will
        result in a change of the game state, and therefore requires updating
        the KB in the Game Master.

        The statement should come directly from the result of the MOVABLE query
        issued to the KB, in the following format:
        (movable disk1 peg1 peg3)

        Args:
            movable_statement: A Statement object that contains one of the currently viable moves

        Returns:
            None
        """
        ### Student code goes here

        # judge if legal
        if GameMaster.isMovableLegal(self, movable_statement):
            ### ge-information
            movable_disk = movable_statement.terms[0]
            from_where = movable_statement.terms[1]
            to_where = movable_statement.terms[2]
            Game_status = self.getGameState()

            #### get the one under movable
            curr_peg = int(from_where.term.element[3:])
            curr_peg_state = Game_status[curr_peg - 1]  # initial peg num is 1

            if len(curr_peg_state) < 2: next_top = "base" + str(curr_peg)
            else: next_top = "disk" + str(curr_peg_state[1])

            ### get the top on target_peg
            target_peg = int(to_where.term.element[3:])
            target_peg_state = Game_status[target_peg -
                                           1]  # initial peg num is 1
            if len(target_peg_state) < 1: target_top = "base" + str(target_peg)
            else: target_top = "disk" + str(target_peg_state[0])

            ## fact above
            # construct the question
            disk_str = str(movable_disk)
            questionAbove = "fact: (above disk ?x)".replace("disk", disk_str)

            # ask
            askPegNumber = parse_input(questionAbove)
            statement_matched = self.kb.kb_ask(askPegNumber)

            # retract Above fact
            for ind, item in statement_matched.list_of_bindings:
                fact = item[0]
                if fact in self.kb.facts:
                    self.kb.kb_retract(fact)

            # retract 2 original tops
            del_fact1 = parse_input("fact: (top " + str(movable_disk) + " " +
                                    str(from_where) + ")")
            del_fact2 = parse_input("fact: (top " + str(target_top) + " " +
                                    str(to_where) + ")")
            self.kb.kb_retract(del_fact1)
            self.kb.kb_retract(del_fact2)

            # add new Above
            general_fact = "fact: (above disk_x disk_y)"
            general_fact = general_fact.replace("disk_x", disk_str)
            general_fact = general_fact.replace("disk_y", target_top)
            new_fact = parse_input(general_fact)
            self.kb.kb_assert(new_fact)

            ## fact top
            general_fact = "fact: (top disk peg)"
            general_fact = general_fact.replace("disk", next_top)
            general_fact = general_fact.replace("peg", str(from_where))
            new_fact = parse_input(general_fact)
            self.kb.kb_assert(new_fact)

            general_fact = "fact: (top disk peg)"
            general_fact = general_fact.replace("disk", str(movable_disk))
            general_fact = general_fact.replace("peg", str(to_where))
            new_fact = parse_input(general_fact)
            self.kb.kb_assert(new_fact)

        pass