positional letter mapping snake game

This commit is contained in:
Xevion
2019-09-17 00:16:39 -05:00
parent 493352a14f
commit 6a166e3fca
3 changed files with 44 additions and 28 deletions

View File

@@ -3,7 +3,6 @@ import math, time, random
class Node(object): class Node(object):
def __init__(self, parent=None, position=None): def __init__(self, parent=None, position=None):
self.parent, self.position = parent, position self.parent, self.position = parent, position
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):
@@ -21,7 +20,9 @@ class Node(object):
class SnakeGrid(object): class SnakeGrid(object):
def __init__(self, x, y, length=3): def __init__(self, x, y, length=3):
self.x, self.y, self.length, self.sleepTime = x, y, length, 0.0 self.x, self.y, self.length, self.sleepTime = x, y, length, 0.0
# Right, Down, Up, Left
self.offsets = [[0, 1], [1, 0], [-1, 0], [0, -1]] self.offsets = [[0, 1], [1, 0], [-1, 0], [0, -1]]
self.offsetLetters = list("RDUL")
self.generate() self.generate()
def sleep(self, seconds): def sleep(self, seconds):
@@ -85,7 +86,6 @@ 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:
@@ -96,29 +96,42 @@ 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): def solution(self, maxdist=20, startpos=None):
path = self.generateSolutions() pelletCount, path = self.generateSolutions(maxdist=maxdist, startpos=startpos)
for i, pos in enumerate(path): for i, pos in enumerate(path):
if self.available(pos): if self.available(pos):
self.mark(pos, str(i + 1)) self.mark(pos, str(i))
return path return pelletCount, self.mapPositions(path)
def mapPositions(self, positions):
letters = []
curpos = positions.pop(0)
while len(positions) > 0:
nextpos = positions.pop(0)
offset = [nextpos[0] - curpos[0], nextpos[1] - curpos[1]]
letters.append(offset)
curpos = nextpos
letters = list(map(lambda item : self.offsetLetters[self.offsets.index(item)], letters))
return ''.join(letters)
# Generater a solution for the maz # Generater a solution for the maz
def generateSolutions(self, maxdist=30): def generateSolutions(self, maxdist=20, startpos=None):
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 path[::-1] return (pelletCount, path[::-1])
# Pathfinding initial constants # Pathfinding initial constants
start_node = Node(None, self.positions[-1]) start_node = Node(None, self.positions[-1])
end_node = Node(None, self.bestPellet(start_node.position)) end_node = Node(None, startpos or self.bestPellet(start_node.position))
open_list, closed_list = [start_node], [] open_list = [start_node]
closed_list = [Node(position=pos) for pos in self.pellets(char='X')]
finished_end_nodes = [] finished_end_nodes = []
pathdist = 0 pathdist = 0
pelletCount = 1
output = "" output = ""
while len(open_list) > 0: while len(open_list) > 0:
@@ -141,6 +154,7 @@ class SnakeGrid(object):
open_list = [start_node] open_list = [start_node]
closed_list.append(end_node) closed_list.append(end_node)
end_node = position=self.bestPellet(current_node.position, blacklist=Node.positionify(finished_end_nodes)) end_node = position=self.bestPellet(current_node.position, blacklist=Node.positionify(finished_end_nodes))
pelletCount += 1
# 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)
@@ -166,14 +180,14 @@ class SnakeGrid(object):
if child not in open_list: if child not in open_list:
open_list.append(child) open_list.append(child)
return output
# Quick method for getting a position with the offsets provided # Quick method for getting a position with the offsets provided
def getPos(self, xoffset=0, yoffset=0): def getPos(self, xoffset=0, yoffset=0):
return [random.randint(1, self.x + xoffset), random.randint(1, self.y + yoffset)] return [random.randint(1, self.x + xoffset), random.randint(1, self.y + yoffset)]
# Quick method for marking a postiion # Quick method for marking a postiion
def mark(self, pos, marker='X'): def mark(self, pos, marker='X'):
if self.matrix[pos[0]][pos[1]] != ' ':
print(f'Overwritten {self.matrix[pos[0][pos[1]]]} with \'{marker}\'')
self.matrix[pos[0]][pos[1]] = marker self.matrix[pos[0]][pos[1]] = marker
# Mechansim for determining whether a position is in the boundaries of the matrix # Mechansim for determining whether a position is in the boundaries of the matrix
@@ -206,17 +220,20 @@ 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) for position in snakegrid.pellets():
pelletCount, solution = snakegrid.solution(startpos=position)
print(f'{solution} - {pelletCount}')
print(dividerTotal) print(dividerTotal)
print(solution) print(snakegrid)
time.sleep(timing)
# snakegrid.sleep(timing)
print(dividerTotal) print(dividerTotal)
# Finish and print timing statistics # Finish and print timing statistics
t2 = time.time() t2 = time.time()
print(f'Processing Time : {roundTime(t2 - t1 - (timing * iterations) - snakegrid.sleepTime)}') print(f'Processing Time : {roundTime(t2 - t1 - snakegrid.sleepTime)}')
print(f'Artificial Time : {roundTime((timing * iterations) + snakegrid.sleepTime)}') print(f'Artificial Time : {roundTime(snakegrid.sleepTime)}')
print(f'Total Time : {roundTime(t2 - t1)}') print(f'Total Time : {roundTime(t2 - t1)}')
print(dividerTotal) print(dividerTotal)

View File

View File

@@ -2,8 +2,7 @@
<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$/../../october-2013/3/input-generator/main.py" beforeDir="false" afterPath="$PROJECT_DIR$/../../october-2013/3/input-generator/main.py" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/question26.java" beforeDir="false" afterPath="$PROJECT_DIR$/src/question26.java" afterDir="false" />
</list> </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" />
@@ -68,7 +67,7 @@
<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="533"> <state relative-caret-position="533">
<caret line="42" column="62" selection-start-line="42" selection-start-column="62" selection-end-line="42" selection-end-column="62" /> <caret line="43" column="62" selection-start-line="43" selection-start-column="62" selection-end-line="43" 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#435#436#0" expanded="true" />
@@ -107,10 +106,10 @@
</option> </option>
</component> </component>
<component name="ProjectFrameBounds" extendedState="6"> <component name="ProjectFrameBounds" extendedState="6">
<option name="x" value="1978" /> <option name="x" value="-8" />
<option name="y" value="119" /> <option name="y" value="-8" />
<option name="width" value="1440" /> <option name="width" value="1936" />
<option name="height" value="788" /> <option name="height" value="1066" />
</component> </component>
<component name="ProjectLevelVcsManager" settingsEditedManually="true"> <component name="ProjectLevelVcsManager" settingsEditedManually="true">
<ConfirmationsSetting value="2" id="Add" /> <ConfirmationsSetting value="2" id="Add" />
@@ -136,7 +135,7 @@
</panes> </panes>
</component> </component>
<component name="PropertiesComponent"> <component name="PropertiesComponent">
<property name="com.android.tools.idea.instantapp.provision.ProvisionBeforeRunTaskProvider.myTimeStamp" value="1568600612753" /> <property name="com.android.tools.idea.instantapp.provision.ProvisionBeforeRunTaskProvider.myTimeStamp" value="1568696222928" />
<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">
@@ -179,7 +178,7 @@
<servers /> <servers />
</component> </component>
<component name="ToolWindowManager"> <component name="ToolWindowManager">
<frame x="1912" y="-8" width="1936" height="1066" extended-state="6" /> <frame x="-8" y="-8" width="1936" height="1066" extended-state="6" />
<editor active="true" /> <editor active="true" />
<layout> <layout>
<window_info content_ui="combo" id="Project" order="0" visible="true" weight="0.1881663" /> <window_info content_ui="combo" id="Project" order="0" visible="true" weight="0.1881663" />
@@ -217,7 +216,7 @@
<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="533"> <state relative-caret-position="533">
<caret line="42" column="62" selection-start-line="42" selection-start-column="62" selection-end-line="42" selection-end-column="62" /> <caret line="43" column="62" selection-start-line="43" selection-start-column="62" selection-end-line="43" 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#435#436#0" expanded="true" />