def start_new_game(self):
     self.game = Game(self,
                      white_player=self.players['white'],
                      black_player=self.players['black'])
     self.game.init()
     self.game.main()
     self.needs_redraw = True
Exemple #2
0
 def __init__(self, host, port):
     """Init the threaded server settings"""
     self.host = host
     self.port = port
     self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     self.client = None
     self.server_comm_pause_start = 0
     self.game = Game()
Exemple #3
0
 def __init__(self, **kwargs):
     super(GameScreen, self).__init__(**kwargs)
     self.game = Game(['DEFAULT', 'DEFAULT'], 0)
     self.words = open('dictionaries/ProgrammingWord').readlines()
     self.timer = sched.scheduler(time.time, time.sleep)
     root_box = BoxLayout(orientation="vertical")
     root_box.add_widget(self.configure_player_now_bar_())
     name_label = DurationClock(text='Нажмите чтобы начать')
     root_box.add_widget(name_label)
     root_box.add_widget(Button(text='Начать', on_press=self.start_game))
     root_box.add_widget(self.config_status_bar_())
     self.add_widget(root_box)
Exemple #4
0
 def on_enter(self, *largs):
     """This method is config game when window is push"""
     self.words = open('dictionaries/' + self.manager.dicts).readlines()
     self.game = Game(self.manager.names, self.manager.mode)
     self.upd()
Exemple #5
0
class GameScreen(Screen):
    """No ideas"""
    def __init__(self, **kwargs):
        super(GameScreen, self).__init__(**kwargs)
        self.game = Game(['DEFAULT', 'DEFAULT'], 0)
        self.words = open('dictionaries/ProgrammingWord').readlines()
        self.timer = sched.scheduler(time.time, time.sleep)
        root_box = BoxLayout(orientation="vertical")
        root_box.add_widget(self.configure_player_now_bar_())
        name_label = DurationClock(text='Нажмите чтобы начать')
        root_box.add_widget(name_label)
        root_box.add_widget(Button(text='Начать', on_press=self.start_game))
        root_box.add_widget(self.config_status_bar_())
        self.add_widget(root_box)

    def on_enter(self, *largs):
        """This method is config game when window is push"""
        self.words = open('dictionaries/' + self.manager.dicts).readlines()
        self.game = Game(self.manager.names, self.manager.mode)
        self.upd()

    @staticmethod
    def configure_player_now_bar_():
        """This method is config player now bar"""
        player_box = BoxLayout(orientation="horizontal", size_hint=(1, .2))
        player_box.add_widget(Label(text='ф'))
        player_box.add_widget(Label(text='a'))
        return player_box

    def config_status_bar_(self):
        """Method to configure status bar add interface"""
        res_box = BoxLayout(orientation='horizontal', size_hint=(1, .1))
        res_box.add_widget(
            Button(text='Передать ход', on_press=self.next, size_hint=(.2, 1)))
        res_box.add_widget(
            Button(text='Выйти', on_press=self.exit, size_hint=(.2, 1)))
        return res_box

    def upd(self):
        """"This method is update player now bar labels"""
        now = self.game.now_play()
        score = self.game.now_players_scroe()
        self.children[0].children[3].children[0].text = now[1] + ': ' + str(
            score[1]) + ' очков'
        self.children[0].children[3].children[1].text = now[0] + ': ' + str(
            score[0]) + ' очков'

    def next(self, instance):
        """This method is push next player"""
        self.game.next()
        self.upd()
        instance.parent.parent.children[2].text = 'Нажмите чтобы начать'

    def exit(self, instance):
        """This method is push prev window"""

        self.manager.transition = SlideTransition(direction="right")
        self.manager.current = self.manager.previous()

    def get(self, instance):
        """This method update score when word is get"""
        text = instance.parent.children[2].text.split('\n')
        text[0] = random.choice(self.words)
        instance.parent.children[2].text = ''.join(text)
        self.game.get_word()
        self.upd()

    def start_game(self, instance):
        """This method start hat timer"""
        instance.text = 'Угадано'
        instance.parent.children[2].text = random.choice(self.words)
        instance.bind(on_press=self.get)
        instance.unbind(on_press=self.start_game)
        for i in range(33, -1, -1):
            Clock.schedule_once(
                partial(instance.parent.children[2].update, str(i)), 33 - i)
Exemple #6
0
from game_state import Game

game = Game()
game.start()
Exemple #7
0
class ThreadedServer():
    """Socket server that received client connections and data"""
    def __init__(self, host, port):
        """Init the threaded server settings"""
        self.host = host
        self.port = port
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.client = None
        self.server_comm_pause_start = 0
        self.game = Game()
        # self.send_comm = False

    def bind(self):
        """Bind IP address and Port for the server"""
        try:
            logging.info(
                'ThreadedServer.bind(): Try to create socket on {}:{}'.format(
                    self.host, self.port))
            self.sock.bind((self.host, self.port))

        except socket.error as e:
            logging.error('ThreadedServer.bind(): {}'.format(str(e)))

        else:
            logging.info(
                'ThreadedServer.bind(): Socket created on {}.{}'.format(
                    self.host, self.port))
            logging.info("==========" * 7)

            self.listen()

    def listen(self):
        """
        Listen for new connections to the server
        and start a new thread for each new connection
        """
        logging.info(
            "ThreadedServer.listen(): listening for new client connection...")
        self.sock.listen(5)

        while True:
            client, address = self.sock.accept()
            self.client = client
            # client.settimeout(10)
            logging.info(
                "================================================================\nThreadedServer.listen(): Connected to: {}:{}\n=========================================================================="
                .format(address[0], str(address[1])))
            threading.Thread(target=self.listen_to_client,
                             args=(client, address, Player())).start()
            logging.info(
                "ThreadedServer.listen() Show active threads \n{}".format(
                    threading.enumerate()))

    def listen_to_client(self, client, address, player):
        """Listen for data being sent from the client"""

        # Client/server Communication loop
        while True:

            try:
                # receive data and decode data,
                # then pass to the player class if data is not empty.
                data = client.recv(8192).decode()

            except socket.error as e:
                logging.error(
                    "ThreadedServer.listen_to_client(): Unable to recevie client data... closing client connection \n{}"
                    .format(str(e)))
                client.close()
                return False

            else:
                # no data received
                if data == "":
                    continue

                else:
                    # always clean incomming data
                    data = sf.clean_json_data(data)

                    # connection confirmation
                    if data == "Handshake":
                        try:
                            response = '''{"connected": "True"}'''
                            client.send(str.encode(response))
                            logging.info(
                                "ThreadedServer.listen_to_client(): connection confirmation sent...\n"
                            )
                            continue

                        except socket.error as e:
                            logging.error(
                                "ThreadedServer.listen_to_client(): Unable to send connection confirmation... closing client connection \n{}"
                                .format(str(e)))
                            client.close()

                    # heartbeat data request for wall and ipads when in lobby
                    elif data == "DataRequest":
                        # logging.info(
                        #     "ThreadedServer.listen_to_client(): {}\n".format(data))
                        client.send(str.encode(self.game.send_game_state()))
                        continue
                    # Current Player stats sent to wall
                    elif data == "WallRequest":
                        # logging.info(
                        #     "ThreadedServer.listen_to_client(): {}\n".format(data))
                        client.send(str.encode(self.game.send_wall_data()))
                        continue
                    # Top 5 players to wall
                    elif data == "Leaderboard":
                        # logging.info(
                        #     "ThreadedServer.listen_to_client(): {}\n".format(data))
                        client.send(str.encode(self.game.send_leaderboard()))
                        continue
                    # Master reset of the game
                    # Torch everything... No survivors, only glory
                    elif data == "for_valhalla":
                        logging.info(
                            "ThreadedServer.listen_to_client(): {}\n".format(
                                data))
                        self.game.reset_game()
                        continue
                    else:
                        # logging.info(
                        #     "ThreadedServer.listen_to_client(): {}\n".format(data))
                        player.update(data, self.game.lap_time_durration)
                        self.game.update_player_data(player)
                        client.send(str.encode(self.game.send_game_state()))
class GameManager(object):

    player_type_flip = {'human': 'ai', 'ai': 'human'}

    def __init__(self):

        self.game = None
        self.screen = None
        self.players = {'white': 'human', 'black': 'ai'}
        self.game_running = True
        self.clock = pygame.time.Clock()
        self.buttons = []
        self.toggles = {}
        self.needs_redraw = True

    def init(self):

        pygame.init()
        self.screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
        self.initialize_buttons()

    def initialize_buttons(self):

        start_button = Button(start_coord, 'Start Game', self.start_new_game,
                              start_anchor)

        def f():
            pass

        black_label = Button(black_label_coord, 'Black:', f, black_anchor)
        black_toggle = ControlToggle(black_coord,
                                     self.players['black'].capitalize(),
                                     self.toggle_black, black_anchor)
        white_label = Button(white_label_coord, 'White:', f, white_anchor)
        white_toggle = ControlToggle(white_coord,
                                     self.players['white'].capitalize(),
                                     self.toggle_white, white_anchor)

        exit_button = Button(exit_coord, 'Exit', self.exit_game, exit_anchor)

        self.buttons.extend((start_button, black_label, black_toggle,
                             white_label, white_toggle, exit_button))
        self.toggles['black'] = black_toggle
        self.toggles['white'] = white_toggle

    def start_new_game(self):
        self.game = Game(self,
                         white_player=self.players['white'],
                         black_player=self.players['black'])
        self.game.init()
        self.game.main()
        self.needs_redraw = True

    def main(self):

        while self.game_running:
            self.handle_input()

            if self.needs_redraw:
                self.draw()
                pygame.display.update()

            self.clock.tick(FPS)

        pygame.quit()

    def handle_input(self):

        for event in pygame.event.get():

            if event.type == QUIT:
                self.exit_game()
            elif event.type == KEYDOWN:
                if event.key == K_ESCAPE:
                    self.exit_game()

            elif event.type == MOUSEBUTTONDOWN:

                for button in self.buttons:
                    if button.mouse_is_over():
                        button.on_click()

    def draw(self):

        self.screen.fill(BLACK)

        for button in self.buttons:
            button.draw(self.screen)

        self.needs_redraw = False

    def exit_game(self):
        self.game_running = False

    def toggle_black(self):

        self.toggle_player('black')

    def toggle_white(self):

        self.toggle_player('white')

    def toggle_player(self, team):

        new_control = GameManager.player_type_flip[self.players[team]]
        self.players[team] = new_control

        self.toggles[team].flip_toggle(new_control.capitalize())
        self.needs_redraw = True