Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import random
- import socket
- import time
- import psycopg2
- from sqlalchemy import create_engine
- from sqlalchemy.orm import declarative_base
- from sqlalchemy import Column, Integer, String
- from sqlalchemy.orm import sessionmaker
- import pygame
- engine = create_engine("postgresql+psycopg2://postgres:1111@localhost/rebotica")
- Session = sessionmaker(bind=engine)
- Base = declarative_base()
- s = Session()
- # Настройка констант для pygame
- pygame.init()
- WIDHT_ROOM, HEIGHT_ROOM = 4000, 4000
- WIDHT_SERVER, HEIGHT_SERVER = 300, 300
- FPS = 100
- # Создание окна сервера
- screen = pygame.display.set_mode((WIDHT_SERVER, HEIGHT_SERVER))
- pygame.display.set_caption("Сервер")
- clock = pygame.time.Clock()
- def find(vector: str):
- first = None
- for num, sign in enumerate(vector):
- if sign == "<":
- first = num
- if sign == ">" and first is not None:
- second = num
- result = list(map(float, vector[first + 1:second].split(",")))
- return result
- return ""
- # Декларативный класс таблицы игроков
- class Player(Base):
- __tablename__ = "gamers"
- id = Column(Integer, primary_key=True, autoincrement=True)
- name = Column(String(250))
- address = Column(String)
- x = Column(Integer, default=500)
- y = Column(Integer, default=500)
- size = Column(Integer, default=50)
- errors = Column(Integer, default=0)
- abs_speed = Column(Integer, default=2)
- speed_x = Column(Integer, default=2)
- speed_y = Column(Integer, default=2)
- def __init__(self, name, address):
- self.name = name
- self.address = address
- def update(player):
- player.x += player.speed_x
- player.y += player.speed_y
- def change_speed(player, vector):
- vector = find(vector)
- if vector[0] == 0 and vector[1] == 0:
- player.speed_x = player.speed_y = 0
- else:
- vector = vector[0] * player.abs_speed, vector[1] * player.abs_speed
- player.speed_x = vector[0]
- player.speed_y = vector[1]
- Base.metadata.create_all(engine)
- main_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Настраиваем сокет
- main_socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) # Отключаем пакетирование
- main_socket.bind(("localhost", 10000)) # IP и порт привязываем к порту
- main_socket.setblocking(False) # Непрерывность, не ждём ответа
- main_socket.listen(5) # Прослушка входящих соединений, 5 одновременных подключений
- print("Сокет создался")
- players = {}
- server_works = True
- while server_works:
- clock.tick(FPS)
- try:
- # проверяем желающих войти в игру
- new_socket, addr = main_socket.accept() # принимаем входящие
- print('Подключился', addr)
- new_socket.setblocking(False)
- player = Player("Имя", addr)
- s.merge(player)
- s.commit()
- addr = f'({addr[0]},{addr[1]})'
- data = s.query(Player).filter(Player.address == addr)
- for user in data:
- players[user.id] = new_socket
- except BlockingIOError:
- pass
- # Считываем команды игроков
- for id in list(players):
- try:
- data = players[id].recv(1024).decode()
- player = s.get(Player, id)
- change_speed(player, data)
- except:
- pass
- # Отправляем статус игрового поля
- for id in list(players):
- try:
- players[id].send("Игра".encode())
- except:
- players[id].close()
- del players[id]
- # Так же удаляем строчку из БД
- s.query(Player).filter(Player.id == id).delete()
- s.commit()
- print("Сокет закрыт")
- # Отрисовываем серверное окно
- for event in pygame.event.get():
- if event.type == pygame.QUIT:
- server_works = False
- screen.fill('black')
- for id in players:
- player = s.get(Player, id)
- x = player.x * WIDHT_SERVER // WIDHT_ROOM
- y = player.y * HEIGHT_SERVER // HEIGHT_ROOM
- size = player.size * WIDHT_SERVER // WIDHT_ROOM
- pygame.draw.circle(screen, "yellow2", (x, y), size)
- for id in players:
- player = s.get(Player, id)
- update(player)
- pygame.display.update()
- pygame.quit()
- main_socket.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement