Make Robot Walk Path in Python [duplicate] - python

This question already has answers here:
List of lists changes reflected across sublists unexpectedly
(17 answers)
Closed 5 years ago.
So this problem was given as an end of the class quiz. I didnt have time to test it out so I tried re-writting it and testing. However for some reason its not working the way I want it and I dont know why.
So you've got a nxn grid given as lists. A robot with an initial starting point given as a tuple. And the path the robot will travel given as "N", "S", "E", "W" within a list.
so input would be something like
make_grid(starting_point, path, size_of_grid)
make_grid((0,0),["S","E","S","S"],4)
with an output like
[".","_","_","_"],[".",".","_","_"],["_",".""_""_"],["_",".""_""_"]
where the "." is the robots starting point and traveled path. The "_" are the untraveled areas of the grid. And if it hits the border it stays in the exact same spot.
My problem is the result is that it marks the whole column as a traveled path with a period
def check(coord ,size):
if ((coord<0) or (coord>size)):
return True
else:
return False
def make_grid(start, path, size):
n = 0
row = []
while (n < size):
row.append("_")
n += 1
n = 1
grid = [row]
while ( n < size):
grid.append(row)
n +=1
x = start[0]
y = start[1]
grid[x][y] = "."
n = 0
while (n < len(path)):
if (path[n] == "N"):
x -= 1
if (check(x,size)):
x += 1
elif (path[n] == "E"):
y += 1
if (check(y,size)):
y -= 1
elif (path[n] == "S"):
x +=1
if (check(x,size)):
x -=1
elif (path[n] == "W"):
y -=1
if (check(y,size)):
y += 1
grid[x][y] = "."
n += 1
n = 0
while (n < size):
print grid[n]
n += 1

Your initialization of each row in grid is setting each row to the same list. So any change to an element in grid will change every row (since they are all the same list). You need to set each element of grid to a separate object. Something like:
grid = []
for i in range(size):
grid.append([])
for j in range(size):
grid[i].append('_')
I'm sure a more experienced Python programmer can come up with a more compact initialization.

Related

Can't get out of While loop(Python 3.9)

I'm a new at programming, I like solving this euler questions and I know there are solutions for this problem but it's not about the problem at all actually.
So, i managed to create a working function for finding example: 33. triangular number. It works but i couldn't manage to properly desing my while loop. I wanted to make it like, it starts from first triangular checks it's divisors make list of it's divisors, checks the length of the divisors, because problem wants "What is the value of the first triangle number to have over five hundred divisors?" . But i never managed to work the while loop. Thank you for reading.
nums = [1]
triangles = [1]
divisors = []
def triangularcreator(x):
if x == 1:
return 1
n = 1
sum = 0
while n!=0:
n += 1
nums.append(n)
for i in range(len(nums)):
sum += nums[i]
triangles.append(sum)
sum = 0
if x == len(triangles):
n = 0
return triangles[-1]
counter = 1
while True:
for i in range(1, triangularcreator(counter) + 1):
if triangularcreator(counter) % i == 0:
divisors.append(i)
if len(divisors) == 500:
print(triangularcreator(counter))
break
counter +=1
divisors.clear()
You should try to change a few things, starting with calculating just once the value of triangularcreator(counter) and assigning this value to a variable that you can use in different points of your code.
Second, you create a loop which will be calculate always triangularcreator(1). At the end of each iteration you increase the value of counter+=1, but then at the beginign of the new iteration you assignt it again value 1, so it will not progress as you expect. Try this few things:
counter = 1
while True:
triangle = triangularcreator(counter)
for i in range(1, triangle + 1):
if triangle % i == 0:
divisors.append(i)
if len(divisors) == 500:
print(triangle )
break
counter +=1
Also these two arrays nums = [1], triangles = [1] should be declared and initialized inside the def triangularcreator. Otherwise you would be appending elements in each iteration
Edit: I believe it is better to give you my own answer to the problem, since you are doing some expensive operations which will make code to run for a long time. Try this solution:
import numpy as np
factor_num = 0
n = 0
def factors(n):
cnt = 0
# You dont need to iterate through all the numbers from 1 to n
# Just to the sqrt, and multiply by two.
for i in range(1,int(np.sqrt(n)+1)):
if n % i == 0:
cnt += 1
# If n is perfect square, it will exist a middle number
if (np.sqrt(n)).is_integer():
return (cnt*2)-1
else:
return (cnt*2)-1
while factor_num < 500:
# Here you generate the triangle, by summing all elements from 1 to n
triangle = sum(list(range(n)))
# Here you calculate the number of factors of the triangle
factor_num = factors(triangle)
n += 1
print(triangle)
Turns out that both of your while loop are infinite either in triangularcreatorin the other while loop:
nums = [1]
triangles = [1]
divisors = []
def triangularcreator(x):
if x == 1:
return 1
n = 1
sum = 0
while n:
n += 1
nums.append(n)
for i in range(len(nums)):
sum += nums[i]
triangles.append(sum)
sum = 0
if len(triangles) >= x:
return triangles[-1]
return triangles[-1]
counter = 1
while True:
check = triangularcreator(counter)
for i in range(1, check + 1):
if check % i == 0:
divisors.append(i)
if len(divisors) >= 500:
tr = triangularcreator(counter)
print(tr)
break
counter +=1
Solution
Disclaimer: This is not my solution but is #TamoghnaChowdhury, as it seems the most clean one in the web. I wanted to solve it my self but really run out of time today!
import math
def count_factors(num):
# One and itself are included now
count = 2
for i in range(2, int(math.sqrt(num)) + 1):
if num % i == 0:
count += 2
return count
def triangle_number(num):
return (num * (num + 1) // 2)
def divisors_of_triangle_number(num):
if num % 2 == 0:
return count_factors(num // 2) * count_factors(num + 1)
else:
return count_factors((num + 1) // 2) * count_factors(num)
def factors_greater_than_triangular_number(n):
x = n
while divisors_of_triangle_number(x) <= n:
x += 1
return triangle_number(x)
print('The answer is', factors_greater_than_triangular_number(500))

Function to find winning line with NxN board and M pieces in a row in Python 3

I am trying to create a function that finds if a move is winning on an NxN board where the winning condition is M pieces in a row in Python 3.
I am pretty new to programming and in my specific case I am creating a Gomoku game (15x15 board with 5 pieces in a row to win). To get it working I created 6 for loops to check vertical, horizontal and 4 diagonals. See the code below for examples on the 2 options for left to right digonals. This takes way too long though when I need to loop through it many times (8) for computer to find if I can win or if it has a winning move.
end_row = 15
for j in range(11):
end_row -= 1
counter = 0
for i in range(end_row):
if board[i+j][i] == board[i+1+j][i+1] and board[i+j][i] != ' ':
counter += 1
if counter == 4:
winning_line = [(i+j-3, i-3), (i+j-2, i-2), (i+j-1, i-1), (i+j, i), (i+1+j, i+1)]
winner = True
break
else:
counter = 0
# Top left to bottom right, lower side
end_row = 15
for j in range(11):
end_row -= 1
counter = 0
for i in range(end_row):
if board[i][i+j] == board[i+1][i+1+j] and board[i][i+j] != ' ':
counter += 1
if counter == 4:
winning_line = [(i-3, i+j-3), (i-2, i+j-2), (i-1, i+j-1), (i, i+j), (i+1, i+1+j)]
winner = True
break
else:
counter = 0
# What I want to do instead, where x and y are coordinates of last move:
# Horizontal
counter = 0
for i = x - (n - 1) to x + (n - 1):
if board[i][y] == board[x][y] :
counter++
else :
counter = 0
if counter == n:
return true
The problem with the lower part of the code is that if I place a piece on e.g. position (0, 0) the program will complain when trying to reach board[-4][0] in the first looping. I will have to place lots of if statements when I get close to the edge, which is not an elegant solution.
I thought of making a 3*15 x 3*15 board instead, where the actual board is the inner 15x15 part and the rest just contains placeholders:
15x15 || 15x15 || 15x15
15x15 || board || 15x15
15x15 || 15x15 || 15x15
This to avoid getting outside of my list of lists when looping through. Not an elegant solution either, but takes less space in the code.
Any suggestions on how to solve this problem? Thank you in advance from a beginner programmer!
As #MePsyDuck mentioned in comments, you can use min and max functions to limit the range to only reference valid squares in the board matrix.
Furthermore, you could make a generic function that does the count-job on any given list of values. Then you can call that generic function four times: once for every direction (horizontal, vertical, diagonal \ and diagonal /)
Here is how that could work:
def is_win(board, n, x, y):
end_row = len(board)
color = board[x][y]
def check(values):
counter = 0
for value in values:
if value == color:
counter += 1
else:
counter = 0
if counter == n:
return True
return False
return (check([board[i][y] for i in range(max(0, x - n + 1), min(end_row, x + n))])
or check([board[x][i] for i in range(max(0, y - n + 1), min(end_row, y + n))])
or check([board[x+i][y+i] for i in range(max(-x, -y, 1 - n), min(end_row - x, end_row - y, n))])
or check([board[x+i][y-i] for i in range(max(-x, y - end_row + 1, 1 - n), min(end_row - x, y + 1, n))]))
Instead of looping from 0 to 14, just loop from 0 to (board_size - winning_length).
Here's an example for a 1-dimensional board:
BOARD_SIZE = 15
WINNING_LENGTH = 5
for x in range(BOARD_SIZE - WINNING_LENGTH):
players_here = set()
for pos in range(x, x + WINNING_LENGTH):
players_here.add(board[pos])
if len(players_here) == 1:
# Exactly 1 player occupies every position in this line, so they win

Conway's Game of Life not counting neighbors correctly

I am doing the standard Conway's Game of Life program using Python. I am having an issue when trying to count neighbors as I iterate through the array. I created print statements that print the succession of the if statement, as well as the value of count for each statement.
Here is my code: ( I have the questions inside the # throughout the code)
import random
numrows = 10
numcols = 10
def rnd():
rn = random.randint(0,1)
return rn
def initial():
grid = []
count = 0
for x in range(numrows):
grid.append([])
for y in range(numcols):
rand=random.randrange(1,3)
if(rand == 1):
grid[x].append('O')
else:
grid[x].append('-')
for x in grid:
print(*x, sep=' ',end="\n") #this prints the random 2d array
print("")
print("")
answer = 'y'
newgrid = []
count = 0
while(answer == 'y'): # I believe I am going through, checking neighbors
# and moving onto the next index inside these for
#loops below
for r in range(0,numrows):
grid.append([])
for c in range(0,numcols):
if(r-1 > -1 and c-1 > -1): #I use this to check out of bound
if(newgrid[r-1][c-1] == 'O'):#if top left location is O
count = count + 1 #should get count += 1
else:
count = count
print("top left check complete")
print(count)
if(r-1 > -1):
if(newgrid[r-1][c] == 'O'):
count = count + 1
else:
count = count
print("top mid check complete")
print(count)
if(r-1 > -1 and c+1 < numcols):
if(newgrid[r-1][c+1] == 'O'):
count = count + 1
else:
count = count
print("top right check complete")
print(count)
if(c-1 > -1 and r-1 > -1):
if(newgrid[r][c-1] == 'O'):
count = count + 1
else:
count = count
print("mid left check complete")
print(count)
if(r-1 > -1 and c+1 < numcols):
if(newgrid[r][c+1] == 'O'):
count = count + 1
else:
count = count
print("mid right check complete")
print(count)
if(r+1 < numrows and c-1 > -1):
if(newgrid[r+1][c-1] == 'O'):
count = count + 1
else:
count = count
print("bot left check complete")
print(count)
if(r+1 < numrows and c-1 > -1):
if(newgrid[r+1][c] == 'O'):
count = count + 1
else:
count = count
print("bot mid check complete")
print(count)
if(r+1 < numrows and c+1 < numcols):
if(newgrid[r+1][c+1] == 'O'):
count = count + 1
else:
count = count
print("bot right check complete")
print(count)
# I am not sure about the formatting of the code below, how do I know that
# the newgrid[r][c] location is changing? should it be according to the for-
# loop above? Or should it get it's own? If so, how could I construct it as
# to not interfere with the other loops and items of them?
if(newgrid[r][c] == '-' and count == 3):
newgrid[r][c] ='O'
elif(newgrid[r][c] == 'O' and count < 2):
newgrid[r][c] = '-'
elif(newgrid[r][c] == 'O' and (count == 2 or count == 3)):
newgrid[r][c] = 'O'
elif(newgrid[r][c] == 'O' and count > 3):
newgrid[r][c] = '-'
# I'm also confused how to go about printing out the 'new' grid after each
# element has been evaluated and changed. I do however know that after the
# new grid prints, that I need to assign it to the old grid, so that it can
# be the 'new' default grid. How do I do this?
for z in newgrid:
print(*z, sep=' ',end="\n")
answer = input("Continue? y or n( lower case only): ")
newgrid = grid
if(answer != 'y'):
print(" Hope you had a great life! Goodbye!")
initial()
Here is the current output and error message:
>>> initial()
- O - - O - - O - -
- O - - O - - - O O
- O - - O - O O - O
O - - O - - O O O O
O - O O - - - O O -
O - O - O - O - O -
O - O O O O - - O -
- - - - O O O - - O
O O - O - - O - - -
- - O O O - O - - -
top left check complete
0
top mid check complete
0
top right check complete
0
mid left check complete
0
mid right check complete
0
bot left check complete
0
bot mid check complete
0
Traceback (most recent call last):
File "<pyshell#68>", line 1, in <module>
initial()
File "C:\Users\Ted\Desktop\combined.py", line 86, in initial
if(newgrid[r+1][c+1] == 'O'):
IndexError: list index out of range
As I iterate through the random array to see what the neighbors are, it seems to be fine up until it moves over to [0][1] while checking the bot right neighbor.
Also, the mid right neighbor should + 1 to count as it is alive. However, even with succession of the if statement, count remains 0?
Question 1: How can I possibly know that my if conditions witll suffice for every instance of [r][c] for all sides of the array?
Question 2: Is my current method of checking out of bounds the best for my situation? Is there a way to make a "check all for out of bounds" before I even check the value?
I am at my wit's end at this point. Thanks in advance for the time taken to help answer my questions
You are getting that index error because your newgrid only contains a single empty row. And your testing for neighbours in newgrid instead of in grid (as Blckknght mentions in the comments). I've made a few repairs, but there's a lot more that can be done to improve this code. It looks like it's working now, but it's hard to tell when you're working with random Life forms. :) I suggest giving your program some way of using known Life patterns like blinkers and gliders to see that they behave correctly.
The simplest way to ensure that newgrid is valid is to copy it from grid. If we just do newgrid = grid that simply makes newgrid another name for the grid object. To copy a list of lists properly we need to make copies of each of the internal lists. My new code does that with the copy_grid function.
I've fixed a couple of minor bugs that you had in the if tests in the section that counts neighbours, and I've simplified the logic that updates a cell from its neighbour count. I've also condensed the code that makes a random grid, and I've added a simple function that can read a Life pattern from a string and build a grid from it. This lets us test the code with a Glider. I've also added a function that makes an empty grid. The program doesn't currently use that function although I used it during my tests, and I guess it's a useful example. :)
import random
# Set a seed so that we get the same random numbers each time we run the program
# This makes it easier to test the program during development
random.seed(42)
numrows = 10
numcols = 10
glider = '''\
----------
--O-------
---O------
-OOO------
----------
----------
----------
----------
----------
----------
'''
# Make an empty grid
def empty_grid():
return [['-' for y in range(numcols)]
for x in range(numrows)]
# Make a random grid
def random_grid():
return [[random.choice('O-') for y in range(numcols)]
for x in range(numrows)]
# Make a grid from a pattern string
def pattern_grid(pattern):
return [list(row) for row in pattern.splitlines()]
# Copy a grid, properly!
def copy_grid(grid):
return [row[:] for row in grid]
# Print a grid
def show_grid(grid):
for row in grid:
print(*row)
print()
def run(grid):
show_grid(grid)
# Copy the grid to newgrid.
newgrid = copy_grid(grid)
while True:
for r in range(numrows):
for c in range(numcols):
# Count the neighbours, making sure that they are in bounds
count = 0
# Above this row
if(r-1 > -1 and c-1 > -1):
if(grid[r-1][c-1] == 'O'):
count += 1
if(r-1 > -1):
if(grid[r-1][c] == 'O'):
count += 1
if(r-1 > -1 and c+1 < numcols):
if(grid[r-1][c+1] == 'O'):
count += 1
# On this row
if(c-1 > -1):
if(grid[r][c-1] == 'O'):
count += 1
if(c+1 < numcols):
if(grid[r][c+1] == 'O'):
count += 1
# Below this row
if(r+1 < numrows and c-1 > -1):
if(grid[r+1][c-1] == 'O'):
count += 1
if(r+1 < numrows):
if(grid[r+1][c] == 'O'):
count += 1
if(r+1 < numrows and c+1 < numcols):
if(grid[r+1][c+1] == 'O'):
count += 1
# Update the cell in the new grid
if grid[r][c] == '-':
if count == 3:
newgrid[r][c] ='O'
else:
if count < 2 or count> 3:
newgrid[r][c] = '-'
# Copy the newgrid to grid
grid = copy_grid(newgrid)
show_grid(grid)
answer = input("Continue? [Y/n]: ")
if not answer in 'yY':
print(" Hope you had a great life! Goodbye!")
break
#grid = random_grid()
grid = pattern_grid(glider)
run(grid)
This code does work correctly, but there is still plenty of room for improvement. For example, here's an improved version of run() that condenses the neighbour counting section by using a couple of loops.
def run(grid):
show_grid(grid)
# Copy the grid to newgrid.
newgrid = copy_grid(grid)
while True:
for r in range(numrows):
for c in range(numcols):
# Count the neighbours, making sure that they are in bounds
# This includes the cell itself in the count
count = 0
for y in range(max(0, r - 1), min(r + 2, numrows)):
for x in range(max(0, c - 1), min(c + 2, numcols)):
count += grid[y][x] == 'O'
# Update the cell in the new grid
if grid[r][c] == '-':
if count == 3:
newgrid[r][c] ='O'
else:
# Remember, this count includes the cell itself
if count < 3 or count > 4:
newgrid[r][c] = '-'
# Copy the newgrid to grid
grid = copy_grid(newgrid)
show_grid(grid)
answer = input("Continue? [Y/n]: ")
if not answer in 'yY':
print(" Hope you had a great life! Goodbye!")
break
To count the neighbors, just follow this simple rule. You will have the row and col of the current cell. Using that form two arrays, one for rows and another for columns. Below would be your logic.
You can find the detailed implementation with a demo video here.
this.neibhours = function() {
var rows = [row-1, row, row+1];
var cols = [col-1, col, col+1];
neibhourCells = [];
for(var i=0; i < rows.length; i++) {
for(var j=0; j < cols.length; j++) {
if(!(col === cols[j] && row === rows[i])) {
var cell = new Cell(rows[i], cols[j])
if(cell.isOnGrid()) {
neibhourCells.push(cell);
}
}
}
}
return neibhourCells;
}

Conaway's Game of Life problems

Here is my very rough implementation of Conway's Game of Life simulation.
LIVE = 1
DEAD = 0
def board(canvas, width, height, n):
for row in range(n+1):
for col in range(n+1):
canvas.create_rectangle(row*height/n,col*width/n,(row+1)*height/n,(col+1)*width/n,width=1,fill='black',outline='green')
n = int(raw_input("Enter the dimensions of the board: "))
width = n*25
height = n*25
from Tkinter import *
import math
window=Tk()
window.title('Game of Life')
canvas=Canvas(window,width=width,height=height,highlightthickness=0)
canvas.grid(row=0,column=0,columnspan=5)
board = [[DEAD for row in range(n)] for col in range(n)]
rect = [[None for row in range(n)] for col in range(n)]
for row in range(n):
for col in range(n):
rect[row][col] = canvas.create_rectangle(row*height/n,col*width/n,(row+1)*height/n,(col+1)*width/n,width=1,fill='black',outline='green')
#canvas.itemconfigure(rect[2][3], fill='red') #rect[2][3] is rectangle ID
#print rect
f = open('filename','r') #filename is whatever configuration file is chosen that gives the step() function to work off of for the first time
for line in f:
parsed = line.split()
print parsed
if len(parsed)>1:
row = int(parsed[0].strip())
col = int(parsed[1].strip())
board[row][col] = LIVE
board[row][col] = canvas.itemconfigure(rlist[row][col], fill='red')
def surrounding(row,col):
count = 0
if board[(row-1) % n][(col-1) % n] == LIVE:
count += 1
if board[(row-1) % n][col % n] == LIVE:
count += 1
if board[(row-1) % n][(col+1) % n] == LIVE:
count += 1
if board[row % n][(col-1) % n] == LIVE:
count += 1
if board[row % n][(col+1) % n] == LIVE:
count += 1
if board[(row+1) % n][(col-1) % n] == LIVE:
count +=1
if board[(row+1) % n ][col % n] == LIVE:
count += 1
if board[(row+1) % n][(col+1) % n] == LIVE:
count += 1
print count
return count
surrounding(1,1)
def round():
board_copy = board
for row in range(n):
for col in range(n):
if surrounding(row,col) == 3:
board_copy[row][col] = LIVE
board_copy[row][col] = canvas.itemconfigure(rect[row][col],fill='red')
elif surrounding(row,col) > 3 or getNeighbors(row,col) < 2:
board_copy[row][col] = DEAD
board_copy[row][col] = canvas.itemconfigure(rect[row][col],fill='black')
board = board_copy
def start():
global alarm
alarm = window.after(500,round)
def stop():
window.after.cancel(alarm)
So I have a function to count how many surrounding squares around a certain square had the value LIVE (where LIVE = 1).
Originally, all squares were initialized to DEAD. The configuration file determines which squares are assigned the value LIVE. Made a configuration file so that the 8 squares surrounding the square at 1,1 would return a value of 8, but I am getting back a value of 0 consistently, no matter the configuration or the tested square.
UPDATE: Changed the counter to begin at 1 and the return value was 1. I'm guessing my function isn't actually counting (or reading the values of the surrounding squares on the board), but I can't see why it would not.
Also, for my step() function, I need a function that makes a copy of the board and then changes the fill on the copy depending on a count being performed on the original board. If a rectangle on the original board has 3 rectangles with the values of LIVE, then the rectangle with the same indices on the board copy will have a LIVE value and turn red. Same for DEAD, except for different case. At the end the copied board (with changes) replaces the original board so that when we run the function again, it will be based off the copy.
I'm assuming board_copy = board is sufficient in making the copy; what do I write so that on the Tkinter window, after the function is performed, the board_copy is what appears?
The format of the config file is
rownum colnum
rownum colnum
So the config file I used if I wanted to get 8 in countNeighbors function (if it worked) for the first round would be:
0 0
0 1
0 2
1 0
1 2
2 0
2 1
2 2
I'm assuming board_copy = board is sufficient in making the copy;
No, board_copy = board is not sufficient. This will just bind the name board_copy to the exact same list of list as board, i.e. everything you change in board_copy is also changed in board.
Instead, you could use the deepcopy function from the copy module:
import copy
board_copy = copy.deepcopy(board)
Or use a list-comprehension to create a deep copy of the nested list:
board_copy = [[x for x in row] for row in board]
The use of board = board_copy at the end of the method is okay, since here you just want to bind the new board to board. Note, however, that you will also need to add global board at the top of the method to access the globally defined board.
Also, note that you define both a function board (def board(...): and a global variable board (board = [...]). The latter will shadow the first, i.e. you will not be able to use the board function. You should rename the function to e.g. def draw_board(...).
There might be more problems with your code, but I can not execute it sinceit seems to be incomplete (where is start called?) and I do not know the content of 'filename'.

List.append() changing all elements to the appended item [duplicate]

This question already has answers here:
Why does foo.append(bar) affect all elements in a list of lists?
(3 answers)
Closed 4 years ago.
I seem to have a problem with my maze generating program made in Python. I'm trying to randomly create a path that branches out at select points, with the points getting stored as it goes along. When the maze gets to a dead end, it will sort back through the visited points by testing the top value than popping that and going to the next one, until it gets to a spot where it isn't a dead end. However, when I try to append items to the list I'm using to save the spaces I've been to, something strange happens, I've never seen it before actually. Here's the code, and the best way to see it is to run it a through times until it goes all the way through. I haven't really found a way to counter the dead end problem, so if anyone could help me with that also, that would be great.
import random
width = 8
def check(x,y):
"""Figures out the directions that Gen can move while"""
if x-1 == -1:
maze[x][y][3] = 0
if x+1 == 8:
maze[x][y][1] = 0
if y+1 == 8:
maze[x][y][2] = 0
if y-1 == -1:
maze[x][y][0] = 0
if x + 1 in range(0,8) and visited[x+1][y] == False:
maze[x][y][1] = 2
if x - 1 in range(0,8) and visited[x-1][y] == False:
maze[x][y][3] = 2
if y + 1 in range(0,8) and visited[x][y+1] == False:
maze[x][y][2] = 2
if y - 1 in range(0,8) and visited[x][y-1] == False:
maze[x][y][0] = 2
def Gen(x,y):
visited[x][y] = True
past.append(current)
dirs = []
check(x,y)
print current
if maze[x][y][0] == 2:
dirs.append(0)
if maze[x][y][1] == 2:
dirs.append(1)
if maze[x][y][2] == 2:
dirs.append(2)
if maze[x][y][3] == 2:
dirs.append(3)
pos = random.choice(dirs)
print dirs
maze[x][y][pos] = 1
if pos == 0:
current[1] -= 1
if pos == 1:
current[0] += 1
if pos == 2:
current[1] += 1
if pos == 3:
current[0] -= 1
if maze[x][y][0] == 4:
maze[x][y][0] = 1
if maze[x][y][1] == 4:
maze[x][y][1] = 1
if maze[x][y][2] == 4:
maze[x][y][2] = 1
if maze[x][y][3] == 4:
maze[x][y][3] = 1
print maze[x][y]
print past, '\n'
#Build the initial values for the maze to be replaced later
maze = []
current = [0,0]
visited = []
past = []
#Generate empty 2d list with a value for each of the xy coordinates
for i in range(0,width):
maze.append([])
for q in range(0, width):
maze[i].append([])
for n in range(0, 4):
maze[i][q].append(4)
#Makes a list of falses for all the non visited places
for x in range(0, width):
visited.append([])
for y in range(0, width):
visited[x].append(False)
#Generates the walls
#for q in range(0, width):
# for i in range(0, width):
# check(q, i)
current = [0,0]
while current != [7,7]:
Gen(current[0], current[1])
print maze
As you can see, it starts at 0,0 and then figures out the possible paths to take. It randomly selects from those and sets the value for that side of the room in 0,0 to 1, which means a passage. 2 means wall and 0 means out of bounds. 4 is just a placeholder as all values should be filled by the time the maze is completely generated.
If anyone could help me, that would be great and very appreciated. Thanks in advance.
I believe the current list is simply copied multiple times into past. So you have multiple copies of the same list.
To fix: in the line past.append(current) (two lines below def Gen(x,y):), change it to past.append(current[:]).
The notation list[:] creates a copy of the list. Technically, you are creating a slice of the whole list.
By the way, a better solution would be to not use a global current variable :)
Yeah this is correct while List Comprehension in Python you need to append by strip other wise it will replace multiple times

Categories

Resources