started region networking for pathfinding and such

This commit is contained in:
Joa Frehner 2023-11-14 16:32:07 +01:00
parent 2a90bfaaad
commit 5c23804b71
6 changed files with 437 additions and 24 deletions

View File

@ -225,3 +225,43 @@ func setPresent(tile):
func _load_worldmap(): func _load_worldmap():
get_tree().change_scene('res://Worldmap.tscn') get_tree().change_scene('res://Worldmap.tscn')
func requestTiles(unit = null):
rpc_id(1, 'requestTiles', unit)
signal receiveTiles
func receiveTiles(bundledTileStuff):
var newTileRect = bundledTileStuff[0]
var newTiles = bundledTileStuff[1]
var newSuperTiles = bundledTileStuff[2]
emit_signal("receiveTiles", newTileRect, newTiles, newSuperTiles)
func requestUnits():
rpc_id(1, 'requestUnits')
signal receiveUnits
func receiveUnits(newBoardUnits):
var boardUnits = newBoardUnits
for child in $TileMap/Units.get_children():
child.queue_free()
var boardUnitsIndex = 0
for unit in boardUnits:
var newUnit
if unit.superUnit:
newUnit = (load("res://SuperUnit.tscn")).instance()
else:
newUnit = (load("res://Unit.tscn")).instance()
newUnit.boardUnitsIndex = boardUnitsIndex
$TileMap/Units.add_child(newUnit)
newUnit.on_ready()
boardUnitsIndex +=1
emit_signal("receiveUnits", newBoardUnits)

View File

@ -1,18 +1,382 @@
extends Node2D extends Node2D
# Declare member variables here. Examples: var tiles = []
# var a = 2
# var b = "text" var superTiles=[]
var ownedBy = ""
var tileRect = Vector2(7,7)
var animationInProgress = false
var selectedNode
var selectedUnit
var selectedFaction
var boardUnits ={}
var occupiedTiles=[]
var enemyOccupiedTiles=[]
var route
var routeVertices
var hoveredCoords
func _ready():#this mostly just builds a bunch of stuff
yield(get_tree().create_timer(0.01), "timeout")
buildWorld()
func buildWorld():
requestTiles()
requestUnits()
$TileMap.buildTileMap(tiles)
func requestTiles(unit = null):
rpc_id(1, 'requestTiles', unit, self)
func receiveTiles(newTileRect, newTiles, newSuperTiles):
tileRect = tileRect
tiles = newTiles
superTiles = newSuperTiles
func requestUnits():
rpc_id(1, 'requestUnits', self)
func receiveUnits(newBoardUnits):
boardUnits = newBoardUnits
for child in $TileMap/Units.get_children():
child.queue_free()
var boardUnitsIndex = 0
for unit in boardUnits:
var newUnit
if unit.superUnit:
newUnit = (load("res://SuperUnit.tscn")).instance()
else:
newUnit = (load("res://Unit.tscn")).instance()
newUnit.boardUnitsIndex = boardUnitsIndex
$TileMap/Units.add_child(newUnit)
newUnit.on_ready()
boardUnitsIndex +=1
func unitSelectedMethod(unit):#this is called when a unit is selected
if unit == null:
clearPathingInfo()
$moveapcost.text = ""
$unitapcounter.text = ""
selectedFaction = null
else:
selectedNode = unit
selectedUnit = boardUnits[unit.boardUnitsIndex]
requestTiles(selectedUnit)
selectedFaction = selectedUnit.faction
for unit in boardUnits:
if unit.id != selectedUnit.id:
unit.isSelected = false
$TileMap/LineManager.drawAdvancedLine([],[],0,0)
# getOccupiedTiles(selectedUnit)
func _input(event):#this responds to any input. Has various functions depending on input
# print("region ",boardUnits)
# print("server ",server.boardUnits)
if selectedUnit != null:
if event is InputEventMouseButton and Input.is_action_just_released("left_click"):
if !selectedUnit.superUnit:
clickPath()
else:
clickSuperPath()
if event is InputEventMouseMotion:
if true:
hoveredCoords = event.position
if !selectedUnit.superUnit:
hoverPath()
else:
hoverSuperPath()
if event is InputEvent and Input.is_action_just_released("ui_accept"):
if animationInProgress == false:
nextRound()
if event is InputEvent and Input.is_action_just_released("ui_right"):
print("reset pathing")
resetPathing()
func clickPath():#this finalizes the selected path while calculating ap and new ap and shortening the path if ap is insufficient. Then it calls to execute the path
if animationInProgress == false and route.size() >1:
var totalApCost = addUpArray(routeVertices)
if totalApCost > selectedUnit.moveAp:
var apDebt = totalApCost - selectedUnit.moveAp
if apDebt > selectedUnit.ap:
while addUpArray(routeVertices) > selectedUnit.ap + selectedUnit.moveAp:
route.pop_back()
routeVertices.pop_back()
while route.size() != 0 and occupiedTiles.has(route[-1]):#prevents overlap
route.pop_back()
routeVertices.pop_back()
if route.size() > 1:
executePath(route, routeVertices)
func hoverPath(coord = hoveredCoords):#this gets the hovered tile and tells the pathfinding to make the path and tells the line to draw the returned path
if selectedUnit !=null and coord != null:
coord = $ground.world_to_map(hoveredCoords)
coord.x=clamp(coord.x,0,tileRect.x-1)
coord.y=clamp(coord.y,0,tileRect.y-1)
if animationInProgress == false:# and occupiedTiles.has(coord) == false: #might be buggy
clearPathingInfo()
$unitapcounter.text = str("Unit Faction: ", selectedUnit.faction ,"\n Total AP: ", selectedUnit.moveAp + selectedUnit.ap, "\nUnit Movement AP: ", selectedUnit.moveAp, " Unit Universal AP: ", selectedUnit.ap)
if occupiedTiles.has(coord) == false:
var path=findPath(selectedUnit.coords,coord)
if path != null :#and selectedUnit.unitCurrentPosition != path[0][-1]: #might be buggy
$moveapcost.text = str("AP Cost: ",addUpArray(path[1]))
$TileMap.get_node("LineManager").drawAdvancedLine(path[0], routeVertices, selectedUnit.ap, selectedUnit.moveAp)
func nextRound():#this sends a nextRound signal to units on the board and refreshes their ap.
resetPathing()
rpc_id(1, 'nextRound')
func executePath(route, vertices):#this takes the current selected route and tells the unit to execute it/ follow the selected route.
rpc_id(1, 'moveUnit', route, selectedUnit.id)
var convertedRoute = []
for coords in route:
convertedRoute.append($ground.map_to_world(coords))
selectedNode.moveOnPath(convertedRoute)
animationInProgress = true
clearPathingInfo()
# Called when the node enters the scene tree for the first time. func clearPathingInfo():#this erases the Dijkstra/pathfinding-specific tile info for when a new tile is selected and new pathfinding info is needed.
func _ready(): for column in tiles:
PlayerManager.subMenuOpen = false for tile in column:
print(DataManager.selectedTile) tile.verticeExplored = false
pass # Replace with function body. tile.route = []
tile.shortestKnownPath = INF
tile.vertices = []
for column in superTiles:
for tile in column:
tile.verticeExplored = false
tile.route = []
tile.shortestKnownPath = INF
tile.vertices = []
pass
# Called every frame. 'delta' is the elapsed time since the previous frame. func setDistance(target, origin, index, diagonal = false):#this sets the distances to the connections between tiles.
#func _process(delta): if not diagonal:
# pass match target.type:
"grass":
origin.verticeDistance[index] = 5
"road":
origin.verticeDistance[index] = 2
"mountain":
origin.verticeDistance[index] = INF
"enemyOccupied":
origin.verticeDistance[index] = INF
else:
match target.type:
"grass":
origin.verticeDistance[index] = 8
"road":
origin.verticeDistance[index] = 3
"mountain":
origin.verticeDistance[index] = INF
"enemyOccupied":
origin.verticeDistance[index] = INF
func findPath(start, end):#this actually finds the path. returns an array that at [0] contains the route and at [1] contains the distances of each step on the route (vertices).
var startingTile = tiles[start.x][start.y]
var endTile = tiles[end.x][end.y]
startingTile.vertices = [0]
var smallestVerticeDistance
var a = [1]
for number in a:
var currentTile = null #Unerkundedte Tile mit dem kurzesten Weg finden. Ohne jegliche Erkundung sollte es die Starting Tile sein
var smallestVertice = [INF]
for columns in tiles:
for tile in columns:
if tile.route.size() == 0:
tile.route.append(startingTile.coords)
if tile.vertices == null:
print("\n ERROR Some vertices are null \n")
break
if tile.verticeExplored == false and tile.vertices.size() > 0:
smallestVerticeDistance = addUpArray(smallestVertice)
var tileTotalVertice = 0
tileTotalVertice = addUpArray(tile.vertices)
if tileTotalVertice < smallestVerticeDistance:
smallestVertice = tile.vertices
currentTile = tile# Hier wird die neue currentTile gesetzt. DIe neue CurrenTile ist die mit dem kleinsten zusammengerechneten Vertices/ dem kurzesten Pfad
if currentTile == null:
animationInProgress = false
break
if currentTile == endTile:
route=endTile.route
routeVertices=endTile.vertices
return[endTile.route, endTile.vertices]
var translation = null
var direction = 0
for entry in currentTile.verticeDistance:
match direction:
0:
if entry != INF:
translation = Vector2(0,1)
1:
if entry != INF:
translation = Vector2(1,1)
2:
if entry != INF:
translation = Vector2(1,0)
3:
if entry != INF:
translation = Vector2(1,-1)
4:
if entry != INF:
translation = Vector2(0,-1)
5:
if entry != INF:
translation = Vector2(-1,-1)
6:
if entry != INF:
translation = Vector2(-1,0)
7:
if entry != INF:
translation = Vector2(-1,1)
if translation != null:
var tileToModify = tiles[(currentTile.coords + translation).x][(currentTile.coords + translation).y]
if addUpArray(currentTile.vertices) + currentTile.verticeDistance[direction] < addUpArray(tileToModify.vertices) or tileToModify.vertices.size() == 0:
# print("Shorter Path found.")
var newShortestPath = currentTile.duplicate().vertices.duplicate()
var newnewShortestPath = newShortestPath.append(currentTile.duplicate().verticeDistance.duplicate()[direction])
tileToModify.vertices = newShortestPath.duplicate()
var newShortestRoute = currentTile.duplicate().route.duplicate()
var newnewShortestRoute = newShortestRoute.append(tileToModify.coords) #this is really bodged but i dont know how to fix it and it somehow works fine despite everything
tileToModify.route = newShortestRoute
direction += 1
tiles[currentTile.coords.x][currentTile.coords.y]= currentTile
currentTile.verticeExplored = true
a.append(1)
func addUpArray(array):#adds up each int in an array. useful for calculating total distance.
var total = 0
for number in array:
total += number
return(total)
func _on_pathAnimationCompleted():#this gets a signal from the selected unit and tells the program that the movement is over by setting animationInProgress to false. starting an animation for example requires this to be false (so no two can be started at once).
requestTiles()
requestUnits()
resetPathing()
print(boardUnits)
animationInProgress = false
selectedUnit = null
func resetPathing():#this clears the current route and removes the line. Without it weird bugs can happen where It can do a path that it already did again.
route = []
routeVertices = []
if selectedUnit != null:
$TileMap/LineManager.drawAdvancedLine(route, routeVertices, selectedUnit.ap, selectedUnit.moveAp)
else:
$TileMap/LineManager.drawAdvancedLine(route, routeVertices, 0, 0)
func findSuperPath(start,end):
var startingTile = superTiles[start.x][start.y]
var endTile = superTiles[end.x][end.y]
startingTile.vertices = [0]
var smallestVerticeDistance
var a = [1]
for number in a:
var currentTile = null #Unerkundedte Tile mit dem kurzesten Weg finden. Ohne jegliche Erkundung sollte es die Starting Tile sein
var smallestVertice = [INF]
for columns in superTiles:
for tile in columns:
if tile.route.size() == 0:
tile.route.append(startingTile.coords)
if tile.vertices == null:
print("\n ERROR Some vertices are null \n")
break
if tile.verticeExplored == false and tile.vertices.size() > 0:
smallestVerticeDistance = addUpArray(smallestVertice)
var tileTotalVertice = 0
tileTotalVertice = addUpArray(tile.vertices)
if tileTotalVertice < smallestVerticeDistance:
smallestVertice = tile.vertices
currentTile = tile# Hier wird die neue currentTile gesetzt. DIe neue CurrenTile ist die mit dem kleinsten zusammengerechneten Vertices/ dem kurzesten Pfad
if currentTile == null:
animationInProgress = false
break
if currentTile == endTile:
route=endTile.route
routeVertices=endTile.vertices
return[endTile.route, endTile.vertices]
var translation = null
var direction = 0
for entry in currentTile.verticeDistance:
match direction:
0:
if entry != INF:
translation = Vector2(0,1)
1:
if entry != INF:
translation = Vector2(1,1)
2:
if entry != INF:
translation = Vector2(1,0)
3:
if entry != INF:
translation = Vector2(1,-1)
4:
if entry != INF:
translation = Vector2(0,-1)
5:
if entry != INF:
translation = Vector2(-1,-1)
6:
if entry != INF:
translation = Vector2(-1,0)
7:
if entry != INF:
translation = Vector2(-1,1)
if translation != null:
var tileToModify = superTiles[(currentTile.coords + translation).x][(currentTile.coords + translation).y]
if addUpArray(currentTile.vertices) + currentTile.verticeDistance[direction] < addUpArray(tileToModify.vertices) or tileToModify.vertices.size() == 0:
# print("Shorter Path found.")
var newShortestPath = currentTile.duplicate().vertices.duplicate()
var newnewShortestPath = newShortestPath.append(currentTile.duplicate().verticeDistance.duplicate()[direction])
tileToModify.vertices = newShortestPath.duplicate()
var newShortestRoute = currentTile.duplicate().route.duplicate()
var newnewShortestRoute = newShortestRoute.append(tileToModify.coords) #this is really bodged but i dont know how to fix it and it somehow works fine despite everything
tileToModify.route = newShortestRoute
direction += 1
superTiles[currentTile.coords.x][currentTile.coords.y]= currentTile
currentTile.verticeExplored = true
a.append(1)
func hoverSuperPath(coord = hoveredCoords):
coord = $ground.world_to_map(hoveredCoords+Vector2(-32,-32))
coord.x=clamp(coord.x,0,tileRect.x-2)
coord.y=clamp(coord.y,0,tileRect.y-2)
if animationInProgress == false:# and occupiedTiles.has(coord) == false: #might be buggy
clearPathingInfo()
$unitapcounter.text = str("Unit Faction: ", selectedUnit.faction ,"\n Total AP: ", selectedUnit.moveAp + selectedUnit.ap, "\nUnit Movement AP: ", selectedUnit.moveAp, " Unit Universal AP: ", selectedUnit.ap)
if occupiedTiles.has(coord) == false and occupiedTiles.has(coord+Vector2(1,0)) == false and occupiedTiles.has(coord+Vector2(0,1)) == false and occupiedTiles.has(coord+Vector2(1,1)) == false:
var path=findSuperPath(selectedUnit.coords,coord)
if path != null :#and selectedUnit.unitCurrentPosition != path[0][-1]: #might be buggy
$moveapcost.text = str("AP Cost: ",addUpArray(path[1]))
$TileMap/LineManager.drawAdvancedSuperLine(path[0], path[1], selectedUnit.ap, selectedUnit.moveAp)
func clickSuperPath():
if animationInProgress == false and route.size() >1:
var totalApCost = addUpArray(routeVertices)
if totalApCost > selectedUnit.moveAp:
var apDebt = totalApCost - selectedUnit.moveAp
if apDebt > selectedUnit.ap:
# print("Not enough AP for this move.")
while addUpArray(routeVertices) > selectedUnit.ap + selectedUnit.moveAp:
route.pop_back()
routeVertices.pop_back()
while route.size() != 0 and (occupiedTiles.has(route[-1]) == true or occupiedTiles.has(route[-1]+Vector2(1,0)) == true or occupiedTiles.has(route[-1]+Vector2(0,1)) == true or occupiedTiles.has(route[-1]+Vector2(1,1)) == true):#prevents overlap
route.pop_back()
routeVertices.pop_back()
if route.size() != 0 and route[0] != route[-1]:
totalApCost = addUpArray(routeVertices)
apDebt = totalApCost - selectedUnit.moveAp
if route.size() > 1:
executeSuperPath(route, routeVertices)
func executeSuperPath(route, vertices):#this takes the current selected route and tells the unit to execute it/ follow the selected route.
rpc_id(1, 'moveUnit', route, selectedUnit.id)
var convertedRoute = []
for coords in route:
convertedRoute.append($ground.map_to_world(coords))
selectedNode.moveOnPath(convertedRoute)
animationInProgress = true
clearPathingInfo()

View File

@ -122,9 +122,6 @@ margin_left = 1228.0
margin_top = -6.0 margin_top = -6.0
margin_right = 1914.0 margin_right = 1914.0
margin_bottom = 1016.0 margin_bottom = 1016.0
__meta__ = {
"_edit_use_anchors_": false
}
[node name="RegionUI" parent="Container" instance=ExtResource( 8 )] [node name="RegionUI" parent="Container" instance=ExtResource( 8 )]

View File

@ -199,3 +199,14 @@ remote func settle(tile, army, ascending): #if ascending, the cheapest ressource
var finish = buildingtime / 1.5 + ['turn'] var finish = buildingtime / 1.5 + ['turn']
else: else:
var finish = buildingtime + ['turn'] var finish = buildingtime + ['turn']
var regions = {}
func _ready():
var newRegion = load("res://region/Region.gd")
regions["123"] = newRegion
func requestTiles(unit,regionId = 123):
rpc_id(1, 'requestTiles',regions["123"].requestTiles())
func requestUnits(regionId = 123):
rpc_id(1, 'requestUnits', regions["123"].requestUnits())

View File

@ -50,11 +50,9 @@ func buildWorld():
superTiles = buildSuperTiles(tiles) superTiles = buildSuperTiles(tiles)
func nextRound():#this sends a nextRound signal to units on the board and refreshes their ap. func nextRound():#this sends a nextRound signal to units on the board and refreshes their ap.
print("next turn")
for unit in boardUnits: for unit in boardUnits:
unit.moveAp = unit.maxMoveAp unit.moveAp = unit.maxMoveAp
unit.ap = unit.maxAp unit.ap = unit.maxAp
print(unit.ap)
func buildTiles(x,y):#this creates the tiles array and adds all the tile-dictionaries. Also sets ground-type. func buildTiles(x,y):#this creates the tiles array and adds all the tile-dictionaries. Also sets ground-type.
var tilesToReturn = [] var tilesToReturn = []
@ -338,8 +336,11 @@ func addEnemyOccupiedTilesToMap(enemyOccupiedTiles):#this creates the tiles arra
mapTiles[tile.x][tile.y].type = "enemyOccupied" mapTiles[tile.x][tile.y].type = "enemyOccupied"
return mapTiles return mapTiles
func getTiles(unit):
if unit == null or !unit.superUnit: func requestTiles(unit, clientID):
return setVertices(addEnemyOccupiedTilesToMap(getOccupiedTiles(unit)[1])) var newTiles = setVertices(addEnemyOccupiedTilesToMap(getOccupiedTiles(unit)[1]))
else: var newSuperTiles = buildSuperTiles(setVertices(addEnemyOccupiedTilesToMap(getOccupiedTiles(unit)[1])))
return buildSuperTiles(setVertices(addEnemyOccupiedTilesToMap(getOccupiedTiles(unit)[1]))) return [tileRect, newTiles, newSuperTiles]
func requestUnits(clientID):
return boardUnits