fixed snake pathfinding

This commit is contained in:
Xevion
2019-09-16 00:06:59 -05:00
parent 78b904bcf2
commit 493352a14f
6 changed files with 95 additions and 30 deletions

View File

@@ -7,12 +7,16 @@ class Node(object):
self.g, self.h, self.f = 0, 0, 0 self.g, self.h, self.f = 0, 0, 0
def __eq__(self, other): def __eq__(self, other):
assert type(other) == Node, "Can only compare equality against other Node objects" assert type(other) == Node, "Node cannot compared against type \"{}\"".format(str(type(other)))
return self.position == other.position return self.position == other.position
def __repr__(self): def __repr__(self):
return f'<Node ({self.position[0]}, {self.position[1]})>' return f'<Node ({self.position[0]}, {self.position[1]})>'
@classmethod
def positionify(self, nodes):
return [node.position for node in nodes]
# Generate a grid and return it to the user # Generate a grid and return it to the user
class SnakeGrid(object): class SnakeGrid(object):
def __init__(self, x, y, length=3): def __init__(self, x, y, length=3):
@@ -81,6 +85,7 @@ class SnakeGrid(object):
def bestPellet(self, curpos, blacklist=[]): def bestPellet(self, curpos, blacklist=[]):
potential = self.pellets() potential = self.pellets()
if blacklist: if blacklist:
print(curpos, blacklist)
potential = list(filter(lambda item : item not in blacklist, potential)) potential = list(filter(lambda item : item not in blacklist, potential))
# Returns None if no potential pellets are in due to blacklist # Returns None if no potential pellets are in due to blacklist
if not potential: if not potential:
@@ -91,15 +96,22 @@ class SnakeGrid(object):
def merge(self, pos1, pos2): def merge(self, pos1, pos2):
return [pos1[0] + pos2[0], pos1[1] + pos2[1]] return [pos1[0] + pos2[0], pos1[1] + pos2[1]]
def solution(self, maxdist=20):
path = self.generateSolutions()
for i, pos in enumerate(path):
if self.available(pos):
self.mark(pos, str(i + 1))
return path
# Generater a solution for the maz # Generater a solution for the maz
def solution(self, length=20): def generateSolutions(self, maxdist=30):
def build_path(current_node): def build_path(current_node):
path = [] path = []
current = current_node current = current_node
while current is not None: while current is not None:
path.append(current.position) path.append(current.position)
current = current.parent current = current.parent
return str(path[::-1]) return path[::-1]
# Pathfinding initial constants # Pathfinding initial constants
start_node = Node(None, self.positions[-1]) start_node = Node(None, self.positions[-1])
@@ -110,7 +122,7 @@ class SnakeGrid(object):
output = "" output = ""
while len(open_list) > 0: while len(open_list) > 0:
self.sleep(0.125) # self.sleep(0.125)
pathdist += 1 pathdist += 1
# Choose the best node to work on # Choose the best node to work on
current_index, current_node = min(enumerate(open_list), key=lambda item : item[1].f) current_index, current_node = min(enumerate(open_list), key=lambda item : item[1].f)
@@ -119,16 +131,21 @@ class SnakeGrid(object):
# Check if we've hit the maximum distance # Check if we've hit the maximum distance
if pathdist >= length: if pathdist >= maxdist:
return build_path(current_node) return build_path(current_node)
# If we've hit the "end node", but still distance to travel, setup a new one # If we've hit the "end node", but still distance to travel, setup a new one
if current_node == end_node: if current_node == end_node:
finished_end_nodes.append(end_node) finished_end_nodes.append(end_node)
end_node = self.bestPellet(blacklist=finished_end_nodes) start_node = end_node
open_list = [start_node]
closed_list.append(end_node)
end_node = position=self.bestPellet(current_node.position, blacklist=Node.positionify(finished_end_nodes))
# if we've acquired all pellets by chance # if we've acquired all pellets by chance
if end_node is None: if end_node is None:
return build_path(current_node) return build_path(current_node)
else:
end_node = Node(parent=None, position=end_node)
# Basically iterates upon all positions next to the current node dependent on the cardinal directions # Basically iterates upon all positions next to the current node dependent on the cardinal directions
for offset in self.offsets: for offset in self.offsets:
@@ -137,18 +154,16 @@ class SnakeGrid(object):
if self.inBounds(child): if self.inBounds(child):
child = Node(parent=current_node, position=child) child = Node(parent=current_node, position=child)
if child in closed_list:
continue
# Ensure not already a closed position # Ensure not already a closed position
if not child in closed_list:
child.g = current_node.g + 1 child.g = current_node.g + 1
child.h = self.distance(child.position, end_node.position) child.h = self.distance(child.position, end_node.position)
child.f = child.g + child.h child.f = child.g + child.h
# Ensure that child node is # Ensure that child node is
for open_node in open_list: if child not in open_list:
if child == open_node:
if child.g > open_node.g:
continue
open_list.append(child) open_list.append(child)
return output return output
@@ -170,7 +185,8 @@ class SnakeGrid(object):
return (self.matrix[pos[0]][pos[1]] == look) if self.inBounds(pos) else False return (self.matrix[pos[0]][pos[1]] == look) if self.inBounds(pos) else False
def __repr__(self): def __repr__(self):
return '\n'.join(' - '.join(_) for _ in self.matrix) length = max([max(len(item) for item in sub) for sub in self.matrix])
return '\n'.join(' - '.join(map(lambda item : item.ljust(length) if item != ' ' else (' ' * length), line)) for line in self.matrix)
# Driver Code # Driver Code
if __name__ == "__main__": if __name__ == "__main__":
@@ -190,10 +206,11 @@ if __name__ == "__main__":
# Build and prints matrixes # Build and prints matrixes
for x in range(iterations): for x in range(iterations):
snakegrid = SnakeGrid(size[0], size[1], 3) snakegrid = SnakeGrid(size[0], size[1], 3)
solution = snakegrid.solution()
print(dividerCustom.format(str(x+1).zfill(len(str(iterations))))) print(dividerCustom.format(str(x+1).zfill(len(str(iterations)))))
print(snakegrid) print(snakegrid)
print(dividerTotal) print(dividerTotal)
print(snakegrid.solution()) print(solution)
time.sleep(timing) time.sleep(timing)
print(dividerTotal) print(dividerTotal)

View File

@@ -446,3 +446,5 @@ This is a rather long problem, so let's split it up into parts.
Class X is a implementation of the Comparable Interface, and is essentially a method for comparing Strings when sorted. Focus on the `compareTo` method. Class X is a implementation of the Comparable Interface, and is essentially a method for comparing Strings when sorted. Focus on the `compareTo` method.
The `compareTo` method is how comparables "compare", and it returns a integer value to representation how it should be placed in the array. The array is sorted in descending order when `Collections.sort` is called on it. The `compareTo` method is how comparables "compare", and it returns a integer value to representation how it should be placed in the array. The array is sorted in descending order when `Collections.sort` is called on it.
The integer it returns is calculated based on the length first: if the two Strings have the same length, it returns the result of the two strings `compareTo` method, but if they're not the same length, it returns the difference in length of the two Strings.

View File

@@ -1,7 +1,10 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project version="4"> <project version="4">
<component name="ChangeListManager"> <component name="ChangeListManager">
<list default="true" id="5ee3d13c-335f-4b45-baa5-1d7b6e58ccd6" name="Default Changelist" comment="" /> <list default="true" id="5ee3d13c-335f-4b45-baa5-1d7b6e58ccd6" name="Default Changelist" comment="">
<change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/question26.java" beforeDir="false" afterPath="$PROJECT_DIR$/src/question26.java" afterDir="false" />
</list>
<ignored path="$PROJECT_DIR$/out/" /> <ignored path="$PROJECT_DIR$/out/" />
<option name="EXCLUDED_CONVERTED_TO_IGNORED" value="true" /> <option name="EXCLUDED_CONVERTED_TO_IGNORED" value="true" />
<option name="SHOW_DIALOG" value="false" /> <option name="SHOW_DIALOG" value="false" />
@@ -40,16 +43,35 @@
</counts> </counts>
</usages-collector> </usages-collector>
</session> </session>
<session id="-2041611852">
<usages-collector id="statistics.lifecycle.project">
<counts>
<entry key="project.open.time.0" value="1" />
<entry key="project.opened" value="1" />
</counts>
</usages-collector>
<usages-collector id="statistics.file.extensions.edit">
<counts>
<entry key="java" value="461" />
</counts>
</usages-collector>
<usages-collector id="statistics.file.types.edit">
<counts>
<entry key="JAVA" value="461" />
</counts>
</usages-collector>
</session>
</component> </component>
<component name="FileEditorManager"> <component name="FileEditorManager">
<leaf SIDE_TABS_SIZE_LIMIT_KEY="300"> <leaf SIDE_TABS_SIZE_LIMIT_KEY="300">
<file pinned="false" current-in-tab="true"> <file pinned="false" current-in-tab="true">
<entry file="file://$PROJECT_DIR$/src/question26.java"> <entry file="file://$PROJECT_DIR$/src/question26.java">
<provider selected="true" editor-type-id="text-editor"> <provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="221"> <state relative-caret-position="533">
<caret line="15" column="30" selection-start-line="15" selection-start-column="30" selection-end-line="15" selection-end-column="30" /> <caret line="42" column="62" selection-start-line="42" selection-start-column="62" selection-end-line="42" selection-end-column="62" />
<folding> <folding>
<element signature="imports" expanded="true" /> <element signature="imports" expanded="true" />
<element signature="e#435#436#0" expanded="true" />
<element signature="e#466#467#0" expanded="true" /> <element signature="e#466#467#0" expanded="true" />
</folding> </folding>
</state> </state>
@@ -65,6 +87,9 @@
</list> </list>
</option> </option>
</component> </component>
<component name="Git.Settings">
<option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$/../../.." />
</component>
<component name="GradleLocalSettings"> <component name="GradleLocalSettings">
<option name="projectSyncType"> <option name="projectSyncType">
<map> <map>
@@ -87,6 +112,9 @@
<option name="width" value="1440" /> <option name="width" value="1440" />
<option name="height" value="788" /> <option name="height" value="788" />
</component> </component>
<component name="ProjectLevelVcsManager" settingsEditedManually="true">
<ConfirmationsSetting value="2" id="Add" />
</component>
<component name="ProjectView"> <component name="ProjectView">
<navigator proportions="" version="1"> <navigator proportions="" version="1">
<foldersAlwaysOnTop value="true" /> <foldersAlwaysOnTop value="true" />
@@ -108,7 +136,7 @@
</panes> </panes>
</component> </component>
<component name="PropertiesComponent"> <component name="PropertiesComponent">
<property name="com.android.tools.idea.instantapp.provision.ProvisionBeforeRunTaskProvider.myTimeStamp" value="1568588789665" /> <property name="com.android.tools.idea.instantapp.provision.ProvisionBeforeRunTaskProvider.myTimeStamp" value="1568600612753" />
<property name="last_opened_file_path" value="$PROJECT_DIR$" /> <property name="last_opened_file_path" value="$PROJECT_DIR$" />
</component> </component>
<component name="RunDashboard"> <component name="RunDashboard">
@@ -152,8 +180,9 @@
</component> </component>
<component name="ToolWindowManager"> <component name="ToolWindowManager">
<frame x="1912" y="-8" width="1936" height="1066" extended-state="6" /> <frame x="1912" y="-8" width="1936" height="1066" extended-state="6" />
<editor active="true" />
<layout> <layout>
<window_info content_ui="combo" id="Project" order="0" visible="true" weight="0.18603411" /> <window_info content_ui="combo" id="Project" order="0" visible="true" weight="0.1881663" />
<window_info id="Structure" order="1" side_tool="true" weight="0.25" /> <window_info id="Structure" order="1" side_tool="true" weight="0.25" />
<window_info id="Image Layers" order="2" /> <window_info id="Image Layers" order="2" />
<window_info id="Designer" order="3" /> <window_info id="Designer" order="3" />
@@ -162,7 +191,7 @@
<window_info id="Favorites" order="6" side_tool="true" /> <window_info id="Favorites" order="6" side_tool="true" />
<window_info anchor="bottom" id="Message" order="0" /> <window_info anchor="bottom" id="Message" order="0" />
<window_info anchor="bottom" id="Find" order="1" /> <window_info anchor="bottom" id="Find" order="1" />
<window_info anchor="bottom" id="Run" order="2" weight="0.2306867" /> <window_info active="true" anchor="bottom" id="Run" order="2" visible="true" weight="0.2306867" />
<window_info anchor="bottom" id="Debug" order="3" weight="0.4" /> <window_info anchor="bottom" id="Debug" order="3" weight="0.4" />
<window_info anchor="bottom" id="Cvs" order="4" weight="0.25" /> <window_info anchor="bottom" id="Cvs" order="4" weight="0.25" />
<window_info anchor="bottom" id="Inspection" order="5" weight="0.4" /> <window_info anchor="bottom" id="Inspection" order="5" weight="0.4" />
@@ -170,7 +199,7 @@
<window_info anchor="bottom" id="Terminal" order="7" /> <window_info anchor="bottom" id="Terminal" order="7" />
<window_info anchor="bottom" id="Event Log" order="8" side_tool="true" /> <window_info anchor="bottom" id="Event Log" order="8" side_tool="true" />
<window_info anchor="bottom" id="Version Control" order="9" show_stripe_button="false" /> <window_info anchor="bottom" id="Version Control" order="9" show_stripe_button="false" />
<window_info anchor="bottom" id="Messages" order="10" /> <window_info anchor="bottom" id="Messages" order="10" weight="0.32939914" />
<window_info anchor="right" id="Commander" internal_type="SLIDING" order="0" type="SLIDING" weight="0.4" /> <window_info anchor="right" id="Commander" internal_type="SLIDING" order="0" type="SLIDING" weight="0.4" />
<window_info anchor="right" id="Ant Build" order="1" weight="0.25" /> <window_info anchor="right" id="Ant Build" order="1" weight="0.25" />
<window_info anchor="right" content_ui="combo" id="Hierarchy" order="2" weight="0.25" /> <window_info anchor="right" content_ui="combo" id="Hierarchy" order="2" weight="0.25" />
@@ -187,10 +216,11 @@
<component name="editorHistoryManager"> <component name="editorHistoryManager">
<entry file="file://$PROJECT_DIR$/src/question26.java"> <entry file="file://$PROJECT_DIR$/src/question26.java">
<provider selected="true" editor-type-id="text-editor"> <provider selected="true" editor-type-id="text-editor">
<state relative-caret-position="221"> <state relative-caret-position="533">
<caret line="15" column="30" selection-start-line="15" selection-start-column="30" selection-end-line="15" selection-end-column="30" /> <caret line="42" column="62" selection-start-line="42" selection-start-column="62" selection-end-line="42" selection-end-column="62" />
<folding> <folding>
<element signature="imports" expanded="true" /> <element signature="imports" expanded="true" />
<element signature="e#435#436#0" expanded="true" />
<element signature="e#466#467#0" expanded="true" /> <element signature="e#466#467#0" expanded="true" />
</folding> </folding>
</state> </state>

View File

@@ -1,5 +1,6 @@
import static java.lang.System.*; import static java.lang.System.*;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
@@ -16,6 +17,20 @@ class X implements Comparable<X> {
public String toString() { public String toString() {
return this.str; return this.str;
} }
public int[] getValues() {
int[] values = new int[this.str.length()];
for(int i = 0; i < this.str.length(); i++) {
values[i] = (int) this.str.charAt(i);
}
return values;
}
public int getSum() {
int sum = 0;
for(int val : this.getValues()) {
sum += val;
}
return sum;
}
} }
class question26 { class question26 {
@@ -26,5 +41,6 @@ class question26 {
w.add(new X(sub)); w.add(new X(sub));
Collections.sort(w); Collections.sort(w);
out.println(w); out.println(w);
out.println(Arrays.toString(new X("Hello").getValues()));
} }
} }