Skip to content

Commit

Permalink
Merge pull request #123 from asdawej/dev-pyapi
Browse files Browse the repository at this point in the history
Fix the error resulting from autopep8
  • Loading branch information
asdawej authored Mar 10, 2024
2 parents b0a6847 + 76d228d commit e0923e1
Show file tree
Hide file tree
Showing 7 changed files with 89 additions and 118 deletions.
5 changes: 3 additions & 2 deletions CAPI/python/PyAPI/API.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,8 +104,9 @@ def GetScore(self) -> int:
return self.__logic.GetScore()

def HaveView(self, gridX: int, gridY: int) -> bool:
return self.__logic.HaveView(gridX, gridY, self.GetSelfInfo().x,
self.GetSelfInfo().y, self.GetSelfInfo().viewRange)
return self.__logic.HaveView(gridX, gridY,
self.GetSelfInfo().x, self.GetSelfInfo().y,
self.GetSelfInfo().viewRange)

def Print(self, cont: str) -> None:
pass
Expand Down
20 changes: 8 additions & 12 deletions CAPI/python/PyAPI/Communication.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,8 @@ def __init__(self, sIP: str, sPort: str):
def Move(self, time: int, angle: float, playerID: int) -> bool:
try:
with self.__mtxLimit:
if (
self.__counter >= self.__limit
or self.__counterMove >= self.__moveLimit
):
if (self.__counter >= self.__limit
or self.__counterMove >= self.__moveLimit):
return False
self.__counter += 1
self.__counterMove += 1
Expand All @@ -55,8 +53,8 @@ def SendMessage(self, toID: int, message: Union[str, bytes], playerID: int, team
return False
self.__counter += 1
sendResult: Message2Clients.BoolRes = self.__THUAI7Stub.Send(
THUAI72Proto.THUAI72ProtobufSendMsg(
playerID, toID, teamID, message, True if isinstance(message, bytes) else False)
THUAI72Proto.THUAI72ProtobufSendMsg(playerID, toID, teamID, message,
True if isinstance(message, bytes) else False)
)
except grpc.RpcError:
return False
Expand Down Expand Up @@ -136,10 +134,8 @@ def Construct(self, constructionType: THUAI7.ConstructionType, playerID: int, te
def EndAllAction(self, playerID: int, teamID: int) -> bool:
try:
with self.__mtxLimit:
if (
self.__counter >= self.__limit
or self.__counterMove >= self.__moveLimit
):
if (self.__counter >= self.__limit
or self.__counterMove >= self.__moveLimit):
return False
self.__counter += 1
self.__counterMove += 1
Expand All @@ -158,8 +154,8 @@ def SendMessage(self, toID: int, message: Union[str, bytes], playerID: int, team
return False
self.__counter += 1
sendResult: Message2Clients.BoolRes = self.__THUAI7Stub.Send(
THUAI72Proto.THUAI72ProtobufSendMsg(
playerID, toID, teamID, message, True if isinstance(message, bytes) else False)
THUAI72Proto.THUAI72ProtobufSendMsg(playerID, toID, teamID, message,
True if isinstance(message, bytes) else False)
)
except grpc.RpcError:
return False
Expand Down
14 changes: 4 additions & 10 deletions CAPI/python/PyAPI/Interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,7 @@ def GetBullets(self) -> List[THUAI7.Bullet]:
pass

@abstractmethod
def ShipGetSelfInfo(self) -> THUAI7.Ship:
pass

@abstractmethod
def TeamGetSelfInfo(self) -> THUAI7.Team:
def GetSelfInfo(self) -> Union[THUAI7.Ship, THUAI7.Team]:
pass

@abstractmethod
Expand Down Expand Up @@ -71,7 +67,7 @@ def GetScore(self) -> int:
pass

@abstractmethod
def Send(self, toPlayerID: int, message: str, binary: bool) -> bool:
def SendMessage(self, toID: int, message: Union[str, bytes]) -> bool:
pass

@abstractmethod
Expand Down Expand Up @@ -119,9 +115,7 @@ def Attack(self, angle: float) -> bool:
pass

@abstractmethod
def HaveView(
self, gridX: int, gridY: int, selfX: int, selfY: int, viewRange: int
) -> bool:
def HaveView(self, gridX: int, gridY: int, selfX: int, selfY: int, viewRange: int) -> bool:
pass

@abstractmethod
Expand Down Expand Up @@ -296,7 +290,7 @@ def Construct(self, constructionType: THUAI7.ConstructionType) -> Future[bool]:
pass

@abstractmethod
def GetSelfInfo(self) -> Union[THUAI7.Student, THUAI7.Tricker]:
def GetSelfInfo(self) -> THUAI7.Ship:
pass

@abstractmethod
Expand Down
131 changes: 56 additions & 75 deletions CAPI/python/PyAPI/logic.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@


class Logic(ILogic):
# TODO: Mismatch between logic.py & main.py
def __init__(self, playerID: int, shipType: THUAI7.ShipType, teamID: int, x: int, y: int) -> None:
self.__playerID: int = playerID
self.__teamID: int = teamID
Expand All @@ -42,7 +43,7 @@ def __init__(self, playerID: int, shipType: THUAI7.ShipType, teamID: int, x: int
self.__counterState: int = 0
self.__counterBuffer: int = 0

self.__gameState: THUAI7.GameState = THUAI7.GameState(0)
self.__gameState: THUAI7.GameState = THUAI7.GameState.NullGameState

self.__AILoop: bool = True

Expand Down Expand Up @@ -171,6 +172,13 @@ def GetMoney(self) -> int:
if self.__teamID == 1
else self.__currentState.gameInfo.redMoney)

def GetScore(self) -> int:
with self.__mtxState:
self.__logger.debug("Called GetScore")
return copy.deepcopy(self.__currentState.gameInfo.blueScore
if self.__teamID == 1
else self.__currentState.gameInfo.redScore)

def Attack(self, angle: float) -> int:
self.__logger.debug("Called Attack")
return self.__comm.Attack(angle, self.__playerID, self.__teamID)
Expand Down Expand Up @@ -226,12 +234,12 @@ def messageThread():
self.__comm.AddPlayer(self.__playerID, self.__teamID, self.__shipType, self.__x, self.__y)
self.__logger.info("Player added")

while self.__gameState != THUAI7.GameState(3):
while self.__gameState != THUAI7.GameState.GameEnd:
clientMsg = self.__comm.GetMessage2Client()
self.__logger.debug("Get message from server")
self.__gameState = Proto2THUAI7.gameStateDict[clientMsg.game_state]

if self.__gameState == THUAI7.GameState(1):
if self.__gameState == THUAI7.GameState.GameStart:
self.__logger.info("Game start!")

for obj in clientMsg.obj_message:
Expand All @@ -253,7 +261,7 @@ def messageThread():
self.__AILoop = True
self.__UnBlockAI()

elif self.__gameState == THUAI7.GameState(2):
elif self.__gameState == THUAI7.GameState.GameRunning:
# 读取玩家的GUID
self.__LoadBuffer(clientMsg)
else:
Expand Down Expand Up @@ -295,10 +303,7 @@ def LoadBuffer(self, message: Message2Clients.MessageToClient) -> None:
self.__LoadBufferCase(item)
if Setting.asynchronous():
with self.__mtxState:
self.__currentState, self.__bufferState = (
self.__bufferState,
self.__currentState,
)
self.__currentState, self.__bufferState = self.__bufferState, self.__currentState
self.__counterState = self.__counterBuffer
self.__logger.info("Update state!")
self.__freshed = True
Expand Down Expand Up @@ -328,35 +333,26 @@ def __LoadBufferCase(self, item: Message2Clients.MessageOfObj) -> None:
if item.WhichOneof("message_of_obj") == "ship_message":
if item.ship_message.team_id != self.__teamID:
if AssistFunction.HaveView(self.__bufferState.self.viewRange,
self.__bufferState.self.x,
self.__bufferState.self.y,
item.ship_message.x,
item.ship_message.y,
self.__bufferState.self.x, self.__bufferState.self.y,
item.ship_message.x, item.ship_message.y,
self.__bufferState.gameMap):
self.__bufferState.enemyShips.append(Proto2THUAI7.Protobuf2THUAI7Ship(item.ship_message))
self.__logger.debug("Load enemy ship")

elif item.WhichOneof("message_of_obj") == "bullet_message":
if AssistFunction.HaveView(
self.__bufferState.self.viewRange,
self.__bufferState.self.x,
self.__bufferState.self.y,
item.bullet_message.x,
item.bullet_message.y,
self.__bufferState.gameMap,
):
self.__bufferState.bullets.append(
Proto2THUAI7.Protobuf2THUAI7Bullet(item.bullet_message)
)
if AssistFunction.HaveView(self.__bufferState.self.viewRange,
self.__bufferState.self.x, self.__bufferState.self.y,
item.bullet_message.x, item.bullet_message.y,
self.__bufferState.gameMap):
self.__bufferState.bullets.append(Proto2THUAI7.Protobuf2THUAI7Bullet(item.bullet_message))
self.__logger.debug("Add Bullet!")

elif item.WhichOneof("message_of_obj") == "factory_message":
if AssistFunction.HaveView(self.__bufferState.self.viewRange, self.__bufferState.self.x,
self.__bufferState.self.y, item.factory_message.x, item.factory_message.y, self.__bufferState.gameMap):
pos = (
AssistFunction.GridToCell(
item.factory_message.x), AssistFunction.GridToCell(
item.factory_message.y))
self.__bufferState.self.y, item.factory_message.x, item.factory_message.y,
self.__bufferState.gameMap):
pos = (AssistFunction.GridToCell(item.factory_message.x),
AssistFunction.GridToCell(item.factory_message.y))
if pos not in self.__bufferState.mapInfo.factoryState:
self.__bufferState.mapInfo.factoryState[pos] = item.factory_message.hp
self.__logger.debug("New Factory")
Expand All @@ -365,18 +361,12 @@ def __LoadBufferCase(self, item: Message2Clients.MessageOfObj) -> None:
self.__logger.debug("Update Factory")

elif item.WhichOneof("message_of_obj") == "community_message":
if AssistFunction.HaveView(
self.__bufferState.self.viewRange,
self.__bufferState.self.x,
self.__bufferState.self.y,
item.community_message.x,
item.community_message.y,
self.__bufferState.gameMap,
):
pos = (
AssistFunction.GridToCell(
item.community_message.x), AssistFunction.GridToCell(
item.community_message.y))
if AssistFunction.HaveView(self.__bufferState.self.viewRange,
self.__bufferState.self.x, self.__bufferState.self.y,
item.community_message.x, item.community_message.y,
self.__bufferState.gameMap):
pos = (AssistFunction.GridToCell(item.community_message.x),
AssistFunction.GridToCell(item.community_message.y))
if pos not in self.__bufferState.mapInfo.communityState:
self.__bufferState.mapInfo.communityState[pos] = item.community_message.hp
self.__logger.debug("New Community")
Expand All @@ -385,9 +375,12 @@ def __LoadBufferCase(self, item: Message2Clients.MessageOfObj) -> None:
self.__logger.debug("Update Community")

elif item.WhichOneof("message_of_obj") == "fort_message":
if AssistFunction.HaveView(self.__bufferState.self.viewRange, self.__bufferState.self.x,
self.__bufferState.self.y, item.fort_message.x, item.fort_message.y, self.__bufferState.gameMap):
pos = (AssistFunction.GridToCell(item.fort_message.x), AssistFunction.GridToCell(item.fort_message.y))
if AssistFunction.HaveView(self.__bufferState.self.viewRange,
self.__bufferState.self.x, self.__bufferState.self.y,
item.fort_message.x, item.fort_message.y,
self.__bufferState.gameMap):
pos = (AssistFunction.GridToCell(item.fort_message.x),
AssistFunction.GridToCell(item.fort_message.y))
if pos not in self.__bufferState.mapInfo.fortState:
self.__bufferState.mapInfo.fortState[pos] = item.fort_message.hp
self.__logger.debug("New Fort")
Expand All @@ -396,41 +389,38 @@ def __LoadBufferCase(self, item: Message2Clients.MessageOfObj) -> None:
self.__logger.debug("Update Fort")

elif item.WhichOneof("message_of_obj") == "wormhole_message":
pos = (
AssistFunction.GridToCell(
item.wormhole_message.x), AssistFunction.GridToCell(
item.wormhole_message.y))
pos = (AssistFunction.GridToCell(item.wormhole_message.x),
AssistFunction.GridToCell(item.wormhole_message.y))
self.__bufferState.mapInfo.wormholeState[pos] = item.wormhole_message.hp
self.__logger.debug("Update Wormhole")

elif item.WhichOneof("message_of_obj") == "home_message":
if AssistFunction.HaveView(self.__bufferState.self.viewRange, self.__bufferState.self.x,
self.__bufferState.self.y, item.home_message.x, item.home_message.y, self.__bufferState.gameMap):
pos = (AssistFunction.GridToCell(item.home_message.x), AssistFunction.GridToCell(item.home_message.y))
if AssistFunction.HaveView(self.__bufferState.self.viewRange,
self.__bufferState.self.x, self.__bufferState.self.y,
item.home_message.x, item.home_message.y,
self.__bufferState.gameMap):
pos = (AssistFunction.GridToCell(item.home_message.x),
AssistFunction.GridToCell(item.home_message.y))
self.__bufferState.mapInfo.homeState[pos] = item.home_message.hp
self.__logger.debug("Update Home")

elif item.WhichOneof("message_of_obj") == "resource_message":
if AssistFunction.HaveView(self.__bufferState.self.viewRange, self.__bufferState.self.x,
self.__bufferState.self.y, item.resource_message.x, item.resource_message.y, self.__bufferState.gameMap):
pos = (
AssistFunction.GridToCell(
item.resource_message.x), AssistFunction.GridToCell(
item.resource_message.y))
if AssistFunction.HaveView(self.__bufferState.self.viewRange,
self.__bufferState.self.x, self.__bufferState.self.y,
item.resource_message.x, item.resource_message.y,
self.__bufferState.gameMap):
pos = (AssistFunction.GridToCell(item.resource_message.x),
AssistFunction.GridToCell(item.resource_message.y))
self.__bufferState.mapInfo.resourceState[pos] = item.resource_message.progress
self.__logger.debug("Update Resource")

elif item.WhichOneof("message_of_obj") == "news_message":
if item.news_message.to_id == self.__playerID:
if item.news_message.WhichOneof("news") == "text_message":
self.__messageQueue.put(
(item.news_message.from_id, item.news_message.text_message)
)
self.__messageQueue.put((item.news_message.from_id, item.news_message.text_message))
self.__logger.debug("Add News!")
elif item.news_message.WhichOneof("news") == "binary_message":
self.__messageQueue.put(
(item.news_message.from_id, item.news_message.binary_message)
)
self.__messageQueue.put((item.news_message.from_id, item.news_message.binary_message))
self.__logger.debug("Add News!")
else:
self.__logger.error("Unknown News!")
Expand Down Expand Up @@ -465,10 +455,7 @@ def __Update(self) -> None:
with self.__cvBuffer:
self.__cvBuffer.wait_for(lambda: self.__bufferUpdated)
with self.__mtxState:
self.__bufferState, self.__currentState = (
self.__currentState,
self.__bufferState,
)
self.__bufferState, self.__currentState = self.__currentState, self.__bufferState
self.__counterState = self.__counterBuffer
self.__bufferUpdated = False
self.__logger.info("Update state!")
Expand Down Expand Up @@ -499,13 +486,9 @@ def Main(
# os.path.realpath(__file__))) + "/logs")

if platform.system().lower() == "windows":
os.system(
f'mkdir "{os.path.dirname(os.path.dirname(os.path.realpath(__file__)))}\\logs"'
)
os.system(f'mkdir "{os.path.dirname(os.path.dirname(os.path.realpath(__file__)))}\\logs"')
else:
os.system(
f'mkdir -p "{os.path.dirname(os.path.dirname(os.path.realpath(__file__)))}/logs"'
)
os.system(f'mkdir -p "{os.path.dirname(os.path.dirname(os.path.realpath(__file__)))}/logs"')

fileHandler = logging.FileHandler(
os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
Expand Down Expand Up @@ -565,9 +548,7 @@ def AIThread():
self.__timer.EndTimer()

if self.__TryConnection():
self.__logger.info(
"Connect to the server successfully, AI thread will be started."
)
self.__logger.info("Connect to the server successfully, AI thread will be started.")
self.__threadAI = threading.Thread(target=AIThread)
self.__threadAI.start()
self.__ProcessMessage()
Expand Down
19 changes: 10 additions & 9 deletions CAPI/python/PyAPI/main.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
import PyAPI.structures as THUAI7
import platform
import argparse
from typing import List, Callable
from PyAPI.logic import Logic
from PyAPI.AI import AI
from PyAPI.Interface import IAI
import argparse
import platform
import os
import sys

sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + "/proto")

import PyAPI.structures as THUAI7 # NOQA: E402
from PyAPI.logic import Logic # NOQA: E402
from PyAPI.AI import AI # NOQA: E402
from PyAPI.Interface import IAI # NOQA: E402


def PrintWelcomeString() -> None:
# Generated by http://www.network-science.de/ascii/ with font "standard"
Expand Down Expand Up @@ -92,11 +93,11 @@ def THUAI7Main(argv: List[str], AIBuilder: Callable) -> None:
file = args.file
screen = args.screen
warnOnly = args.warnOnly
playerType = THUAI7.PlayerType(0)
playerType = THUAI7.PlayerType.NullPlayerType
if pID == 4:
playerType = THUAI7.PlayerType(1)
playerType = THUAI7.PlayerType.Ship
else:
playerType = THUAI7.PlayerType(2)
playerType = THUAI7.PlayerType.Team

if platform.system().lower() == "windows":
PrintWelcomeString()
Expand Down
Loading

0 comments on commit e0923e1

Please sign in to comment.