Related
Part 3 of my python programming project. Find it here.
Since the last post, I've managed to get work out the transposition tables and started creating the move ordering function.
The move function starts by checking if there's a move in the opening books, if there isn't one then it executes the move ordering function and lastly if there was no move found, it calculates the best move in the position.
This is what I have so far:
def domove(depth):
try:
move = chess.polyglot.MemoryMappedReader("C:/Users/bruno/Desktop/chess/books/pecg_book.bin").weighted_choice(board).move()
move = chess.polyglot.MemoryMappedReader("C:/Users/bruno/Desktop/chess/books/human.bin").weighted_choice(board).move()
move = chess.polyglot.MemoryMappedReader("C:/Users/bruno/Desktop/chess/books/computer.bin").weighted_choice(board).move()
movehistory.append(move)
return move
except:
orderMoves(move)
bestMove = move
movehistory.append(bestMove)
return bestMove
finally:
bestMove = chess.Move.null()
bestValue = -9999
alpha = -10000
beta = 10000
for move in board.legal_moves:
make_move(move)
boardValue = -alphabeta(-beta, -alpha, depth-1)
if boardValue > bestValue:
bestValue = boardValue
bestMove = move
if( boardValue > alpha ):
alpha = boardValue
unmake_move()
movehistory.append(bestMove)
return bestMove
The orderMoves function checks for 3 different things in the current position:
negamax function - searches the transposition tables
Moves that lead to checkmate
Captures that win material
.
def orderMoves(board, bestValue, material, move):
try:
negamax(board)
bestMove = move
movehistory.append(bestMove)
return bestMove
except:
for move in board.legal_moves:
if board.is_checkmate():
bestValue
return bestValue
finally:
for move in board.legal_moves:
if move == board.is_capture():
if newmaterial >= material:
newmaterial = material
return bestValue
The negamax function works via storing and looking up previously stored hashes.
def negamax(node, depth, alpha, beta, score, bestValue):
alphaOrig = alpha
EXACT = score
LOWERBOUND = alpha
UPPERBOUND = beta
## Transposition Table Lookup; node is the lookup key for ttEntry
ttEntry = transpositionTableLookup(node)
if ttEntry.is_valid is True :
if ttEntry.depth >= depth:
if ttEntry.flag == EXACT :
return ttEntry.value
elif ttEntry.flag == LOWERBOUND:
alpha = max(alpha, ttEntry.value)
elif ttEntry.flag == UPPERBOUND:
beta = min(beta, ttEntry.value)
if alpha >= beta:
return ttEntry.value
elif depth == 0 or node == terminal_node():
return bestValue
childNodes = domove(node)
childNodes = orderMoves(childNodes)
bestValue = -99999
for child in childNodes:
bestValue = max(bestValue, -negamax(child, depth - 1, -beta, -alpha))
alpha = max(alpha, bestValue)
if alpha >= beta:
break
##Transposition Table Store; node is the lookup key for ttEntry
ttEntry.value = bestValue
if bestValue <= alphaOrig:
ttEntry.flag = UPPERBOUND
if bestValue >= beta:
ttEntry.flag = LOWERBOUND
else:
ttEntry.flag = EXACT
ttEntry.depth = depth
transpositionTableStore(node, ttEntry)
return bestValue
There's probably a better way of implementing this function, but this was the best I could manage.
After testing this for a few hours of running the code, the results were the same as when I didn't have move ordering. 7 out of the 24 test positions were correct.
What changes could I make to get a cleaner implementation and make it work properly?
Great question.
The Andoma Python chess engine uses this move ordering function in movegeneration.py, that I've also use for my Ramses Chess engine (Python) :
def get_ordered_moves(board: chess.Board) -> List[chess.Move]:
"""
Get legal moves.
Attempt to sort moves by best to worst.
Use piece values (and positional gains/losses) to weight captures.
"""
end_game = check_end_game(board)
def orderer(move):
return move_value(board, move, end_game)
in_order = sorted(
board.legal_moves, key=orderer, reverse=(board.turn == chess.WHITE)
)
return list(in_order)
Working on the google foo-bar challenges and I am stuck on one failing test case (which is a hidden one - so I can't directly see what the problem is)
basically the test is an implementation of a maze solver with a single breakable wall.
I'm doing a modified a* search - with a Boolean flag for paths that contain a broken wall, so that when it reaches the second wall (along a path with a broken wall) it skips it for that path.
I've gone over this code and I can't seem to see the error (if there even is one - at this point I'm almost convinced the test case is somehow wrong)
the parameters:
given a grid of height x,y filled with zero or 1, representing spaces and walls respectively: find the shortest path if you can break exactly 1 wall (if needed)
an example:
[
[0,1,0,0,0,1,0,0,0,0,0]
[0,0,0,1,0,0,1,0,1,1,0]
[1,1,1,1,1,0,1,0,1,0,1]
[0,0,0,0,0,0,0,0,1,1,0]
]
22 is the shortest path breaking 1 wall.
I want a pointer in the right direction: I feel like whatever I'm missing is trivial.
below is the code.
from math import sqrt, ceil
cardinal_moves=[(0,1), (0,-1), (1,0), (-1,0)]
class Node:
def __init__(self, pos ,parent =None):
self.parent = parent
self.pos = pos
self.g = 0
self.h = 0
self.f = 0
self.wall_broken = False
def __eq__(self, other):
return ((self.pos == other.pos) and (self.wall_broken == other.wall_broken))
def update_heuristic(self,parent,end):
self.g = parent.g + 1
self.h = ceil(sqrt((end.pos[0] - self.pos[0])**2 + (end.pos[1] - self.pos[1])**2))
self.f = self.g + self.h
def not_inside_maze(pos,maze):
return pos[0] < 0 or pos[0] >= len(maze) or pos[1] < 0 or pos[1] >= len(maze[0])
def astar_with_1_breakable_wall(maze):
start_pos = (0,0)
end_pos = (len(maze)-1, len(maze[0])-1)
start = Node(start_pos)
end = Node(end_pos)
not_visted = []
visited = []
not_visted.append(start)
while not_visted:
current_node = not_visted[0]
for node in not_visted:
if current_node.f > node.f:
current_node = node
not_visted.remove(current_node)
visited.append(current_node)
if current_node.pos == end.pos:
temp = current_node
path = []
while temp:
path.append(temp.pos)
temp = temp.parent
return path[::-1]
children = []
for position in cardinal_moves:
new_pos = (current_node.pos[0] + position[0], current_node.pos[1] + position[1])
if not_inside_maze(new_pos,maze):
continue
if maze[new_pos[0]][new_pos[1]] == 1:
if current_node.wall_broken:
continue
else:
check = Node(new_pos,current_node)
check.wall_broken = True
already_visited = False
for node in visited:
if check == node:
already_visited = True
break
if not already_visited:
children.append(check)
continue
already_visited = False
check = Node(new_pos,current_node)
check.wall_broken = current_node.wall_broken
for node in visited:
if check == node:
already_visited = True
break
if already_visited:
continue
children.append(check)
for child in children:
child.update_heuristic(current_node,end)
for open_node in not_visted:
if open_node == child:
if open_node.g > child.g:
idx = not_visted.index(open_node)
not_visted[idx] = child
continue
else:
continue
not_visted.append(child)
def shortest_path(maze):
if (astar_with_1_breakable_wall(maze)):
return len(astar_with_1_breakable_wall(maze))
else:
return -1
but every check I make on my machine says this is correct:
#imports added
import sys
#then added this below the maze solver
test = [
[0,1,0,0,0,1,0,0,0,0,0],
[0,0,0,1,0,0,1,0,1,1,0],
[1,1,1,1,1,0,1,0,1,0,1],
[0,0,0,0,0,0,0,0,1,1,0],
]
test2=[
[0,1,0,0,0,0,1,0,0,0,0],
[0,1,0,1,1,0,1,0,1,0,0],
[0,0,0,1,0,0,1,0,1,0,0],
[1,1,1,1,0,1,1,0,1,0,1],
[0,0,0,0,0,0,0,0,1,0,1],
]
print("first test")
print(shortest_path(test))
print("second test")
print(shortest_path(test))
#both of these tests give the correct result
def generate_matrix(h,w,n):
sequence = "{0:b}".format(n).zfill(h*w)
maze =[]
if(sequence[0]=="1" or sequence[len(sequence)-1]=="1"):
return -1
i=0
for y in range(h):
maze.append([])
for x in range(w):
maze[y].append(int(sequence[i]))
i=i+1
return(maze)
for i in range(20):
for j in range(20):
if(i < 6 or j <6):
continue
shortest=j+i
for k in range(2**(i*j)):
if not k%2==0:
continue
if k> 2**(i*j-1):
continue
maze = generate_matrix(i,j,k)
if(not maze == -1):
path = astar_with_1_breakable_wall(maze)
res = shortest_path(maze)
if(res > shortest):
print("\n",res, "shortest was ", shortest)
for index,line in enumerate(maze):
for indx,cell in enumerate(line):
if ((index,indx) in path):
print("\033[94m"+str(cell),end="")
else:
print("\033[92m"+str(cell),end="")
print("\n")
for point in path:
print(point ," ", end="")
print("\n\n")
else:
sys.stdout.write("\r")
the above code makes every matrix possibility, and prints (with highlighting the path) the matrix if the path is longer than the base case.
every result is as I expect - returning the correct shortest path... I have not found the issue with why only the 3rd test case fails...
the answer was something specific to python 2.7.13 apparently - it took a bit of debugging to figure it out, but the not_visited.remove(current_node) was the thing that was failing in certain cases.
I am trying to write a minimax algorithm for a pacman game. I am having a problem with the recursion - sometimes my algorithm 'works' (it does not crash, but returns the wrong value still), and then sometimes it crashes and gives me a recursion error, saying max recursion depth exceeded. Can someone shed some light on what I am doing wrong here? Thank you!
def minimax(self, gamestate, depth, agent):
if depth == self.depth or gamestate.isWin() or gamestate.isLose():
return self.evaluationFunction(gamestate), Directions.STOP
best_move = None
if agent == 0: ## Pacman is max
best_val = float('-inf')
else: ## ghosties are min
best_val = float('inf')
actions = gamestate.getLegalActions(agent)
for action in actions:
next_agent = agent + 1 ## quit moving me! ## this goes here to set next_agent to be same as agent each iteration, because it also gets changed below
successor = gamestate.generateSuccessor(agent, action) ## generate successors gamestate (ie new board)
if next_agent == gamestate.getNumAgents():
next_agent = 0 ## Once we reach the last agent, set back to 0
depth += 1 ## increment depth
v = self.minimax(successor, depth, next_agent)
## here is where we set the max and min values based on the agent
if agent == 0: ## pacman - max
if v > best_val:
best_val = v
best_move = action
else: ## ghost - min
if v < best_val:
best_val = v
best_move = action
return best_move, best_val
I'm trying to do a snake game, where 2 snakes compete between each other. One snake simply follows the food, and avoids obstacles, the other, is the one, for which i'm writing the code, and is supposed to find the best way to get to the food. The food position, every bit of the map and the position of the other snake is known, and the position of the food changes, with every movement of the snakes.
If the map allows it, if there is no obstacle, the snake can traverse through the walls, to go to the other side of the map, like the map is a donut. The snake doesn't move diagonally, only vertically and horizontally, and it can't move backwards.
I'm using jump point search to find a way to the food, and it's working fine, although at 50fps some times the game slows down a bit.
The major problem i'm having, is finding a way to avoid dead ends. If the food gets in a dead end, i want to wait that it leaves the dead end, but what happens is that my snake, goes there, and then dies. Because i'm not avoiding dead ends, when my snake get's big enough, sometimes it crashes in its own body.
This is the code of the agent of my snake.
class AgentStudent(Snake, SearchDomain):
def __init__(self, body=[(0, 0)], direction=(1, 0), name="punkJD"):
super().__init__(body, direction, name=name)
self.count = 0;
#given the current state, and the next state, it returns a direction ( (1,0), (-1,0), (0,1), (0,-1) )
def dir(self, state, n_state):
if state[0] == 0 and n_state[0] == (self.mapsize[0] - 1):
return left
elif state[0] == (self.mapsize[0] - 1) and n_state[0] == 0:
return right
elif state[1] == 0 and n_state[1] == (self.mapsize[1] - 1):
return up
elif state[1] == (self.mapsize[1] - 1) and n_state == 0:
return down
return n_state[0] - state[0], n_state[1] - state[1]
#doesn't matter for the question
def update(self, points=None, mapsize=None, count=None, agent_time=None):
self.mapsize = mapsize
return None
#given current position and food position, it will create a class that will do the search. Seach code bellow
def search_food(self, pos, foodpos):
prob = SearchProblem(self, pos, foodpos, self.olddir)
my_tree = SearchTree(prob, self.mapsize, self.maze)
#doesn't matter, before i was using A*, but then i changed my whole search class
my_tree.strategy = 'A*'
return my_tree.search()
#given the current position and the direction the snake is faced it returns a list of all the possible directions the snake can take. If the current direction is still possible it will be put first in the list to be the first to be considered
def actions(self, pos, dir):
dirTemp = dir
invaliddir = [x for (x, y) in self.complement if y == dir]
validdir = [dir for dir in directions if not (dir in invaliddir)]
validdir = [dir for dir in validdir if
not (self.result(pos, dir) in self.maze.obstacles or self.result(pos, dir) in self.maze.playerpos)]
dirList = [dirTemp] if dirTemp in validdir else []
if dirList != []:
for a in range(len(validdir)):
if validdir[a] != dirTemp:
dirList.append(validdir[a])
return dirList
return validdir
#given the current position and the current direction, it returns the new position
def result(self, a, b):
n_pos = a[0] + b[0], a[1] + b[1]
if n_pos[0] == -1:
n_pos = (self.mapsize[0] - 1), a[1] + b[1]
if n_pos[1] == -1:
n_pos = a[0] + b[0], (self.mapsize[1] - 1)
if n_pos[0] == (self.mapsize[0]):
n_pos = 0, a[1] + b[1]
if n_pos[1] == (self.mapsize[1]):
n_pos = a[0] + b[0], 0
return n_pos
#given the current position and food position it returns the manhattan distance heuristic
def heuristic(self, position, foodpos):
distancex = min(abs(position[0] - foodpos[0]), self.mapsize[0] - abs(position[0] - foodpos[0]))
distancey = min(abs(position[1] - foodpos[1]), self.mapsize[1] - abs(position[1] - foodpos[1]))
return distancex + distancey
#this function is called by the main module of the game, to update the position of the snake
def updateDirection(self, maze):
# this is the brain of the snake player
self.olddir = self.direction
position = self.body[0]
self.maze = maze
# new direction can't be up if current direction is down...and so on
self.complement = [(up, down), (down, up), (right, left), (left, right)]
self.direction = self.search_food(position, self.maze.foodpos)
Bellow is the code to do the search.
I reused a file i had with some classes to do a tree search, and changed it to use jump point search. And for every jump point i find i expand a node in the tree.
class SearchDomain:
def __init__(self):
abstract
def actions(self, state):
abstract
def result(self, state, action):
abstract
def cost(self, state, action):
abstract
def heuristic(self, state, goal_state):
abstract
class SearchProblem:
def __init__(self, domain, initial, goal,dir):
self.domain = domain
self.initial = initial
self.goal = goal
self.dir = dir
def goal_test(self, state):
return state == self.goal
# class that defines the nodes in the tree. It has some attributes that are not used due to my old aproach.
class SearchNode:
def __init__(self,state,parent,heuristic,dir,cost=0,depth=0):
self.state = state
self.parent = parent
self.heuristic = heuristic
self.depth = depth
self.dir = dir
self.cost = cost
if parent!=None:
self.cost = cost + parent.cost
def __str__(self):
return "no(" + str(self.state) + "," + str(self.parent) + "," + str(self.heuristic) + ")"
def __repr__(self):
return str(self)
class SearchTree:
def __init__(self,problem, mapsize, maze, strategy='breadth'):
#attributes used to represent the map in a matrix
#represents obstacle
self.OBS = -1
#represents all the positions occupied by both snakes
self.PPOS = -2
#represents food position
self.FOODPOS = -3
#represents not explored
self.UNIN = -4
self.problem = problem
h = self.problem.domain.heuristic(self.problem.initial,self.problem.goal)
self.root = SearchNode(problem.initial, None,h,self.problem.dir)
self.open_nodes = [self.root]
self.strategy = strategy
self.blacklist = []
self.pqueue = FastPriorityQueue()
self.mapa = maze
#here i initialize the matrix to represent the map
self.field = []
for a in range(mapsize[0]):
self.field.append([])
for b in range(mapsize[1]):
self.field[a].append(self.UNIN)
for a,b in maze.obstacles:
self.field[a][b] = self.OBS
for a,b in maze.playerpos:
self.field[a][b] = self.PPOS
self.field[maze.foodpos[0]][maze.foodpos[1]] = self.FOODPOS
self.field[self.root.state[0]][self.root.state[1]] = self.UNIN
#function to add a jump point to the priority queue
def queue_jumppoint(self,node):
if node is not None:
self.pqueue.add_task(node, self.problem.domain.heuristic(node.state,self.problem.goal)+node.cost)
# given a node it returns the path until the root of the tree
def get_path(self,node):
if node.parent == None:
return [node]
path = self.get_path(node.parent)
path += [node]
return(path)
#Not used in this approach
def remove(self,node):
if node.parent != None:
a = self.problem.domain.actions(node.parent.state, node.dir)
self.blacklist+=node.state
if a == []:
self.remove(node.parent)
node = None
#Function that searches for the food
def search(self):
tempNode = self.root
self.queue_jumppoint(self.root)
count = 0
while not self.pqueue.empty():
node = self.pqueue.pop_task()
actions = self.problem.domain.actions(node.state,node.dir)
if count == 1:
tempNode = node
count+=1
#for every possible direction i call the explore function that finds a jump point in a given direction
for a in range(len(actions)):
print (a)
print (actions[a])
jumpPoint = self.explore(node,actions[a])
if jumpPoint != None:
newnode = SearchNode((jumpPoint[0],jumpPoint[1]),node,self.problem.domain.heuristic(node.state,self.problem.goal),actions[a],jumpPoint[2])
if newnode.state == self.problem.goal:
return self.get_path(newnode)[1].dir
self.queue_jumppoint(newnode)
dirTemp = tempNode.dir
return dirTemp
#Explores the given direction, starting in the position of the given node, to find a jump point
def explore(self,node,dir):
pos = node.state
cost = 0
while (self.problem.domain.result(node.state,dir)) != node.state:
pos = self.problem.domain.result(pos, dir)
cost += 1
#Marking a position as explored
if self.field[pos[0]][pos[1]] == self.UNIN or self.field[pos[0]][pos[1]] == self.PPOS:
self.field[pos[0]][pos[1]] = 20
elif pos[0] == self.problem.goal[0] and pos[1] == self.problem.goal[1]: # destination found
return pos[0],pos[1],cost
else:
return None
#if the snake is going up or down
if dir[0] == 0:
#if there is no obstacle/(or body of any snake) at the right but in the previous position there was, then this is a jump point
if (self.field [self.problem.domain.result(pos,(1,0))[0]] [pos[1]] != self.OBS and self.field [self.problem.domain.result(pos,(1,0))[0]] [self.problem.domain.result(pos,(1,-dir[1]))[1]] == self.OBS) or \
(self.field [self.problem.domain.result(pos,(1,0))[0]] [pos[1]] != self.PPOS and self.field [self.problem.domain.result(pos,(1,0))[0]] [self.problem.domain.result(pos,(1,-dir[1]))[1]] == self.PPOS):
return pos[0], pos[1],cost
#if there is no obstacle/(or body of any snake) at the left but in the previous position there was, then this is a jump point
if (self.field [self.problem.domain.result(pos,(-1,0))[0]] [pos[1]] != self.OBS and self.field [self.problem.domain.result(pos,(-1,0))[0]] [self.problem.domain.result(pos,(1,-dir[1]))[1]] == self.OBS) or \
(self.field [self.problem.domain.result(pos,(-1,0))[0]] [pos[1]] != self.PPOS and self.field [self.problem.domain.result(pos,(-1,0))[0]] [self.problem.domain.result(pos,(1,-dir[1]))[1]] == self.PPOS):
return pos[0], pos[1],cost
#if the snake is going right or left
elif dir[1] == 0:
#if there is no obstacle/(or body of any snake) at the upper part but in the previous position there was, then this is a jump point
if (self.field [pos[0]][self.problem.domain.result(pos,(1,1))[1]] != self.OBS and self.field [self.problem.domain.result(pos,(-dir[0],dir[1]))[0]] [self.problem.domain.result(pos,(1,1))[1]] == self.OBS) or \
(self.field [pos[0]][self.problem.domain.result(pos,(1,1))[1]] != self.PPOS and self.field [self.problem.domain.result(pos,(-dir[0],dir[1]))[0]] [self.problem.domain.result(pos,(1,1))[1]] == self.PPOS):
return pos[0], pos[1],cost
#if there is no obstacle/(or body of any snake) at the down part but in the previous position there was, then this is a jump point
if (self.field [pos[0]] [self.problem.domain.result(pos,(-1,-1))[1]] != self.OBS and self.field [self.problem.domain.result(pos,(-dir[0],dir[1]))[0]] [self.problem.domain.result(pos,(-1,-1))[1]] == self.OBS) or \
(self.field [pos[0]] [self.problem.domain.result(pos,(-1,-1))[1]] != self.PPOS and self.field [self.problem.domain.result(pos,(-dir[0],dir[1]))[0]] [self.problem.domain.result(pos,(-1,-1))[1]] == self.PPOS):
return pos[0], pos[1],cost
#if the food is aligned in some way with the snake head, then this is a jump point
if (pos[0] == self.mapa.foodpos[0] and node.state[0] != self.mapa.foodpos[0]) or \
(pos[1] == self.mapa.foodpos[1] and node.state[1] != self.mapa.foodpos[1]):
return pos[0], pos[1],cost
#if the food is in front of the head of the snake, right next to it, then this is a jump point
if self.field[self.problem.domain.result(pos,(dir[0],dir[1]))[0]][self.problem.domain.result(pos,(1,dir[1]))[1]] == self.FOODPOS:
return pos[0], pos[1],cost
##if an obstacle is in front of the head of the snake, right next to it, then this is a jump point
if self.field[self.problem.domain.result(pos,(dir[0],dir[1]))[0]][ self.problem.domain.result(pos,(1,dir[1]))[1]] == self.OBS:
return pos[0], pos[1],cost
return None
class FastPriorityQueue:
def __init__(self):
self.pq = [] # list of entries arranged in a heap
self.counter = 0 # unique sequence count
def add_task(self, task, priority=0):
self.counter+=1
entry = [priority, self.counter, task]
heapq.heappush(self.pq, entry)
def pop_task(self):
while self.pq:
priority, count, task = heapq.heappop(self.pq)
return task
raise KeyError('pop from an empty priority queue')
def empty(self):
return len(self.pq) == 0
This is my code. I would appreciate any help to be able to avoid dead ends.
I searched for similar problems but couldn't find any that helped me.
StackOverflow is not a coding service, so I'm not going to write your code for you, but I can most definitely tell you what steps you would need to take to solve your issue.
In your comments, you said it would be nice if you could check for dead ends before the game starts. A dead end can be classified as any point that has three or more orthogonally adjacent walls. I'm assuming you want every point leading up to a dead end that is inescapable. Here is how you would check:
Check every point starting from one corner and moving to the other, in either rows or columns, it doesn't matter. Once you reach a point that has three or more orthogonally adjacent walls, mark that point as a dead end, and go to 2.
Find the direction of the empty space next to this point (if any), and check every point in that direction. For each of those points: if it has two or more adjacent walls, mark it as a dead end. If it has only one wall, go to 3. If it has no walls, stop checking in this direction and continue with number 1.
In every direction that does not have a wall, repeat number 2.
Follow these steps until step 1 has checked every tile on the grid.
If you need a programming example, just ask for one in the comments. I didn't have time to make one, but I can make one later if needed. Also, if you need extra clarification, just ask!
I am writing the game of life in python using a Sparse Matrix. My program takes coordinates from user input and sets the cells at the chosen coordinates to be alive. I have it to where it will print the first generation, but I can't seem to figure out why it wont print any subsequent generations. Any help would be appreciated.
class SparseLifeGrid:
generations = list()
def __init__(self):
"""
"pass" just allows this to run w/o crashing.
Replace it with your own code in each method.
"""
self._mat = list()
self.col = []
self.row = []
def minRange(self):
"""
Return the minimum row & column as a tuple.
"""
for i in range(len(self.row)):
if self.row[i] < self.minRow:
self.minRow = self.row[i]
if self.col[i] < self.minCol:
self.minCol = self.col[i]
min_Range = [self.minRow,self.minCol]
return min_Range
def maxRange(self):
"""
Returns the maximum row & column as a tuple.
"""
for i in range(len(self.row)):
if self.row[i] > self.maxRow:
self.maxRow = self.row[i]
if self.col[i] > self.maxCol:
self.maxCol = self.col[i]
max_Range = [self.maxRow,self.maxCol]
return max_Range
def configure(self,coordList):
"""
Set up the initial board position.
"coordlist" is a list of coordinates to make alive.
"""
# for i in coordList:
# self.setCell(i[0],i[1])
self._mat = list()
self.coordList = coordList
for i in range(len(self.coordList)):
spot = self.coordList[i]
self.row += [spot[0]]
self.col += [spot[1]]
self._mat += [[self.row[i],self.col[i]]]
self.maxRow = self.minRow = self.row[0]
self.maxCol = self.minCol = self.col[0]
def clearCell(self,row, col):
"""
Set the cell to "dead" (False)
"""
self[row,col] = 0
def setCell(self,row, col):
"""
Set the cell to "live" (True") and if necessary, expand the
minimum or maximum range.
"""
self[row,col] = 1
def isLiveCell(self,row,col):
n = len(self.coordList)
for i in range(n):
if (self._mat[i] == [row,col]):
return True
return False
def numLiveNeighbors(self, row,col):
"""
Returns the number of live neighbors a cell has.
"""
neighbors = 0
if self.isLiveCell(row+1,col): #checks below the current cell
neighbors += 1
if self.isLiveCell(row-1,col): #checks above the current cell
neighbors += 1
if self.isLiveCell(row,col+1): #checks to the right of the current cell
neighbors += 1
if self.isLiveCell(row,col-1): #checks to the left of the current cell
neighbors += 1
if self.isLiveCell(row+1,col+1): #checks downwards diagonally to the right of the current cell
neighbors += 1
if self.isLiveCell(row+1,col-1): #checks downwards diagonally to the left of the current cell
neighbors += 1
if self.isLiveCell(row-1,col+1): #checks upwards diagonally to the right of the current cell
neighbors += 1
if self.isLiveCell(row-1,col-1): #checks upawards diagonally to the left of the current cell
neighbors += 1
return neighbors
def __getitem__(self,ndxTuple):
row = ndxTuple[0]
col = ndxTuple[1]
if(self.isLiveCell(row,col)==1):
return 1
else:
return 0
def __setitem__(self,ndxTuple, life):
"""
The possible values are only true or false:
True says alive, False for dead.
Also, check to see if this cell is outside of the maximum row and/or
column. If it is, modify the maximum row and/or maximum column.
"""
ndx = self._findPosition(ndxTuple[0],ndxTuple[1])
if ndx != None:
if life != True:
self._mat[ndx].value = life
else:
self._mat.pop[ndx]
else:
if life != True:
element = _GoLMatrixElement(ndxTuple[0],ndxTuple[1],life)
self._mat.append(element)
def _findPosition(self,row,col):
''' Does a search through the matrix when given the row&col and
returns the index of the element if found
'''
n = len(self._mat)
for i in range(n):
if (row == self._mat[i]) and (col == self._mat[i]):
return i
return None
def __str__(self):
"""
Print a column before and after the live cells
"""
s=""
maxRange=self.maxRange()
minRange=self.minRange()
for i in range(minRange[0]-1,maxRange[0]+2):
for j in range(minRange[1]-1,maxRange[1]+2):
s+=" "+str(self[i,j])
s+="\n"
return s
def getCopy(self):
"""
Return a copy of the current board object, including the max and min
values, etc.
"""
return SparseLifeGrid()
def evolve(self):
"""
Save the current state to the "generations" list.
Based on the current generation, return the next generation state.
"""
self.generations.append(self._mat)
for row in range(len(self.row)):
for col in range(len(self.col)):
if ((self[row,col] == True) and (self.numLiveNeighbors(row,col) == 2)):
self.setCell(row,col)
if ((self[row,col] == True) and (self.numLiveNeighbors(row,col) == 3)):
self.setCell(row,col)
if ((self[row,col] == True) and (self.numLiveNeighbors(row,col) < 2)):
self.clearCell(row,col)
if ((self[row,col] == True) and (self.numLiveNeighbors(row,col) > 3)):
self.clearCell(row,col)
if ((self[row,col] == False) and (self.numLiveNeighbors(row,col) == 3)):
self.setCell(row,col)
self.generations.append(self._mat)
return self._mat
def hasOccurred(self):
"""
Check whether this current state has already occured.
If not, return False. If true, return which generation number (1-10).
"""
for i in range(len(self.generations)):
if len(self.generations) > 0:
print("This is generation",len(self.generations))
return self.generations[i]
else:
print("No Generations")
return False
def __eq__(self,other):
"""
This is good method if we want to compare two sparse matrices.
You can just use "sparseMatrixA == sparseMatrixB" once this method
is working.
"""
pass
class _GoLMatrixElement:
"""
Storage class for one cell
"""
def __init__(self,row,col):
self.row = row
self.col = col
self.next = None #
# Since this node exists, this cell is now alive!
# To kill it, we just delete this node from the lists.
from SparseLifeGrid import SparseLifeGrid
import sys
def readPoints(lifeGrid):
"""
Reads the locations of life and set to the SparseMatrix
"""
print("1. Enter positions of life with row,col format (e.g., 2,3).")
print("2. Enter empty line to stop.")
life=input()
coordList=[]
while life:
points=life.split(",")
try:
coord=[int(points[0]),int(points[1])]
coordList.append(coord)
except ValueError:
print("Ignored input:" + life+ ", row, col not valid numbers")
except:
print("Unexpected error:", sys.exc_info()[0])
print("added, keep entering or enter empty line to stop.")
life=input()
print("Thanks, finished entering live cells")
lifeGrid.configure(coordList)
def main():
"""
Runs for ten generations if a stable (repeating) state is not found.
"""
lifeGrid= SparseLifeGrid()
readPoints(lifeGrid)
patterns=0
i=0
while i <10 :
"""
Evolve to the next generation
"""
lifeGrid.evolve()
print(lifeGrid)
"""
Check whether this generation is a repetition of any of the
previous states.
If yes return the previous matching generation (1-10).
"""
patterns=lifeGrid.hasOccurred()
if patterns != -1:
break
i+=1
if i==10:
print("No pattern found")
else:
print("Pattern found at: " + str(i)+ " of type: " + str(patterns))
main()
The loop only executes once because of this:
patterns=lifeGrid.hasOccurred()
if patterns != -1:
break
patterns will never equal -1 under any circumstance, since hasOccurred can only return False or a member of self.generations or None. As a result, the loop will always break in the first iteration, and no subsequent generations will be printed.
Incidentally, your hasOccurred logic is strange. if len(self.generations) equals zero, then the loop will not get executed at all, and none of your return statements will be evaluated, so the result will be None. If the length is greater than zero, then the condition within the loop is always True, so self.generations[i] is always returned in the first iteration. Perhaps you meant to do:
#changed the name from `hasOcurrence`, since that implies the method can only return True or False.
def get_last_occurrence(self):
for i in range(len(self.generations)):
#todo: somehow compare self.generations[i] to the current generation
if the generations match:
return i
#the loop ended without finding a match!
return False
Then, within main:
patterns=lifeGrid.hasOccurred()
if patterns != False:
break