Example #1
0
    def __init__(self, agent_black=None, agent_white=None, gui=True, dir_save=None):
        """
        BLACK always has the first move on the center of the board.
        :param agent_black: agent or None(human)
        :param agent_white: agent or None(human)
        :param gui: if show GUI; always true if there are human playing
        :param dir_save: directory to save board image if GUI is shown; no save for None
        """
        self.agent_black = agent_black
        self.agent_white = agent_white

        self.board = Board(next_color='BLACK')

        gui = gui if agent_black and agent_white else True
        self.ui = UI() if gui else None
        self.dir_save = dir_save

        # Metadata
        self.time_elapsed = None
Example #2
0
class LocalMenuState(State):
    def __init__(self):
        super(LocalMenuState, self).__init__()
        self.ui = UI()

    def on_exit(self):
        print 'local_menu on_exit'

    def update(self, screen, dt):
        self.ui.draw(screen)
        self.ui.update(dt)

    def on_enter(self, params=None):
        print 'local_menu on_enter'

    def event_handler(self, event):
        self.ui.event_handler(event)
Example #3
0
class Match:
    def __init__(self, agent_black=None, agent_white=None, gui=True, dir_save=None):
        """
        BLACK always has the first move on the center of the board.
        :param agent_black: agent or None(human)
        :param agent_white: agent or None(human)
        :param gui: if show GUI; always true if there are human playing
        :param dir_save: directory to save board image if GUI is shown; no save for None
        """
        self.agent_black = agent_black
        self.agent_white = agent_white

        self.board = Board(next_color='BLACK')

        gui = gui if agent_black and agent_white else True
        self.ui = UI() if gui else None
        self.dir_save = dir_save

        # Metadata
        self.time_elapsed = None

    @property
    def winner(self):
        return self.board.winner

    @property
    def next(self):
        return self.board.next

    @property
    def counter_move(self):
        return self.board.counter_move

    def start(self):
        if self.ui:
            self._start_with_ui()
        else:
            self._start_without_ui()

    def _start_with_ui(self):
        """Start the game with GUI."""
        self.ui.initialize()
        self.time_elapsed = time.time()

        # First move is fixed on the center of board
        first_move = (10, 10)
        self.board.put_stone(first_move, check_legal=False)
        self.ui.draw(first_move, opponent_color(self.board.next))

        # Take turns to play move
        while self.board.winner is None:
            if self.board.next == 'BLACK':
                point = self.perform_one_move(self.agent_black)
            else:
                point = self.perform_one_move(self.agent_white)

            # Check if action is legal
            if point not in self.board.legal_actions:
                continue

            # Apply action
            prev_legal_actions = self.board.legal_actions.copy()
            self.board.put_stone(point, check_legal=False)
            # Remove previous legal actions on board
            for action in prev_legal_actions:
                self.ui.remove(action)
            # Draw new point
            self.ui.draw(point, opponent_color(self.board.next))
            # Update new legal actions and any removed groups
            if self.board.winner:
                for group in self.board.removed_groups:
                    for point in group.points:
                        self.ui.remove(point)
                if self.board.end_by_no_legal_actions:
                    print('Game ends early (no legal action is available for %s)' % self.board.next)
            else:
                for action in self.board.legal_actions:
                    self.ui.draw(action, 'BLUE', 8)

        self.time_elapsed = time.time() - self.time_elapsed
        if self.dir_save:
            path_file = join(self.dir_save, 'go_' + str(time.time()) + '.jpg')
            self.ui.save_image(path_file)
            print('Board image saved in file ' + path_file)

    def _start_without_ui(self):
        """Start the game without GUI. Only possible when no human is playing."""
        # First move is fixed on the center of board
        self.time_elapsed = time.time()
        first_move = (10, 10)
        self.board.put_stone(first_move, check_legal=False)

        # Take turns to play move
        while self.board.winner is None:
            if self.board.next == 'BLACK':
                point = self.perform_one_move(self.agent_black)
            else:
                point = self.perform_one_move(self.agent_white)

            # Apply action
            self.board.put_stone(point, check_legal=False)  # Assuming agent always gives legal actions

        if self.board.end_by_no_legal_actions:
            print('Game ends early (no legal action is available for %s)' % self.board.next)

        self.time_elapsed = time.time() - self.time_elapsed

    def perform_one_move(self, agent):
        if agent:
            return self._move_by_agent(agent)
        else:
            return self._move_by_human()

    def _move_by_agent(self, agent):
        if self.ui:
            pygame.time.wait(100)
            pygame.event.get()
        return agent.get_action(self.board)

    def _move_by_human(self):
        while True:
            pygame.time.wait(100)
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                    return
                if event.type == pygame.MOUSEBUTTONDOWN:
                    if event.button == 1 and self.ui.outline.collidepoint(event.pos):
                        x = int(round(((event.pos[0] - 5) / 40.0), 0))
                        y = int(round(((event.pos[1] - 5) / 40.0), 0))
                        point = (x, y)
                        stone = self.board.exist_stone(point)
                        if not stone:
                            return point
Example #4
0
    def __init__(self, character, renderer, proxy, input_mgr, res_mgr,
                 audio_mgr, conf):
        """Constructor.

        :param character: The character name
        :type character: str

        :param renderer: The rederer instance.
        :type renderer: :class:`renderer.Renderer`

        :param proxy: The message proxy
        :type proxy: :class:`network.message.MessageProxy`

        :param input_mgr: The input manager
        :type input_mgr: :class:`core.InputManager`

        :param res_mgr: The resource manager
        :type res_mgr: :class:`loader.ResourceManager`

        :param audio_mgr: The audio manager
        :type audio_mgr: :class:`game.audio.AudioManager`

        :param conf: Configuration
        :type conf: mapping
        """
        self.renderer = renderer
        self.proxy = proxy

        # Setup the context
        context = Context(conf)
        context.input_mgr = input_mgr
        context.res_mgr = res_mgr
        context.audio_mgr = audio_mgr

        # Setup the player
        c_res = res_mgr.get('/characters')
        c_data = c_res.data['map'][character]
        context.character_name = c_data['name']
        context.character_type = ActorType[c_data['type']]
        context.character_avatar = c_data['avatar']

        # Setup the level matrix
        map_res = res_mgr.get('/map')
        context.matrix = map_res['matrix']
        context.scale_factor = map_res.data['scale_factor']

        # Setup lights, scene, camera, terrain and map
        context.light = self.setup_light()
        context.scene = self.setup_scene(context)
        context.camera, context.ratio = self.setup_camera(context)
        context.terrain = self.setup_terrain(context)
        context.map = self.setup_map(context)

        # Setup UI
        ui_res = context.res_mgr.get('/ui')
        player_data = {
            'name': context.character_name,
            'type': context.character_type,
            'avatar': context.character_avatar,
            'avatar_res': c_res['avatar'],
        }
        context.ui = UI(ui_res, self.renderer.width, self.renderer.height,
                        player_data)
        self.context = context

        # Client status variable
        self.exit = False  # Wether or not the client should stop the game loop
        self.last_update = None  # Last tick update

        self.sync_counter = count()  # The computed time delta with the server
        self._syncing = {}
        self.delta = 0  # The computed time delta with the server

        self.time_acc = 0.0  # FPS time accumulator
        self.fps_count = 0  # FPS counter
Example #5
0
 def __init__(self):
     super(LocalMenuState, self).__init__()
     self.ui = UI()
from game.player import Player
from game.sprite import *
from game.raycaster import ray_casting_walls
from game.ui import UI
from game.logic import Logic

# initializing game
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT), pygame.DOUBLEBUF)
clock = pygame.time.Clock()

# game objects
screen_map = pygame.Surface(MAP_RESOLUTION)
sprites = SpriteSet()
player = Player(sprites)
ui = UI(screen, screen_map, player, clock)
logic = Logic(player, sprites, ui)

# displaying initial screen
ui.menu()
pygame.mouse.set_visible(False)
ui.play_music()

while True:
    player.movement()
    ui.background()
    walls, wall_shot = ray_casting_walls(player, ui.textures)

    # UI items
    ui.world(walls + [obj.object_locate(player) for obj in sprites.list_of_objects])
    ui.fps(clock)
Example #7
0
 def setUp(self):
     self.host = 'example.com'
     self.port = 12345
     self.reactor = StubReactor()
     self.ui = UI(self.reactor, windowFactory=StubWindow)
Example #8
0
class UITests(TestCase):
    """
    Tests for L{UI}.
    """

    def setUp(self):
        self.host = 'example.com'
        self.port = 12345
        self.reactor = StubReactor()
        self.ui = UI(self.reactor, windowFactory=StubWindow)

    def test_defaults(self):
        """
        Instantiating a L{UI} with no arguments should work and should
        use appropriate default values for the C{reactor} and
        C{windowFactory}.
        """
        from twisted.internet import reactor
        from game.view import Window
        ui = UI()
        self.assertIdentical(ui.reactor, reactor)
        self.assertIdentical(ui.windowFactory, Window)


    def test_connect(self):
        """
        L{UI.connect} should I{connect} to the Game Server on the given (host,
        port) TUPLE (XXX use an endpoint).
        """
        self.ui.connect((self.host, self.port))
        [(listenedHost,
          listenedPort,
          factory)] = self.reactor.tcpConnectionAttempts
        self.assertEqual(listenedHost, self.host)
        self.assertEqual(listenedPort, self.port)
        protocol = factory.buildProtocol((self.host, self.port)
                                         ).wrappedProtocol
        self.assertTrue(isinstance(protocol, NetworkController))
        self.assertEqual(protocol.environment, None)
        self.assertEqual(protocol.clock, self.reactor)


    def test_connectionSuccessFiresDeferred(self):
        """
        When Twisted tells the factory to build a protocol and then tells the
        protocol that the connection is made, the Deferred that L{UI.connect}
        returns should fire with the L{NetworkController} instance.
        """

        def gotProtocol(protocolWhatWasGot):
            """
            Wrapping is bad for you.
            """
            self.assertIdentical(protocolWhatWasGot, protocol.wrappedProtocol)
            self.assertIdentical(protocolWhatWasGot.transport, protocol)

        d = self.ui.connect((self.host, self.port))
        d.addCallback(gotProtocol)
        factory = self.reactor.tcpConnectionAttempts[0][2]
        protocol = factory.buildProtocol((self.host, self.port))
        protocol.makeConnection(StringTransport())
        return d


    def test_start(self):
        """
        L{UI.start} should connect to the game server, introduce
        itself, and create a Window with the environment when the
        introduction is reciprocated.
        """
        class Introducable(object):
            """
            Thing which records L{introduce} calls.

            @ivar introductions: list of True.
            @ivar environment: Some object.
            """

            def __init__(self):
                self.introductions = []
                self.environment = object()

            def introduce(self):
                """
                Record the fact that an introduction was attempted.
                """
                self.introductions.append(True)
                return self.environment

        environments = []
        introducable = Introducable()
        connections = {(self.host, self.port): succeed(introducable)}
        self.ui.connect = connections.pop
        self.ui.gotIntroduced = environments.append
        self.ui.start((self.host, self.port))
        self.assertEqual(introducable.introductions, [True])
        self.assertEqual(environments, [introducable.environment])


    def test_gotIntroduced(self):
        """
        When the introduction has been reciprocated, the L{UI} should
        start the Environment and create a L{Window} and call
        L{Window.go} on it.
        """
        starts = []
        environment = Environment(3, None)
        environment.start = lambda: starts.append(True)
        self.ui.gotIntroduced(environment)
        self.assertIdentical(self.ui.window.environment, environment)
        self.assertIdentical(self.ui.window.clock, self.reactor)
        self.assertEqual(self.ui.window.went, [True])
        self.assertEqual(starts, [True])


    def test_gotIntroducedWithInitialPlayer(self):
        """
        The initial L{Player} in the L{Environment} should be passed
        to L{UI.gotInitialPlayer}.
        """
        player = object()
        environment = Environment(10, Clock())
        environment.setInitialPlayer(player)
        initialEvents = []
        def gotInitialPlayer(player):
            initialEvents.append(('player', player))
        self.ui.gotInitialPlayer = gotInitialPlayer
        self.ui.gotIntroduced(environment)
        self.assertEquals(initialEvents, [('player', player)]),


    def test_gotInitialPlayer(self):
        """
        After L{UI.gotInitialPlayer}, that player should have a view
        in and a controller on the window.
        """
        player = object()
        window = self.ui.window = StubWindow(None, None)
        self.ui.gotInitialPlayer(player)
        # XXX The view needs to do something, maybe.
        self.assertTrue(
            isinstance(window.controller, PlayerController))
        self.assertIdentical(window.controller.player, player)


    def test_noInitialPlayer(self):
        """
        If no initial L{Player} is available in the L{Environment}, no view or
        controller should be created.
        """
        environment = Environment(10, Clock())
        initialPlayers = []
        self.ui.gotInitialPlayer = initialPlayers.append
        self.ui.gotIntroduced(environment)
        self.assertEqual(len(initialPlayers), 0)
        self.assertIdentical(self.ui.window.controller, None)