added old code, fixed it (mostly), merged some new code to the old code, made it mostly runnable
This commit is contained in:
85
New_Client/Classes/Engine/Components/BoardField.py
Normal file
85
New_Client/Classes/Engine/Components/BoardField.py
Normal file
@ -0,0 +1,85 @@
|
||||
import os
|
||||
import pygame
|
||||
|
||||
class BoardField(pygame.sprite.Sprite):
|
||||
__fieldID:str
|
||||
__name:str
|
||||
__side:str
|
||||
__type:str
|
||||
__pos:pygame.Vector2
|
||||
__size:tuple
|
||||
__color:tuple = (255,255,255)
|
||||
__holdsCard = None
|
||||
image:pygame.image
|
||||
rect:pygame.rect
|
||||
|
||||
def __init__(self, name:str, side:str, type:str, pos:pygame.Vector2, imagePath:str, fid:str):
|
||||
pygame.sprite.Sprite.__init__(self)
|
||||
self.__name = name
|
||||
self.__side = side
|
||||
self.__type = type
|
||||
self.__pos = pos
|
||||
self.__holdsCard = None
|
||||
self.__fieldID = fid
|
||||
|
||||
# Überprüfen des Dateipfads
|
||||
if not os.path.exists(imagePath):
|
||||
print("could not find image Location.")
|
||||
else:
|
||||
# Wenn der Pfad gültig ist, versuchen Sie, das Bild zu laden
|
||||
self.image = pygame.image.load(imagePath).convert_alpha()
|
||||
self.rect = self.image.get_rect()
|
||||
self.rect.center = self.__pos
|
||||
|
||||
def getName(self) -> str:
|
||||
return self.__name
|
||||
|
||||
def getSide(self) -> str:
|
||||
return self.__side
|
||||
|
||||
def getType(self) -> str:
|
||||
return self.__type
|
||||
|
||||
def getPos(self) -> pygame.Vector2:
|
||||
return self.__pos
|
||||
|
||||
def getSize(self) -> tuple:
|
||||
return self.__size
|
||||
|
||||
def getColor(self) -> tuple:
|
||||
return self.__color
|
||||
|
||||
def getRect(self) -> pygame.Rect:
|
||||
return self.rect
|
||||
|
||||
def getImage(self) -> pygame.image:
|
||||
return self.image
|
||||
|
||||
def getHoldingCard(self):
|
||||
return self.__holdsCard
|
||||
|
||||
def setName(self, name:str) -> str:
|
||||
self.__name = name
|
||||
return self.__name
|
||||
|
||||
def setType(self,type:str) -> str:
|
||||
self.__type = type
|
||||
return self.__type
|
||||
|
||||
def setPos(self, pos:pygame.Vector2) -> pygame.Vector2:
|
||||
self.pos = pos
|
||||
return self.__pos
|
||||
|
||||
def setSize(self, size:tuple) -> tuple:
|
||||
self.__size = size
|
||||
return self.__size
|
||||
|
||||
def setColor(self, color:tuple) -> tuple:
|
||||
self.__color = color
|
||||
return self.__color
|
||||
|
||||
def setCardHolding(self, card):
|
||||
self.__holdsCard = card
|
||||
|
||||
def getFieldID(self) -> str:
|
||||
return self.__fieldID
|
46
New_Client/Classes/Engine/Components/Label.py
Normal file
46
New_Client/Classes/Engine/Components/Label.py
Normal file
@ -0,0 +1,46 @@
|
||||
import pygame
|
||||
|
||||
class Label:
|
||||
rect:pygame.rect
|
||||
image:pygame.image
|
||||
__screen:pygame.surface
|
||||
__text:str
|
||||
__pos:pygame.Vector2
|
||||
__font:pygame.font
|
||||
font:pygame.font
|
||||
__name:str
|
||||
|
||||
def __init__(self, name:str, screen:pygame.surface, text:str, pos:pygame.Vector2, size:float=20, color:str="white"):
|
||||
self.__font = pygame.font.SysFont("Arial", size)
|
||||
self.font = pygame.font.SysFont("Arial", size)
|
||||
self.image = self.font.render(text, 1, color)
|
||||
_, _, w, h = self.image.get_rect()
|
||||
self.__pos = pos
|
||||
self.rect = pygame.Rect(self.__pos.x, self.__pos.y, w, h)
|
||||
self.__screen = screen
|
||||
self.__text = text
|
||||
|
||||
def getText(self) -> str:
|
||||
return self.__text
|
||||
|
||||
def getFont(self) -> pygame.font:
|
||||
return self.__font
|
||||
|
||||
def getPos(self) -> pygame.Vector2:
|
||||
return self.__pos
|
||||
|
||||
def getName(self) -> str:
|
||||
return self.__name
|
||||
|
||||
def setText(self, newtext:str, color:str="white"):
|
||||
self.image = self.font.render(newtext, 1, color)
|
||||
|
||||
def setFont(self, font:pygame.font, size:float, color:str="white"):
|
||||
self.__font = pygame.font.SysFont(font, size)
|
||||
self.change_text(self.text, color)
|
||||
|
||||
def setPos(self, pos:pygame.Vector2):
|
||||
self.__pos = pos
|
||||
|
||||
def draw(self):
|
||||
self.__screen.blit(self.image, (self.rect))
|
Binary file not shown.
Binary file not shown.
117
New_Client/Classes/Engine/EventHandler.py
Normal file
117
New_Client/Classes/Engine/EventHandler.py
Normal file
@ -0,0 +1,117 @@
|
||||
import socket
|
||||
|
||||
import pygame
|
||||
from Classes.Engine.Logger import Logger
|
||||
|
||||
from Classes.Game.NetworkEvents.PlaceCard import CardPlaced
|
||||
from Classes.Game.NetworkEvents.GameStart import GameStart
|
||||
from Classes.Game.NetworkEvents.PlaceCard import PlaceCard
|
||||
from Classes.Engine.InputHandler import InputHandler
|
||||
from Classes.Game.World import World
|
||||
from Classes.Game.Player import Player
|
||||
from Classes.Game.NetworkEvents.Login import LoginResponse
|
||||
|
||||
# network event handler this only handles events coming from the server
|
||||
class TCPEventHandler:
|
||||
def __init__(self, socket:socket, inputHandler:InputHandler, world:World):
|
||||
self.tcp_socket = socket
|
||||
self.__world = world
|
||||
self.__inputHandler = inputHandler
|
||||
|
||||
def handleEvents(self, message:dict):
|
||||
if message["event"] == "loginresponse":
|
||||
LoginResponse(message)
|
||||
pass
|
||||
elif message["event"] == "startgame":
|
||||
print("gamestart")
|
||||
GameStart(self.__world, message["hand"], self.__inputHandler, self.__world.getPlayer())
|
||||
pass
|
||||
elif message["event"] == "PlaceCard":
|
||||
CardPlaced(self.__world, message["card"], message["type"], message["owner"], pygame.Vector2(int(message["x"]), int(message["y"]), self.__inputHandler))
|
||||
pass
|
||||
elif message["event"] == "MoveCard":
|
||||
CardMoved(
|
||||
self.__world,
|
||||
message["card"],
|
||||
message["type"],
|
||||
message["owner"],
|
||||
pygame.Vector2(int(message["old_x"]), int(message["old_y"])),
|
||||
pygame.Vector2(int(message["new_x"]), int(message["new_y"])),
|
||||
self.__inputHandler)
|
||||
pass
|
||||
elif message["event"] == "RemoveCard":
|
||||
pass
|
||||
elif message["event"] == "AttackCard":
|
||||
pass
|
||||
elif message["event"] == "AttackPlayer":
|
||||
pass
|
||||
elif message["event"] == "ActivateEffectCard":
|
||||
pass
|
||||
elif message["event"] == "ActivateMonsterCard":
|
||||
pass
|
||||
|
||||
# handles engine events this is separate from the network event handler
|
||||
class EngineEventHandler:
|
||||
|
||||
__inputHandler:InputHandler
|
||||
__world:World
|
||||
__logger:Logger
|
||||
|
||||
def __init__(self, inputHandler:InputHandler, world:World, logger:Logger, tcpClient):
|
||||
self.__logger = logger
|
||||
self.__logger.info("initializing engine Event Handler")
|
||||
if inputHandler == None:
|
||||
raise ValueError("InputHandler was found to be None")
|
||||
|
||||
if world == None:
|
||||
raise ValueError("world was found to be None")
|
||||
|
||||
if world == tcpClient:
|
||||
raise ValueError("tcpCLient was found to be None")
|
||||
|
||||
self.__inputHandler = inputHandler
|
||||
self.__world = world
|
||||
self.__tcpClient = tcpClient
|
||||
|
||||
# handles the incoming event queue
|
||||
def handleEvent(self, events):
|
||||
# TODO: fix bug that stacks cards when dragging them around
|
||||
self.selectedCard = None
|
||||
self.mousePos = self.__inputHandler.getMousePos()
|
||||
|
||||
for event in events:
|
||||
if event.type == pygame.QUIT:
|
||||
self.onCleanup()
|
||||
elif self.__inputHandler.getMousePos()[0]:
|
||||
for card in self.__world.getCards():
|
||||
if card.rect.collidepoint(self.mousePos):
|
||||
self.__logger.info(f"dragging card {card}")
|
||||
self.selectedCard = card
|
||||
|
||||
# failsafe to prevent NoneType errors
|
||||
if self.selectedCard != None:
|
||||
self.__logger.info(f"working with card: {self.selectedCard}")
|
||||
self.selectedCard.setDragging(True)
|
||||
elif event.type == pygame.MOUSEBUTTONUP:
|
||||
if event.button == 1:
|
||||
if self.selectedCard != None:
|
||||
for field in self.__world.getBoardFields():
|
||||
if field.getRect().collidepoint(self.mousePos):
|
||||
if field.getSide() == "Player" and field.getType() == self.selectedCard.getType():
|
||||
try:
|
||||
# snap card into the correct field
|
||||
self.selectedCard.rect.center = field.rect.center
|
||||
self.selectedCard.setDragging(False)
|
||||
print(self.selectedCard)
|
||||
if self.selectedCard == card:
|
||||
# TODO: adapt this into the new game engine version
|
||||
PlaceCard(self.__tcpClient, self.selectedCard) # tells te server that the player placed this card
|
||||
self.selectedCard = None
|
||||
except Exception as e:
|
||||
print(f"failed to place card on server due to error: {e}")
|
||||
|
||||
if self.selectedCard != None:
|
||||
self.selectedCard = None
|
||||
else:
|
||||
raise ValueError("selected card in event handler was found empty this should never happen!")
|
||||
pass
|
53
New_Client/Classes/Engine/InputHandler.py
Normal file
53
New_Client/Classes/Engine/InputHandler.py
Normal file
@ -0,0 +1,53 @@
|
||||
import pygame
|
||||
|
||||
from Classes.Engine.Components.BoardField import BoardField
|
||||
|
||||
class InputHandler:
|
||||
# returns pressed key
|
||||
@staticmethod
|
||||
def getPressed():
|
||||
return pygame.key.get_pressed()
|
||||
|
||||
# returns pressed key
|
||||
@staticmethod
|
||||
def getMousePressed():
|
||||
return pygame.mouse.get_pressed()
|
||||
|
||||
# takes in movement inputs and maps them to x and y axis
|
||||
@staticmethod
|
||||
def getInputAxis() -> tuple:
|
||||
xvel = 0
|
||||
yvel = 0
|
||||
|
||||
# construct x and y velocity input axis
|
||||
if InputHandler.getPressed()[pygame.K_a] or InputHandler.getPressed()[pygame.K_LEFT]:
|
||||
xvel = -1
|
||||
if InputHandler.getPressed()[pygame.K_d] or InputHandler.getPressed()[pygame.K_RIGHT]:
|
||||
xvel = 1
|
||||
if InputHandler.getPressed()[pygame.K_w] or InputHandler.getPressed()[pygame.K_UP]:
|
||||
yvel = -1
|
||||
if InputHandler.getPressed()[pygame.K_s] or InputHandler.getPressed()[pygame.K_DOWN]:
|
||||
yvel = 1
|
||||
|
||||
return tuple((xvel, yvel))
|
||||
|
||||
@staticmethod
|
||||
def getMousePos() -> pygame.Vector2:
|
||||
return pygame.Vector2(pygame.mouse.get_pos())
|
||||
|
||||
# get field under mousbutton
|
||||
@staticmethod
|
||||
def getMouseHover(mouse_pos: pygame.Vector2, world_card_width: int, world_card_height: int, board_fields: list) -> BoardField:
|
||||
x_pos = mouse_pos.x / world_card_width
|
||||
y_pos = mouse_pos.y / world_card_height
|
||||
|
||||
for field in board_fields:
|
||||
field_x = field.getPos().x
|
||||
field_y = field.getPos().y
|
||||
field_width = world_card_width # Annahme: Jedes Feld hat eine Breite von 1 Einheit
|
||||
field_height = world_card_height # Annahme: Jedes Feld hat eine Höhe von 1 Einheit
|
||||
|
||||
if field_x <= x_pos < field_x + field_width and field_y <= y_pos < field_y + field_height:
|
||||
return field
|
||||
|
||||
return None
|
18
New_Client/Classes/Engine/Logger.py
Normal file
18
New_Client/Classes/Engine/Logger.py
Normal file
@ -0,0 +1,18 @@
|
||||
import logging
|
||||
|
||||
|
||||
class Logger:
|
||||
def __init__(self, filename):
|
||||
logging.basicConfig(filename=filename,
|
||||
filemode='a',
|
||||
format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',
|
||||
datefmt='%H:%M:%S',
|
||||
level=logging.DEBUG)
|
||||
|
||||
def info(self, message):
|
||||
print(message)
|
||||
logging.info(message)
|
||||
|
||||
def error(self, message):
|
||||
print(message)
|
||||
logging.error(message)
|
52
New_Client/Classes/Engine/TCPClient.py
Normal file
52
New_Client/Classes/Engine/TCPClient.py
Normal file
@ -0,0 +1,52 @@
|
||||
import json
|
||||
import socket
|
||||
import threading
|
||||
|
||||
from Classes.Engine.EventHandler import TCPEventHandler
|
||||
from Classes.Game.World import World
|
||||
from Classes.Engine.InputHandler import InputHandler
|
||||
|
||||
class TCPClient:
|
||||
|
||||
__running:bool
|
||||
|
||||
def __init__(self, addr: str, port: str, world:World, inputHandler:InputHandler):
|
||||
self.addr = addr
|
||||
self.port = int(port)
|
||||
self.tcpSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
self.world = world
|
||||
self.inputHandler = inputHandler
|
||||
self.eventHandler = TCPEventHandler(self.tcpSocket, self.inputHandler, self.world)
|
||||
|
||||
try:
|
||||
self.tcpSocket.connect((self.addr, self.port))
|
||||
self.__running = True
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error connecting TCP socket: {e}")
|
||||
self.__running = False
|
||||
|
||||
# Starten des Listener-Threads
|
||||
self.listen()
|
||||
|
||||
def send(self, message: dict):
|
||||
try:
|
||||
self.tcpSocket.sendall(json.dumps(message).encode())
|
||||
except Exception as e:
|
||||
print(f"Error sending TCP data: {e}")
|
||||
|
||||
def receive(self):
|
||||
while True:
|
||||
try:
|
||||
data = self.tcpSocket.recv(1024)
|
||||
if data:
|
||||
decoded_data = json.loads(data.decode())
|
||||
self.eventHandler.handleEvents(decoded_data)
|
||||
except Exception as e:
|
||||
print(f"Error receiving TCP data: {e}")
|
||||
break
|
||||
|
||||
def listen(self):
|
||||
self.tcpThread = threading.Thread(target=self.receive)
|
||||
self.tcpThread.daemon = True
|
||||
self.tcpThread.start()
|
6
New_Client/Classes/Engine/Utils/Path.py
Normal file
6
New_Client/Classes/Engine/Utils/Path.py
Normal file
@ -0,0 +1,6 @@
|
||||
import os
|
||||
|
||||
|
||||
class PathUtil:
|
||||
def getAbsolutePathTo(notAbsolutPath:str) -> str:
|
||||
return os.path.abspath("Client/" + notAbsolutPath)
|
11
New_Client/Classes/Engine/Utils/StringUtils.py
Normal file
11
New_Client/Classes/Engine/Utils/StringUtils.py
Normal file
@ -0,0 +1,11 @@
|
||||
import random
|
||||
import string
|
||||
|
||||
|
||||
class StringUtils:
|
||||
def get_random_string(length) -> str:
|
||||
# choose from all lowercase letter
|
||||
letters = string.ascii_lowercase
|
||||
result_str = ''.join(random.choice(letters) for i in range(length))
|
||||
print("Random string of length", length, "is:", result_str)
|
||||
return result_str
|
BIN
New_Client/Classes/Engine/Utils/__pycache__/Path.cpython-311.pyc
Normal file
BIN
New_Client/Classes/Engine/Utils/__pycache__/Path.cpython-311.pyc
Normal file
Binary file not shown.
Binary file not shown.
54
New_Client/Classes/Engine/Window.py
Normal file
54
New_Client/Classes/Engine/Window.py
Normal file
@ -0,0 +1,54 @@
|
||||
import pygame
|
||||
from pygame.locals import *
|
||||
|
||||
from Classes.Engine.Components.BoardField import BoardField
|
||||
from Classes.Game.World import World
|
||||
|
||||
class Window:
|
||||
__width:int = 800
|
||||
__height:int = 600 # takes 80% of width which tranlates to 640
|
||||
__title:str = "python game engine"
|
||||
__screen:pygame.Surface
|
||||
__clock:pygame.time.Clock
|
||||
|
||||
def __init__(self, width:int=800, height:int=600, title:str="python game engine"):
|
||||
self.__width = width
|
||||
self.__height = height
|
||||
self.__title = title
|
||||
|
||||
pygame.init()
|
||||
|
||||
self.__screen = pygame.display.set_mode((self.__width, self.__height))
|
||||
self.__screen.fill((236, 240, 241)) # Hier liegt der Fehler, es muss eine Tuple übergeben werden
|
||||
pygame.display.set_caption(self.__title)
|
||||
|
||||
self.__clock = pygame.time.Clock()
|
||||
self.__framerate = 60 # Framerate auf 60 FPS festlegen
|
||||
|
||||
# set framerate (where the fuck is it?)
|
||||
def Render(self):
|
||||
# dear future me figure out what past me did!
|
||||
pass
|
||||
|
||||
def setWidth(self, width:int):
|
||||
self.__width = width
|
||||
|
||||
def setHeight(self, height:int):
|
||||
self.__height = height
|
||||
|
||||
def setTitle(self, title:str):
|
||||
self.__title = title
|
||||
|
||||
def getScreen(self) -> pygame.surface:
|
||||
return self.__screen
|
||||
|
||||
# draws a passed sprite group to the screen
|
||||
def drawSpriteGroup(self, group:pygame.sprite.Group):
|
||||
group.draw(self.__screen)
|
||||
|
||||
# draws a given group of rectangles onto the screen
|
||||
def drawWorld(self, world:World):
|
||||
for field in world.getBoardFields():
|
||||
pygame.draw.rect(self.__screen, field.getColor(), field.getRect())
|
||||
for label in world.getLabels():
|
||||
label.draw()
|
Binary file not shown.
Binary file not shown.
BIN
New_Client/Classes/Engine/__pycache__/Logger.cpython-311.pyc
Normal file
BIN
New_Client/Classes/Engine/__pycache__/Logger.cpython-311.pyc
Normal file
Binary file not shown.
BIN
New_Client/Classes/Engine/__pycache__/TCPClient.cpython-311.pyc
Normal file
BIN
New_Client/Classes/Engine/__pycache__/TCPClient.cpython-311.pyc
Normal file
Binary file not shown.
BIN
New_Client/Classes/Engine/__pycache__/Window.cpython-311.pyc
Normal file
BIN
New_Client/Classes/Engine/__pycache__/Window.cpython-311.pyc
Normal file
Binary file not shown.
Reference in New Issue
Block a user