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: def connectToMember(self, own_process: Member, ip, port, direction: Direction) -> Member:
body = asdict(own_process) 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() jsonValue = response.json()
return Member(jsonValue["ip"], jsonValue["port"]) return Member(jsonValue["ip"], jsonValue["port"])
def get_edge(self, target: Member, direction: Direction): def get_edge(self, target: Member, direction: Direction):
response = requests.get(f"http://{target.ip}:{target.port}/border/{direction.name}") response = requests.get(f"http://{target.ip}:{target.port}/border/{direction.name}")
return response.json() 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): class Direction(Enum):
LEFT = 1 LEFT = 1
RIGHT = 2 RIGHT = -1
TOP = 3 TOP = 2
BOTTOM = 4 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.APIRequests import APIRequests
from Code.Communication.Direction import Direction from Code.Communication.Direction import Direction, mirror
from Code.Communication.Member import Member from Code.Communication.Member import Member
from Code.Config import GeneralConfig from Code.Config import GeneralConfig
@ -13,7 +13,7 @@ class Neighbours:
def connect(self, direction, ip, port): def connect(self, direction, ip, port):
print(f"connecting to {ip}:{port} on {direction} side") 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 self.neighbours[direction] = new_neighbour
def accept_connection(self, direction: Direction, ip, port) -> tuple[Member, bool]: def accept_connection(self, direction: Direction, ip, port) -> tuple[Member, bool]:
@ -27,6 +27,11 @@ class Neighbours:
def get_edge(self, direction: Direction): def get_edge(self, direction: Direction):
if direction in self.neighbours: 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: elif direction == Direction.RIGHT or direction.LEFT:
return [False] * GeneralConfig.fields_amount_y 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 json
import re import re
import socketserver
from dataclasses import asdict from dataclasses import asdict
from http.server import BaseHTTPRequestHandler, HTTPServer from http.server import BaseHTTPRequestHandler
from Code.Communication.Direction import Direction from Code.Communication.Direction import Direction
from Code.Communication.Neighbours import Neighbours from Code.Communication.Neighbours import Neighbours
from Code.UI.Field import Field
from Code.UI.PlayingField import GameState from Code.UI.PlayingField import GameState
@ -30,7 +28,6 @@ class RequestHandler(BaseHTTPRequestHandler):
def handle(self) -> None: def handle(self) -> None:
super().handle() super().handle()
""" """
/connect/right /connect/right
/connect/left /connect/left
@ -42,9 +39,11 @@ class RequestHandler(BaseHTTPRequestHandler):
if self.path.startswith("/connect/"): if self.path.startswith("/connect/"):
direction = re.findall("/connect/(left|right)", self.path, flags=re.IGNORECASE)[0] direction = re.findall("/connect/(left|right)", self.path, flags=re.IGNORECASE)[0]
data_string = self.rfile.read(int(self.headers['Content-Length'])) 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) 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}") print(f"Sending neighbour: {neighbour}")
if accepted: if accepted:
@ -57,5 +56,17 @@ class RequestHandler(BaseHTTPRequestHandler):
self.send_header('Location', f"http://{neighbour.ip}:{neighbour.port}") self.send_header('Location', f"http://{neighbour.ip}:{neighbour.port}")
self.end_headers() 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 math
import pygame
class Colors: class Colors:
ORANGE = (255, 140, 0) ORANGE = (255, 140, 0)
@ -9,6 +11,11 @@ class Colors:
WHITE = (255, 255, 255) WHITE = (255, 255, 255)
GREY = (84, 84, 84) GREY = (84, 84, 84)
class Fonts:
pygame.init()
monospace_20 = pygame.font.SysFont("monospace", 20)
monospace_80 = pygame.font.SysFont("monospace", 80)
class SquareConfig: class SquareConfig:
width = 10 width = 10

View File

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

View File

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

View File

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