Stuck in a stupid phase of coding game of life - python

I've been trying to code game of life by my own as I want to learn python and I thought that could be a good practice and I have just finish except I need to pass a variable to another method but I really dont know how I know it could seem dumb
but wait a bit and see the code is not that easy as it sound unless for me
import random,time
f=3
c=3
contador = 0
tablero = []
tablero_dibujado = []
class juego(object):
def tablero(self): #Create the Board
for i in range(f):
tablero.append([0]*c)
tablero_dibujado.append([0]*c)
def rellenar_tablero_random(self): #Fill the board with random 0 and 1
for i in range(f):
for j in range(c):
tablero[i][j] = random.randint(0,1)
print(tablero)
def rellenar_tablero_manual(self): #Just to fill the board manually if I want for some reason
tablero[0][1] = 1
for i in range(2):
tablero[1][i] = 1
print(tablero)
def distancia_vecino(self,cell_f,cell_c): #Measure Distance for possible neighbours
distancia_vecino = [(-1,-1),(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1)]
for i in range(8):
string = distancia_vecino[i]
comparar_string = str(string)
x,y = comparar_string.split(",")
x = str(x).replace(",","")
y = str(y).replace(",","")
x = x.replace("(","")
y = y.replace(")","")
y = y.replace(" ","")
x = int(x) + cell_f
y = int(y) + cell_c
if x>=f or x<0:
continue
else:
if y>=c or y<0:
continue
else:
game.detectar_vecino(cell_f,cell_c,x,y)
game.vida(cell_f,cell_c)
def detectar_vecino(self, cell_f, cell_c, x, y): #Check how many neighboards do I have
vecinos = 0
if tablero[cell_f][cell_c] == 1:
if tablero[cell_f][cell_c] == tablero[x][y]:
vecinos+=1
else:
if tablero[cell_f][cell_c] != tablero[x][y]:
vecinos+=1
contador = contador + vecinos
def iterar_tablero(self): #Just to iterate all the board to check the values
for i in range(f):
for j in range(c):
game.distancia_vecino(i,j)
a = input() #In order to the screen dont close after executing it
def vida(self, cell_f, cell_c): #Check if they are alive and if they should be alive or dead
print(contador)
if tablero[cell_f][cell_c] == 1:
if contador > 3 or contador < 2:
tablero[cell_f][cell_c] = 0
else:
if contador == 3:
tablero[cell_f][cell_c] = 1
game.dibujar_tablero()
def dibujar_tablero(self): #Draw the board in a more clearly way
contador1 = 0
for i in range(f):
for j in range(c):
if tablero[i][j] == 1:
tablero_dibujado[i][j] = "§"
else:
tablero_dibujado[i][j] = "■"
for i in tablero_dibujado:
print(" ")
for j in i:
print(j, end=" ")
print("")
time.sleep(2)
game = juego()
game.tablero()
game.rellenar_tablero_manual()
game.iterar_tablero()
What I need is that in detectar_vecino have to get all the neighbour of a cell in the board and the problem is that doing it I got : local variable 'contador' referenced before assignment. And I know why it happen.However I couldnt find any alternative way of doing it so please if anyone know how can I solve it.
I just want to clarify that this isnt any work from anywhere,Im doing it just by my own as a hobby and with this I just want to finish with thank you for your time I appreciate it

Add this line global contador like below
def detectar_vecino(self, cell_f, cell_c, x, y):
global contador # Add this line.
vecinos = 0
if tablero[cell_f][cell_c] == 1:
if tablero[cell_f][cell_c] == tablero[x][y]:
vecinos+=1
else:
if tablero[cell_f][cell_c] != tablero[x][y]:
vecinos+=1
contador = contador + vecinos

Related

All solutions for N-Queens problem prints empty board

As the title states, I've implemented the N-Queens problem for all soulutions but there is one problem, it prints an empty board. I saw a solution only where we put the printboard in an if statement but without a return in printboard i fail to see how it works`
#N Queens through Backtracking with all solutions
def initialize(n):
for key in ['queen','row','col','NWtoSE','SWtoNE']:
board[key] = {}
for i in range(n):
board['queen'][i] = -1
board['row'][i] = 0
board['col'][i] = 0
for i in range (2*n-1):
#Sum of NW to SE diagonal add to constant i.e (i+j) = const
board['SWtoNE'][i] = 0
for i in range (-(n-1), n):
#Difference of SW to NE diagonal is constant i.e (j-i) = const
board['NWtoSE'][i] = 0
def isAvailable(i, j):
return (board['row'][i] == 0 and board['col'][j] == 0 and
board['NWtoSE'][j-i] == 0 and board['SWtoNE'][j+i] == 0)
def addQueen(i, j):
board['queen'][i] = j
board['row'][i] = 1
board['col'][j] = 1
board['NWtoSE'][j-i] = 1
board['SWtoNE'][j+i] = 1
def undo(i, j):
board['queen'][i] = -1
board['row'][i] = 0
board['col'][j] = 0
board['NWtoSE'][j-i] = 0
board['SWtoNE'][j+i] = 0
def printboard():
for i in board['queen'].keys():
print((i, board['queen'][i]), end = " ")
print()
def placequeen(i):
n = len(board['queen'].keys())
for j in range(n):
if(isAvailable(i, j)):
addQueen(i, j)
if i == n-1:
printboard()
else:
placequeen(i+1)
undo(i,j)
board = {}
n = int(input("Enter number of queens : "))
initialize(n)
printboard()
The following is the solution which I don't understand
if placequeen(0): printboard()

List append MemoryError

So I have this piece of code I'm trying to make generate level layouts for a grid of rooms. The first time through the mainloop it runs perfectly it runs and does exactly what it should but the second time through it pauses just after the first print error and gives me the attached error and I cant figure out what's wrong with it.
(the y/n prompt is only to slow down the program so I can see what's happening)
userInput = ""
roomChance = 0.5
world = [[0,0,0], \
[0,1,0], \
[0,0,0]]
possibleWorld = []
newX = []
def check_neighbours(xy):
possibleWorld.clear()
yLoops = 0
for y in xy:
print(" y:", y)
xLoops = 0
for x in y:
print(" x:", x)
#Check left cell
if(xLoops-1 >= 0):
if(y[xLoops-1] == 1):
possibleWorld.append([xLoops, yLoops])
print("x-1:", y[xLoops-1])
#Check right cell
if(xLoops+1 < len(y)):
if(y[xLoops+1] == 1):
possibleWorld.append([xLoops, yLoops])
print("x+1:", y[xLoops+1])
#Check above cell
if(yLoops-1 >= 0):
if(xy[yLoops-1][xLoops] == 1):
possibleWorld.append([xLoops, yLoops])
print("y-1:", xy[yLoops-1][xLoops])
#Check above cell
if(yLoops+1 < len(xy)):
if(xy[yLoops+1][xLoops] == 1):
possibleWorld.append([xLoops, yLoops])
print("y+1:", xy[yLoops+1][xLoops])
print("\n")
xLoops += 1
yLoops += 1
def assign_neighbours(possible, world, chance):
for i in possible:
if(random.random() < chance):
world[i[1]][i[0]] = 1
possible.clear()
def border_expand(world):
for x in world[0]:
if(x == 1):
for i in world[0]:
newX.append(0)
world.insert(0, newX)
newX.clear
break
def print_world(world):
for y in world:
print(y)
# ==================== Mainloop ====================
while(True):
userInput = input(print("Generate Level? Y/N?"))
check_neighbours(world)
print(possibleWorld)
assign_neighbours(possibleWorld, world, roomChance)
print_world(world)
border_expand(world)
print("\n")
print_world(world)
File "C:\Users\Potato\Desktop\Level gen_query.py", line 96, in <module>
border_expand(world)
File "C:\Users\Potato\Desktop\Level gen_query.py", line 67, in border_expand
newX.append(0)
MemoryError```
You're not calling newX.clear, so it is continually growing. When you run world.insert(0, newX) you are inserting a reference to newX into world[0], even if you did call newX.clear() you would not get the behaviour you want as the first element in world would be empty.
You need to create a new list on every call to border_expand so that it is a new list every time
def border_expand(world):
newX = []
for x in world[0]:
if(x == 1):
for i in world[0]:
newX.append(0)
world.insert(0, newX)
break

trying to compare two lists or one list with the same

import random
b=[]
o=[]
v=0
g=2
y=0
V=0
q=0
compat=0
alex=[]
zach=[]
while v != 5:
name="name"
position="position"
answers=[]
for i in range(10):
answer=random.randint(1,4)
answers.append(answer)
b.append(name)
b.append(position)
b.append(answers)
v+=1
print(b)
for ii in range(0,5):
t=b[g]
o.append(t)
g+=3
l=len(o)
for iii in list(o):
C = o[y]
y = y + 1
alex = []
for iiii in range(5):
I = 0
compat=0
R=o[q]
V=0
Y = C[V]
for iiiii in range(10):
r=R[I]
if r == Y:
compat+=1
else:
compat=compat
I+=1
V += 1
print(compat)
alex.append(compat)
print(alex)
zach.append(alex)
q+=1
w=len(zach)
print(zach)
print(w)
this is my code and it works pretty well. but it should put every single value against every other one but it doesnt it just put the same Y value and does not change. i have put v+=1 in tons of different places and moved around the a couple variable but it doesnt change. there should be 25 different answers for 5 people but it doesnt it just prints the same number 5 times then restarts.
any help would be appreciared
Edit: this is what i will intergrat the code above into
global compatability
import sqlite3
with sqlite3.connect("Questionare.db") as db:
cursor = db.cursor()
class mentee: # these classes are made to create a place where atributes can be filled with variables
def __init__(self,mentee_name,mentee_position):
self._mentee_posisition=mentee_position
self._mentee_name=mentee_name
def menteereport(self):
return{"mentee name:":self._mentee_name,"mentee position":self._mentee_posisition}
class mentor:
def __init__(self,mentor_name,mentor_position):
self._mentor_position=mentor_position
self._mentor_name=mentor_name
def mentorreport(self): # these are methods and they use a function with the variables instanciated within the class to make this appen
return {"mentor name":self._mentor_name,"mentor position":self._mentor_position}
class calculation:
def __init__(self,number_of_questions,compatability,mentoranswers,menteeanwers):
self._question_number= 1
self._number_of_questions=number_of_questions
self._compatability=compatability
self._mentor_values=mentoranswers
self._mentee_values=menteeanwers
def calc(self):
compat=0
c=0
for i in range(0,self._number_of_questions):
if self._mentee_values[c] == self._mentor_answers[c]:
compat += 1
c+=1
else:
compat += 0
c+=0
compatability=compat/self._number_of_questions
self._compatability=compatability
compatability=compatability*100
print(self._mentee_answers)
print(self._mentor_answers)
print("\n{:0.2f}%.\n".format(compatability))
def mentoranswer(self):
self._number_of_questions = int(self._number_of_questions)
self._question_number=1
for i in range(0,self._number_of_questions):
answer=input("Q{}".format(self._question_number))
self._question_number+=1
self._mentor_answers.append(answer)
def menteeanswer(self):
self._number_of_questions = int(self._number_of_questions)
self._question_number=1
for i in range(0,self._number_of_questions):
answer=input("Q{}".format(self._question_number))
self._question_number+=1
self._mentee_answers.append(answer)
class timerequirements:
def __init__(self,mentor_time_allotment,mentee_time_allotment,ideal_length_of_mentoring,ideal_length_of_being_mentored):
self._mentor_time_allotment=mentor_time_allotment
self._mentee_time_allotment=mentee_time_allotment
self._ideal_length_of_mentoring=ideal_length_of_mentoring
self._ideal_length_of_being_mentored=ideal_length_of_being_mentored
def main(): # this function is created to put the variables into the artibutes so that everything will work.
v = True
mentoranswers = []
menteeanswers = []
no_of_q = int(input("numebr of questions"))
while v == True:
morm = input("are your a mentor or a mentee")
if morm.lower() == "mentor":
name = input("name")
position = input("position")
answers = []
for i in range(0, no_of_q):
answer = int(input("1 or 2"))
answers.append(answer)
mentoranswers.append(name)
mentoranswers.append(position)
mentoranswers.append(answers)
print(mentoranswers)
elif morm.lower() == "mentee":
name = input("name")
position = input("position")
answers = []
for i in range(0, no_of_q):
answer = int(input("1 or 2"))
answers.append(answer)
menteeanswers.append(name)
mentoranswers.append(position)
menteeanswers.append(answers)
print(menteeanswers)
elif morm.lower() == "q":
v = False
else:
print("try again")
print(mentoranswers.mentorreport())
print(menteeanswers.menteereport())
main()
you are adding way too much noise.
for iii in list(o):
C = o[y]
y = y + 1
why don't you simply use the variable you just created? it will be incremented automatically
for iii in list(o):
C = o[iii]
you should learn how to use a loop and a few other basics. there are good tutorials on the official python site. here the for-loop one. most of your variables exist just to repeat what you are already doing.
i've avoided some high-level constructs, but i left zip.
import random
mentees = []
names = ['zach', 'alex', 'fred', 'jane', 'sara']
for name in names:
mentee = dict()
mentee['name'] = name
mentee['compatibility'] = []
answers = []
for i in range(10):
answers.append(random.randint(1,4))
mentee['answers'] = answers
mentees.append(mentee)
for mentee1 in mentees:
m1_answers = mentee1['answers']
for mentee2 in mentees:
m2_answers = mentee2['answers']
compat = 0
# zip fuses both lists into one
for m1_answer, m2_answer in zip(m1_answers, m2_answers):
if m1_answer == m2_answer:
compat += 1
mentee1['compatibility'].append((mentee2['name'], compat))
print(mentees)

Python error: int object has no attribute to append?

I can't figure out why my code isn't working, very frustrating. I constantly get the error: int object has no attribute to append (for average.append(i, average//250)). But I can't figure out what exactly is wrong here. Is it not possible to import other definition in append functions?
I hope somebody can help me out!
Any help with my code in general is appreciated :)
def main():
average = []
y_values = []
for x in range(0, 2501, 500):
for i in range(250):
average.append(calculate(x))
average = sum(average)
print("{} euro, {} worpen".format(i, average//250))
y_values.append(average//250)
x_values = [0, 500, 1000, 1500, 2000, 2500]
y_values = []
plt.plot(x_values, y_values)
plt.xlabel("Startgeld")
plt.ylabel("Aantal worpen")
plt.title("Monopoly")
plt.show()
def calculate(game_money):
piece = monopoly.Piece()
board = monopoly.Board()
owns = possession(board)
dice = throw()
throw_count = 0
number = 0
total_throw = 0
while not all(owns.values()):
number == throw()
piece.move(number)
total_throw = total_throw + number
throw_count += 1
if total_throw > 40:
game_money += 200
elif board.values[piece.location] > 0:
if game_money > board.values[piece.location]:
if owns[board.names[piece.location]] == False:
owns[board.names[piece.location]] = True
game_money = game_money - board.values[piece.location]
return total_throw
def throw():
dice = randint(1,6) + randint(1,6)
return dice
def possession(board):
owns = {}
for i in range(40):
if board.values[i] > 0:
owns[board.names[i]] = False
return owns
if __name__ == "__main__":
main()
You done a small mistake in your code. See my comment below and correct your code accordingly. Good Luck :-)
y_values = []
average = []
for x in range(0, 2501, 500):
for i in range(250):
average.append(calculate(x))
#average = sum(average) #This is your mistake. Now onward average will be considered as int object make it like below
average1 = sum(average)
print("{} euro, {} worpen".format(i, average1//250))
y_values.append(average1//250)

ValueError: too many values to unpack (expected 2), listcomp

Been trying to learn python and therefore using a pre-made minesweeper and the exercise was to make a class of some functions. But i seem to fet the error:
line 66, in <listcomp>
values = [grid[r][c] for r,c in self.getneighbors(grid, rowno, colno)]
ValueError: too many values to unpack (expected 2)
And i have no idea how to fix it, tried .items but i have no idea what to do. Hopefully i can get some help/tips. Thank you!
import string
import random
gridsize = int(input('SIZE:'))
numberofmines = int(input('MINES:'))
def setupgrid(gridsize,start,numberofmines):
grid = [['0' for i in range(gridsize)] for i in range(gridsize)]
mines = generatemines(grid,start,numberofmines)
p = omringande(grid)
p.getnumbers(grid)
return (grid,mines)
def showgrid(grid):
gridsize = len(grid)
horizontal = ' '+4*gridsize*'-'+'-'
# Print top column letters
toplabel = ' :) '
for i in string.ascii_lowercase[:gridsize]:
toplabel = toplabel+i+' '
print (toplabel,'\n',horizontal)
# Print left row numbers
for idx,i in enumerate(grid):
row = '{0:2} |'.format(idx+1)
for j in i:
row = row+' '+j+' |'
print (row+'\n'+horizontal)
print ('')
def getrandomcell(grid):
gridsize = len(grid)
a = random.randint(0,gridsize-1)
b = random.randint(0,gridsize-1)
return (a,b)
class omringande(object):
def __init__(self,grid):
self.grid = grid
def getneighbors(self,grid,rowno,colno):
gridsize = len(grid)
row = grid[rowno]
column = grid[rowno][colno]
neighbors = []
for i in range(-1,2):
for j in range(-1,2):
if i == 0 and j == 0: continue
elif -1<rowno+i<gridsize and -1<colno+j<gridsize:
neighbors.append((rowno+i,colno+j))
return (row,column)
def getnumbers(self,grid):
gridsize = len(grid)
for rowno,row in enumerate(grid):
for colno,col in enumerate(row):
if col!='X':
# Gets the values of the neighbors
values = [grid[r][c] for r,c in self.getneighbors(grid, rowno, colno)]
# Counts how many are mines
grid[rowno][colno] = str(values.count('X'))
# Generate mines
def generatemines(grid,start,numberofmines):
gridsize = len(grid)
mines = []
for i in range(numberofmines):
cell = getrandomcell(grid)
while cell==(start[0],start[1]) or cell in mines:
cell = getrandomcell(grid)
mines.append(cell)
for i,j in mines: grid[i][j] = 'X'
return mines
def showcells(grid,currgrid,rowno,colno):
# Exit function if the cell was already shown
if currgrid[rowno][colno]!=' ':
return
# Show current cell
currgrid[rowno][colno] = grid[rowno][colno]
# Get the neighbors if the cell is empty
if grid[rowno][colno] == '0':
for r,c in omringande.getneighbors(grid,rowno,colno):
# Repeat function for each neighbor that doesn't have a flag
if currgrid[r][c] != 'F':
showcells(grid,currgrid,r,c)
def playagain():
choice = input('Play again? (y/n): ')
return choice.lower() == 'y'
def playgame():
currgrid = [[' ' for i in range(gridsize)] for i in range(gridsize)]
showgrid(currgrid)
grid = []
flags = []
helpmessage = "Type the column followed by the row (eg. a5).\nTo put or remove a flag, add 'f' to the cell (eg. a5f)\n"
print (helpmessage)
while True:
while True:
lastcell = str(input('Enter the cell ({} mines left): '.format(numberofmines-len(flags))))
print ('\n\n')
flag = False
try:
if lastcell[2] == 'f': flag = True
except IndexError: pass
try:
if lastcell == 'help':
print (helpmessage)
else:
lastcell = (int(lastcell[1])-1,string.ascii_lowercase.index(lastcell[0]))
break
except (IndexError,ValueError):
showgrid(currgrid)
print ("Invalid cell.",helpmessage)
if len(grid)==0:
grid,mines = setupgrid(gridsize,lastcell,numberofmines)
rowno,colno = lastcell
if flag:
# Add a flag if the cell is empty
if currgrid[rowno][colno]==' ':
currgrid[rowno][colno] = 'F'
flags.append((rowno,colno))
# Remove the flag if there is one
elif currgrid[rowno][colno]=='F':
currgrid[rowno][colno] = ' '
flags.remove((rowno,colno))
else: print ('Cannot put a flag there')
else:
# If there is a flag there, show a message
if (rowno,colno) in flags:
print ('There is a flag there')
else:
if grid[rowno][colno] == 'X':
print ('Game Over\n')
showgrid(grid)
if playagain(): playgame()
else: exit()
else:
showcells(grid,currgrid,rowno,colno)
showgrid(currgrid)
if set(flags)==set(mines):
print ('You Win')
if playagain(): playgame()
else: exit()
playgame()
I keep getting the error when the player is supposed to make their move. Tried using (mentioned in other forums) the ".items" but without success.

Categories