Init - fix Randaustausch richtung, Adding Pause

This commit is contained in:
qvalentin 2022-03-27 18:11:51 +02:00
parent 1bca8c3c89
commit 50dca30a57
Signed by: qvalentin
GPG Key ID: C979FA1EAFCABF1C
8 changed files with 61 additions and 24 deletions

View File

@ -10,10 +10,14 @@ class APIRequests:
def connectToMember(self, own_process: Member, ip, port, direction: Direction) -> Member:
body = asdict(own_process)
response = requests.post(f"http://{ip}:{port}/connect/{direction.name}", json=body)
response = requests.post(f"http://{ip}:{port}/connect/{direction.name}", json=body,allow_redirects=True)
jsonValue = response.json()
return Member(jsonValue["ip"], jsonValue["port"])
def get_edge(self, target: Member, direction: Direction):
response = requests.get(f"http://{target.ip}:{target.port}/border/{direction.name}")
return response.json()
def toggle_pause(self, neighbour: Member, new_state: bool):
action = "start" if new_state else "stop"
response = requests.post(f"http://{neighbour.ip}:{neighbour.port}/pause/{action}")

View File

@ -3,6 +3,10 @@ from enum import Enum
class Direction(Enum):
LEFT = 1
RIGHT = 2
TOP = 3
BOTTOM = 4
RIGHT = -1
TOP = 2
BOTTOM = -2
def mirror(direction: Direction):
return Direction(direction.value * -1)

View File

@ -1,5 +1,5 @@
from Code.Communication.APIRequests import APIRequests
from Code.Communication.Direction import Direction
from Code.Communication.Direction import Direction, mirror
from Code.Communication.Member import Member
from Code.Config import GeneralConfig
@ -13,7 +13,7 @@ class Neighbours:
def connect(self, direction, ip, port):
print(f"connecting to {ip}:{port} on {direction} side")
new_neighbour = self.api.connectToMember(self.own_process, ip, port, direction)
new_neighbour = self.api.connectToMember(self.own_process, ip, port, mirror(direction))
self.neighbours[direction] = new_neighbour
def accept_connection(self, direction: Direction, ip, port) -> tuple[Member, bool]:
@ -27,6 +27,11 @@ class Neighbours:
def get_edge(self, direction: Direction):
if direction in self.neighbours:
return self.api.get_edge(self.neighbours[direction], direction)
return self.api.get_edge(self.neighbours[direction], mirror(direction))
elif direction == Direction.RIGHT or direction.LEFT:
return [False] * GeneralConfig.fields_amount_y
def toggle_pause(self,new_state:bool):
for neighbour in self.neighbours.values():
self.api.toggle_pause(neighbour,new_state)

View File

@ -1,12 +1,10 @@
import json
import re
import socketserver
from dataclasses import asdict
from http.server import BaseHTTPRequestHandler, HTTPServer
from http.server import BaseHTTPRequestHandler
from Code.Communication.Direction import Direction
from Code.Communication.Neighbours import Neighbours
from Code.UI.Field import Field
from Code.UI.PlayingField import GameState
@ -30,7 +28,6 @@ class RequestHandler(BaseHTTPRequestHandler):
def handle(self) -> None:
super().handle()
"""
/connect/right
/connect/left
@ -42,9 +39,11 @@ class RequestHandler(BaseHTTPRequestHandler):
if self.path.startswith("/connect/"):
direction = re.findall("/connect/(left|right)", self.path, flags=re.IGNORECASE)[0]
data_string = self.rfile.read(int(self.headers['Content-Length']))
print(f"Got conenction request with value {data_string}")
print(f"Got connection request with value {data_string}")
data = json.loads(data_string)
neighbour, accepted = self.neighbours.accept_connection(Direction[direction.upper()], data["ip"], data["port"])
neighbour, accepted = self.neighbours.accept_connection(Direction[direction.upper()],
data["ip"],
data["port"])
print(f"Sending neighbour: {neighbour}")
if accepted:
@ -57,5 +56,17 @@ class RequestHandler(BaseHTTPRequestHandler):
self.send_header('Location', f"http://{neighbour.ip}:{neighbour.port}")
self.end_headers()
self.end_headers()
elif self.path.startswith("/pause/"):
new_state = re.findall("/pause/(stop|start)", self.path, flags=re.IGNORECASE)[0] == "start"
print(f"pause endpoint {new_state} old state")
if new_state == self.game_state.pause_for_input:
self.send_response(200)
self.end_headers()
else:
self.send_response(200)
self.end_headers()
self.game_state.pause_for_input = new_state
self.neighbours.toggle_pause(new_state)
self.end_headers()

View File

@ -1,5 +1,7 @@
import math
import pygame
class Colors:
ORANGE = (255, 140, 0)
@ -9,6 +11,11 @@ class Colors:
WHITE = (255, 255, 255)
GREY = (84, 84, 84)
class Fonts:
pygame.init()
monospace_20 = pygame.font.SysFont("monospace", 20)
monospace_80 = pygame.font.SysFont("monospace", 80)
class SquareConfig:
width = 10

View File

@ -17,8 +17,6 @@ if __name__ == "__main__":
- ip
- port
- direction
"""
args = sys.argv

View File

@ -1,5 +1,3 @@
import math
from Code.Communication.Direction import Direction
from Code.Config import GeneralConfig, SquareConfig
from Code.UI import Square
@ -8,8 +6,8 @@ from Code.UI.Square import Square
class Field:
def __init__(self):
self.width = GeneralConfig.fields_amount_x+2
self.height = GeneralConfig.fields_amount_y+2
self.width = GeneralConfig.fields_amount_x + 2
self.height = GeneralConfig.fields_amount_y + 2
self.field_shift = -10
self.squares = self._creat_squares()
@ -64,12 +62,12 @@ class Field:
def fill_ghost_edge(self, value: list):
edge_fn = {Direction.LEFT: self.fill_left_ghost_edge, Direction.RIGHT: self.fill_right_ghost_edge,
Direction.TOP: self.fill_top_ghost_edge, Direction.BOTTOM: self.fill_bottom_ghost_edge}
Direction.TOP: self.fill_top_ghost_edge, Direction.BOTTOM: self.fill_bottom_ghost_edge}
edge_fn(value)
def fill_right_ghost_edge(self, value: list):
#if len(value)== self.square.
# if len(value)== self.square.
for i in range(len(value)):
self.squares[len(self.squares[0]) - 1][i].active = value[i]
@ -77,8 +75,8 @@ class Field:
for i in range(len(value)):
self.squares[0][i].active = value[i]
def fill_top_ghost_edge(self,value):
def fill_top_ghost_edge(self, value):
pass
def fill_bottom_ghost_edge(self,value):
def fill_bottom_ghost_edge(self, value):
pass

View File

@ -2,6 +2,7 @@ import pygame as pygame
from Code.Communication.Direction import Direction
from Code.Communication.Neighbours import Neighbours
from Code.Config import Fonts
from Code.Config import GeneralConfig, Colors
from Code.GameLogic.Rules import Rules
from Code.UI.Field import Field
@ -24,6 +25,7 @@ class GameState:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
self.pause_for_input = not self.pause_for_input
self.neighbours.toggle_pause(self.pause_for_input)
def update_field_with_input(self, event):
for line in self.field.squares:
@ -38,16 +40,24 @@ class GameState:
def redraw_field(self, window):
window.fill(Colors.BLACK)
self.field.draw_squares(window)
if not self.pause_for_input:
label_font = Fonts.monospace_80
label = label_font.render("Pause", 1, Colors.ORANGE)
window.blit(label, (100, 100))
def update_borders(self):
self.field.fill_right_ghost_edge(self.neighbours.get_edge(Direction.RIGHT))
self.field.fill_left_ghost_edge(self.neighbours.get_edge(Direction.LEFT))
def run_game(game_state: GameState):
pygame.init()
pygame.display.set_caption(GeneralConfig.window_caption)
window = pygame.display.set_mode((GeneralConfig.width, GeneralConfig.height))
clock = pygame.time.Clock()
time_elapsed_since_last_action = 0
while game_state.run:
game_state.event_handler()