This commit is contained in:
Waylon Walker 2023-06-13 13:41:56 -05:00
parent 7cce3940fc
commit 6676011ec6
2 changed files with 29 additions and 16 deletions

View file

@ -2,6 +2,7 @@ from contextlib import contextmanager
from fastapi import APIRouter, Depends, WebSocket, WebSocketDisconnect
from fastapi.responses import HTMLResponse
from rich.console import Console
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlmodel import Session
@ -9,7 +10,7 @@ from websockets.exceptions import ConnectionClosed
from learn_sql_model.api.websocket_connection_manager import manager
from learn_sql_model.config import get_config, get_session
from learn_sql_model.models.hero import Hero, HeroUpdate, Heros
from learn_sql_model.models.hero import HeroUpdate, Heros
web_socket_router = APIRouter()
@ -100,12 +101,18 @@ async def websocket_endpoint_hero_echo(
):
config = get_config()
await websocket.accept()
try:
with config.database.engine.connect() as con:
while True:
with db_session(config.database_url) as db:
heros = Heros(heros=db.query(Hero).all())
# heros = Heros.list(session=session)
data = await websocket.receive_text()
hero = HeroUpdate.parse_raw(data)
heros = con.execute("SELECT * FROM hero").fetchall()
heros = Heros.parse_obj({"heros": heros})
hero.update(session=session)
Console().print(heros)
await websocket.send_text(heros.json())
except WebSocketDisconnect:
print("disconnected")
except ConnectionClosed:

View file

@ -25,6 +25,9 @@ my_font = pygame.font.SysFont("Comic Sans MS", 30)
config = get_config()
console = Console()
console.quiet = True
class Client:
def __init__(self, name, secret_name):
@ -71,19 +74,19 @@ class Client:
connect()
return self._ws_update
@property
def others(self):
raw_heros = self.ws.recv()
return Heros.parse_raw(raw_heros)
def run(self):
while self.running:
console.print("running")
console.print("handle_events")
self.handle_events()
console.print("update")
self.update()
console.print("render")
self.render()
self.clock.tick(60)
time = self.clock.tick(60)
self.ticks += 1
Console().print("not running, quitting")
console.print(f"time: {time}")
console.print(f"ticks: {self.ticks}")
self.quit()
def quit(self):
@ -100,19 +103,22 @@ class Client:
self.hero.x += speed
# if self.ticks % 1 == 0:
console.print("updating")
update = HeroUpdate(**self.hero.dict(exclude_unset=True))
self.ws_update.send(update.json())
console.print(update)
self.ws.send(update.json())
console.print("sent")
def render(self):
# Console().print(self.hero)
self.screen.fill((0, 0, 0))
raw_heros = self.ws.recv()
console.print(raw_heros)
others = Heros.parse_raw(raw_heros)
Console().print(others)
for other in others.heros:
Console().print(f"drawing {other.name}")
pygame.draw.circle(self.screen, (255, 0, 0), (other.x, other.y), other.size)
self.screen.blit(
my_font.render(other.name, False, (255, 255, 255), 1),