Exemplo n.º 1
0
    def __init__(self, agent, end_score=10):
        self.agent = agent
        self.score1 = 0
        self.score2 = 0
        self.end_score = end_score

        pygame.init()

        self.screen = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT])

        pygame.display.set_caption('Pong')

        pygame.mouse.set_visible(1)

        self.font = pygame.font.Font(None, 36)

        self.background = pygame.Surface(self.screen.get_size())

        self.ball = Ball(WHITE)
        self.balls = pygame.sprite.Group()
        self.balls.add(self.ball)

        self.player_bottom = Player(580, PLAYER_WIDTH, WHITE)
        self.player_top = Player(25, PLAYER_WIDTH, WHITE)

        self.movingsprites = pygame.sprite.Group()
        self.movingsprites.add(self.player_bottom)
        self.movingsprites.add(self.player_top)
        self.movingsprites.add(self.ball)
        self.clock = pygame.time.Clock()
Exemplo n.º 2
0
 def __init__(self, initial_delay, interval, application):
     self.ip = my_ip()
     self.api_version = 'v1'
     self.next_ball = Ball()
     self.view = []
     self.fanout = int(os.environ['FANOUT'])
     self.ttl = int(os.environ['TTL'])
     self.stability_oracle = StabilityOracle(self.ttl)
     self.ordering = EpTOOrdering(self.stability_oracle, application)
     self.schedule_repeated_task(initial_delay, interval)
Exemplo n.º 3
0
def setup():
    """Sets up the game for playing and initialises objects
    """

    pygame.init()

    clock = pygame.time.Clock()
    display = pygame.display
    screen = display.set_mode((BOARD_WIDTH, BOARD_HEIGHT))

    player = Paddle(player_color)
    ball_one = Ball((4, 3), DIFFICULTY)
    ball_two = Ball((3, 2), DIFFICULTY)
    board = Board(screen=screen, player=player, balls=[ball_one, ball_two])
    return board, clock, display
Exemplo n.º 4
0
    def repeated_task(self):

        logger.debug('This repeated_task is started.',
                     next_ball=self.next_ball)

        if not self.next_ball.is_empty():

            self.next_ball.increase_events_ttl()
            logger.debug('I increased the ttl of events in self.next_ball.')
            self.view = self.get_k_view(self.fanout)
            logger.info('I got a k-view from cyclon: ' + str(self.view))
            for destination in self.view:
                response = self.send_next_ball(destination)
                logger.info('I sent next ball to ' + destination +
                            ' and I got ' + str(response))

        self.ordering.order(self.next_ball.copy())
        self.next_ball = Ball()
        logger.debug("I reset next_ball.", next_ball=self.next_ball)
Exemplo n.º 5
0
class TestBall(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        pass

    def setUp(self):
        self.ball = Ball()

    def test_empty_ball_should_be_empty(self):
        self.assertTrue(self.ball.is_empty())

    def test_non_empty_ball_should_not_be_empty(self):
        self.ball = Helpers.generate_non_empty_ball(3)
        self.assertFalse(self.ball.is_empty())

    def test_empty_ball_to_string(self):
        self.assertEqual(str(self.ball), "[]")

    def test_non_empty_ball_to_string(self):
        pass

    def test_ball_increase_events_ttl(self):
        self.ball = Helpers.generate_non_empty_ball(3)
        events = list(self.ball)
        ttl = [event.ttl for event in events]
        for i in range(len(events)):
            self.assertEqual(events[i].ttl, ttl[i])
        self.ball.increase_events_ttl()
        for i in range(len(events)):
            self.assertEqual(events[i].ttl, ttl[i] + 1)

    def test_add_different_events_to_ball(self):
        e1 = Event("source")
        self.ball.add(e1)
        e2 = Event("source")
        self.ball.add(e2)
        self.assertEqual(len(self.ball), 2)

    def test_add_to_ball_should_allow_only_to_add_events(self):
        with self.assertRaises(TypeError):
            self.ball.add("event")
Exemplo n.º 6
0
class Pong:
    def __init__(self, agent, end_score=10):
        self.agent = agent
        self.score1 = 0
        self.score2 = 0
        self.end_score = end_score

        pygame.init()

        self.screen = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT])

        pygame.display.set_caption('Pong')

        pygame.mouse.set_visible(1)

        self.font = pygame.font.Font(None, 36)

        self.background = pygame.Surface(self.screen.get_size())

        self.ball = Ball(WHITE)
        self.balls = pygame.sprite.Group()
        self.balls.add(self.ball)

        self.player_bottom = Player(580, PLAYER_WIDTH, WHITE)
        self.player_top = Player(25, PLAYER_WIDTH, WHITE)

        self.movingsprites = pygame.sprite.Group()
        self.movingsprites.add(self.player_bottom)
        self.movingsprites.add(self.player_top)
        self.movingsprites.add(self.ball)
        self.clock = pygame.time.Clock()

    def play(self):

        done = False
        exit_program = False

        while not exit_program:

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    exit_program = True

            if not done:
                key_state = pygame.key.get_pressed()
                action_player_2 = self.agent.get_direction(
                    key_state, self.ball.x, self.ball.y,
                    self.player_top.rect.x, self.player_bottom.rect.x)
                done, _, _ = self.step(
                    key_state[pygame.K_RIGHT] - key_state[pygame.K_LEFT] + 1,
                    action_player_2)

            if done:
                text = self.font.render("Game Over", 1, (200, 200, 200))
                textpos = text.get_rect(centerx=self.background.get_width() /
                                        2)
                textpos.top = 50
                self.screen.blit(text, textpos)
                exit_program = True

        pygame.quit()

    def step(self, action_player_bottom,
             action_player_top) -> (bool, tuple, float):
        self.screen.fill(BLACK)

        self.player_bottom.update(action_player_bottom - 1)
        self.player_top.update(action_player_top - 1)
        self.ball.update()

        reward = 0
        if self.ball.y < 0:
            reward = -10
            self.score1 += 1
            self.ball.reset()
        elif self.ball.y > 600:
            reward = 10
            self.score2 += 1
            self.ball.reset()

        if pygame.sprite.spritecollide(self.player_bottom, self.balls, False):
            reward = -0.5
            diff = (self.player_bottom.rect.x + self.player_bottom.width /
                    2) - (self.ball.rect.x + self.ball.width / 2)

            self.ball.y = 570
            self.ball.bounce(diff)

        if pygame.sprite.spritecollide(self.player_top, self.balls, False):
            reward = 1
            diff = (self.player_top.rect.x + self.player_top.width / 2) - (
                self.ball.rect.x + self.ball.width / 2)

            self.ball.y = 40
            self.ball.bounce(diff)

        scoreprint = "Player 1: " + str(self.score1)
        text = self.font.render(scoreprint, 1, WHITE)
        textpos = (0, 0)
        self.screen.blit(text, textpos)

        scoreprint = "Player 2: " + str(self.score2)
        text = self.font.render(scoreprint, 1, WHITE)
        textpos = (300, 0)
        self.screen.blit(text, textpos)

        self.movingsprites.draw(self.screen)

        pygame.display.flip()

        self.clock.tick(30)

        done = False
        if self.score1 == self.end_score or self.score2 == self.end_score:
            done = True
        return done, Positions(self.ball.x, self.ball.y,
                               self.player_bottom.rect.x,
                               self.player_top.rect.x), reward
Exemplo n.º 7
0
 def setUp(self):
     self.ball = Ball()
Exemplo n.º 8
0
 def generate_empty_ball(cls):
     return Ball()
Exemplo n.º 9
0
class EpTODissemination(object):
    def __init__(self, initial_delay, interval, application):
        self.ip = my_ip()
        self.api_version = 'v1'
        self.next_ball = Ball()
        self.view = []
        self.fanout = int(os.environ['FANOUT'])
        self.ttl = int(os.environ['TTL'])
        self.stability_oracle = StabilityOracle(self.ttl)
        self.ordering = EpTOOrdering(self.stability_oracle, application)
        self.schedule_repeated_task(initial_delay, interval)

    def schedule_repeated_task(self, initial_delay, interval):
        logger.debug(
            'This is a repeated task but I am waiting a delay to start.',
            delay=initial_delay)
        time.sleep(initial_delay)
        scheduler = BackgroundScheduler()
        scheduler.add_job(self.repeated_task,
                          'interval',
                          seconds=interval,
                          max_instances=1)
        scheduler.start()

    def broadcast(self, data: str = None):
        event = Event(self.ip, data=data, ts=self.stability_oracle.get_clock())
        logger.debug('I am adding an event to next_ball.', added_event=event)
        self.next_ball.add(event)

    def receive_ball(self, received_ball):
        logger.debug('I received a ball.', received_ball=received_ball)
        ball = []
        for event in received_ball:
            logger.debug('Looping events.', current_event=event)
            ball.append(Event.from_dict(event))

        for event in ball:
            if event.ttl < self.ttl:
                if event in self.next_ball:
                    for e in self.next_ball:
                        if e.event_id == event.event_id and e.ttl < event.ttl:
                            e.ttl = event.ttl
                else:
                    self.next_ball.add(event)
            self.stability_oracle.update_clock(event.ts)

    def get_k_view(self, k):
        logger.debug('Getting PartialView of size k from Cyclon', k=k)
        ret = requests.get('http://localhost:5000/' + self.api_version +
                           '/k-view',
                           params={'k': k},
                           timeout=5)
        logger.debug('I got the a response:', response=ret.content)
        return json.loads(ret.content)
        # return [ip.encode('ascii', 'ignore') for ip in json.loads(ret.content)]

    def send_next_ball(self, destination_ip):
        destination = os.getenv('TEST_IP',
                                format_address(destination_ip, 5001))
        m = Message(format_address(self.ip, 5001), destination, self.next_ball)
        logger.debug('I am sending next ball message.',
                     message=m.to_json(),
                     destination=destination)
        ret = requests.post(m.destination + '/' + self.api_version +
                            '/send-ball',
                            json=m.to_json(),
                            timeout=5)
        return ret.content

    # Task executed every delta time units
    def repeated_task(self):

        logger.debug('This repeated_task is started.',
                     next_ball=self.next_ball)

        if not self.next_ball.is_empty():

            self.next_ball.increase_events_ttl()
            logger.debug('I increased the ttl of events in self.next_ball.')
            self.view = self.get_k_view(self.fanout)
            logger.info('I got a k-view from cyclon: ' + str(self.view))
            for destination in self.view:
                response = self.send_next_ball(destination)
                logger.info('I sent next ball to ' + destination +
                            ' and I got ' + str(response))

        self.ordering.order(self.next_ball.copy())
        self.next_ball = Ball()
        logger.debug("I reset next_ball.", next_ball=self.next_ball)