예제 #1
0
    def datagram_received(self, data, addr):
        data = data.decode()
        data = json.loads(data)
        command = data[0]

        if command == DATA:
            players = data[1]

            # собираем ID сервера
            visible_pids = []
            for player in players:
                visible_pids.append(player[J_ID])

            # собираем ID клиента
            client_pids = []
            for pid in game.players:
                client_pids.append(pid)

            # удаляем лишние объекты игроков на клиенте (которые отключились)
            for pid in client_pids:
                if not pid in visible_pids:
                    game.players.pop(pid)

            for player in players:
                pid = player[J_ID]

                if not game.players.get(pid):
                    if player[J_SKIN] == SKIN_BLUE:
                        skin = Texture("images/robots/textures/robot_blue.png")
                    elif player[J_SKIN] == SKIN_ORANGE:
                        skin = Texture(
                            "images/robots/textures/robot_orange.png")
                    else:
                        skin = Texture(
                            "images/robots/textures/robot_green.png")

                    new_player = {pid: Robot(Point(0, 0), skin, angle=0)}
                    new_player[pid].texture.set_size(Size(30, 30))
                    game.players.update(new_player)

                game.players[pid].position = Point(player[J_POSITION_X],
                                                   player[J_POSITION_Y])
                game.players[pid].texture.set_angle(player[J_ANGLE])
        elif command == ID:
            client.id = data[1]
        elif command == KICK:
            info_label.set_text('You have been kicked from the server!')
            client.disconnect()
        elif command == MESSAGE:
            chat_area.value += '{}: {}'.format(data[2], data[1]) + '\n'
        elif command == PING:
            client.ping = round((time() - client.ping_send_time) * 1000)  # мс
예제 #2
0
    def __init__(self, resources):
        self.res = resources
        self.position = Point(0, 0)
        self.visible = True
        self.score = 0
        self.over = False
        self.objects = []

        # creating level and adding walls to form and to pygame walls group
        # self.pacman = Pacman(Position(480, 660), self.res.animations.pacman)
        # self.pacman.visible = False
        # self.add_object(self.pacman)
        self.players = {}
예제 #3
0
    def __init__(self, position, animation, angle=0):
        """
        Initialize GameObject
        :param position: pacman.helper_types.Position
        :param size: pacman.helper_types.Size
        :param texture: pacman.resources.Animation
        """
        super(GameObject, self).__init__(position, Size(40, 40), True)
        sprite.Sprite.__init__(self)

        self.speed = Point(0, 0)
        self.angle = angle

        self.texture = animation
        self.texture.set_size(self.size)
        self.image = animation.frame

        # for backward compatibility
        self.animation = self.texture

        self.rect = self.image.get_rect()
        self.rect.x, self.rect.y = self.position.x, self.position.y
예제 #4
0
def main():
    """!
    @brief Поток отображения клиента
    """
    player = None
    while not main_form.terminated:
        for event in pygame.event.get():
            main_form.gui_events(event)

            if event.type == pygame.QUIT:
                main_form.terminate()

            elif client.connected():
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_ESCAPE:
                        client.disconnect()
                    if client.input:
                        if event.key == pygame.K_w:
                            client.send([BUTTON_DOWN, B_GO_TOP])
                        if event.key == pygame.K_s:
                            client.send([BUTTON_DOWN, B_GO_BOTTOM])
                        if event.key == pygame.K_a:
                            client.send([BUTTON_DOWN, B_GO_LEFT])
                        if event.key == pygame.K_d:
                            client.send([BUTTON_DOWN, B_GO_RIGHT])

                elif event.type == pygame.KEYUP:
                    if client.input:
                        if event.key == pygame.K_w:
                            client.send([BUTTON_UP, B_GO_TOP])
                        if event.key == pygame.K_s:
                            client.send([BUTTON_UP, B_GO_BOTTOM])
                        if event.key == pygame.K_a:
                            client.send([BUTTON_UP, B_GO_LEFT])
                        if event.key == pygame.K_d:
                            client.send([BUTTON_UP, B_GO_RIGHT])
                elif event.type == pygame.MOUSEMOTION:
                    if client.input:
                        client.send([ANGLE, client.angle])

        if game.players.get(client.id):
            # получаем объект игрока (который играет с этого клиента =) )
            player = game.players.get(client.id)

            mouse_pos = pygame.mouse.get_pos()
            mouse_pos = Point(mouse_pos[0], mouse_pos[1])

            if TRACKING_CAMERA:
                client.angle = get_angle(CENTER_POS, player.size, mouse_pos)
            else:
                client.angle = get_angle(player.position, player.size,
                                         mouse_pos)

        res.update()
        game.update()
        if player:
            main_form.update(camera_mode=TRACKING_CAMERA,
                             point=player.position)
        else:
            main_form.update(camera_mode=TRACKING_CAMERA, point=Point(0, 0))

    client.disconnect()
예제 #5
0
from classes.network_constants import *
from classes.helper_types import Size, Point
from classes.constants import FORM_WIDTH, FORM_HEIGHT, FPS

from classes.resources import Resources
from classes.core import Core
from classes.game import Game
from classes.game_object import Robot
from classes.gui_block import GuiPanel
from classes.texture import Texture

DEFAULT_PORT = 22000
TRACKING_CAMERA = True
MAX_CONNECT_ATTEMPTS = 3

CENTER_POS = Point(FORM_WIDTH / 2, FORM_HEIGHT / 2)

CONFIG_FILE = 'config.conf'


def get_angle(pl_pos: Point, size: Size, m_pos: Point) -> float:
    """!
    @brief Возращает угол между мышью и объектом

    @param pl_pos: Point(координаты игрока)
    @param size: Size(helper_types)
    @param m_pos: Point(координаты мыши)
    @return: float(градус поворота)
    """
    x = pl_pos.x + size.width / 2 - m_pos.x
    y = pl_pos.y + size.height / 2 - m_pos.y
예제 #6
0
 def delete_player(self, addr: str):
     self.players[addr].position = Point(1, 1)
     self.players[addr].speed = Point(0, 0)
     self.players.pop(addr)
예제 #7
0
    def datagram_received(self, data, addr):
        data = data.decode()

        # проверяем корректность присланных данных
        try:
            data = json.loads(data)
        except json:
            print('#ERROR: incorrect format of input data')
            return None

        command = data[0]
        players = server.players
        player = server.players.get(addr)

        # подключение, отключение и передача данных
        if command == CONNECT:
            pid = server.get_new_pid()
            print('{} connected ({}:{})!'.format(data[1], addr[0], addr[1]))
            new_player = {addr: PlayerInfo(pid, Point(100, 100), Point(0, 0),
                                            login=data[1],
                                            skin=data[2],
                                            angle=0)
                          }
            players.update(new_player)

            server.send([ID, pid], addr)
        # если игрока не существует и он не был создан (см. выше)
        elif not player:
            print('#ERROR: Player for {} not found - kicking...'.format(addr[0]))
            server.kick_addr(addr)
            return None

        if command == DISCONNECT:
            login = server.players[addr].login
            print('{} disconnected ({}:{})!'.format(login, addr[0], addr[1]))
            server.delete_player(addr)
        elif command == PING:
            player.net_activity = time()
            server.send([PING], addr)
        elif command == BUTTON_DOWN:
            button = data[1]
            if button == B_GO_TOP:
                player.ignore_command[B_GO_TOP] = False
                player.ignore_command[B_GO_BOTTOM] = True
                player.speed.y = -player.speed_amount
            elif button == B_GO_BOTTOM:
                player.ignore_command[B_GO_TOP] = True
                player.ignore_command[B_GO_BOTTOM] = False
                player.speed.y = player.speed_amount
            elif button == B_GO_LEFT:
                player.ignore_command[B_GO_LEFT] = False
                player.ignore_command[B_GO_RIGHT] = True
                player.speed.x = -player.speed_amount
            elif button == B_GO_RIGHT:
                player.ignore_command[B_GO_LEFT] = True
                player.ignore_command[B_GO_RIGHT] = False
                player.speed.x = player.speed_amount
        elif command == BUTTON_UP:
            button = data[1]
            if button == B_GO_TOP and not player.ignore_command[B_GO_TOP] or \
                    button == B_GO_BOTTOM and not player.ignore_command[B_GO_BOTTOM]:
                player.speed.y = 0
            elif button == B_GO_LEFT and not player.ignore_command[B_GO_LEFT] or \
                    button == B_GO_RIGHT and not player.ignore_command[B_GO_RIGHT]:
                player.speed.x = 0
        elif command == ANGLE:
            # получили информацию о направление взгляда игрока
            new_angle = data[1]
            player.angle = new_angle
        elif command == MESSAGE:
            # пришло сообщение от игрока
            login = server.players[addr].login
            print('{}: {}'.format(login, data[1]))
            server.notify_all([MESSAGE, data[1], login])

        # обработка нажатий клавиш
        elif command == C_GO_TOP_DOWN:
            player.ignore_command[C_GO_TOP_UP] = False
            player.ignore_command[C_GO_BOTTOM_UP] = True
            player.speed.y = -player.speed_amount
        elif command == C_GO_BOTTOM_DOWN:
            player.ignore_command[C_GO_TOP_UP] = True
            player.ignore_command[C_GO_BOTTOM_UP] = False
            player.speed.y = player.speed_amount
        elif command == C_GO_LEFT_DOWN:
            player.ignore_command[C_GO_RIGHT_UP] = True
            player.ignore_command[C_GO_LEFT_UP] = False
            player.speed.x = -player.speed_amount
        elif command == C_GO_RIGHT_DOWN:
            player.ignore_command[C_GO_RIGHT_UP] = False
            player.ignore_command[C_GO_LEFT_UP] = True
            player.speed.x = player.speed_amount

        # обработка отпускания клавиш
        elif command == C_GO_TOP_UP and not player.ignore_command[C_GO_TOP_UP]:
            player.speed.y = 0
        elif command == C_GO_BOTTOM_UP and not player.ignore_command[C_GO_BOTTOM_UP]:
            player.speed.y = 0
        elif command == C_GO_LEFT_UP and not player.ignore_command[C_GO_LEFT_UP]:
            player.speed.x = 0
        elif command == C_GO_RIGHT_UP and not player.ignore_command[C_GO_RIGHT_UP]:
            player.speed.x = 0