All cells in Conway's game of life are alive - python

I tried to implement Conway's game of life in Python-3.6 with this code:
import numpy as np
import time
screen = np.zeros((25,25),dtype=np.int)
while True:
print(screen)
command = input('command?')
if command[0] == 'x':
command = command.split(' ')
x = int(command[0][1:])
y = int(command[1][1:])
if screen[x][y] == 0:
screen[x][y] = 1
else:
screen[x][y] = 0
elif command == 'start':
break
while True:
for x in range(len(screen)):
for y in range(len(screen[x])):
neighbors = 0
if x != len(screen)-1:
neighbors += screen[x+1][y]
if x != 0:
neighbors += screen[x-1][y]
if y != len(screen[x])-1:
neighbors += screen[x][y+1]
if y != 0:
neighbors += screen[x][y-1]
if x != len(screen)-1 and y != len(screen[x])-1:
neighbors += screen[x+1][y+1]
if x != 0 and y != 0:
neighbors += screen[x-1][y-1]
if 0 and y != len(screen[x])-1:
neighbors += screen[x-1][y+1]
if x != len(screen)-1 and y != 0:
neighbors += screen[x+1][y-1]
if screen[x][y] == 0 and neighbors == 3:
screen[x][y] = 1
elif screen[x][y] == 1 and neighbors < 2:
screen[x][y] == 0
elif screen[x][y] == 1 and neighbors > 3:
screen[x][y] == 0
elif screen[x][y] == 1 and neighbors == 2 or 3:
screen[x][y] = 1
print(screen)
time.sleep(0.1)
The Problem is that when I try to run this code with any figure, all the cells are immediately set to 1 in the first generation and won't die off.
Can someone tell me were the issue in my code is and how to solve it?

Your problem seems to be here:
elif screen[x][y] == 1 and neighbors == 2 or 3:
You can't do that (well, you can, but it doesn't do what you expect). Instead try:
elif screen[x][y] == 1 and neighbors in (2 , 3):
(or in {2, 3}).
Check this question for more information.

Related

Execute code whenever the space bar is pressed?

I am making this kind of a game but it isn't really a game so basically I want this to run every time I hit space but it doesn't work no matter what I try so I would be really thankful if somebody could have helped me out on this.
import random
import keyboard
food = 5
x = 0
y = 0
if keyboard.is_pressed('space'):
bobsDecision = random.randint(0,1)
if bobsDecision == 1:
print ('bob ate')
food = 5
else:
xoy = random.randint(1,4)
if xoy == 1:
x = x + 1
elif xoy == 2:
x = x - 1
elif xoy == 3:
y = y + 1
elif xoy == 4:
y = y - 1
food = food - 1
print ('the cords are ', x, " ", y)
print ('The food supply is ', food)
Your code runs once and immediately skips over keyboard.is_pressed("space"), and then exits.
What you want to do instead is to loop forever, and use the keyboard module's read_key functionality to make it wait for a keypress.
An example of this is this - I also added support for exiting the loop/game with esc.
import random
import keyboard
food = 5
x = 0
y = 0
while True:
keyboard.read_key()
if keyboard.is_pressed("esc"):
print("Stopping play...")
break
elif keyboard.is_pressed("space"):
bobsDecision = random.randint(0,1)
if bobsDecision == 1:
print ('bob ate')
food = 5
else:
xoy = random.randint(1,4)
if xoy == 1:
x = x + 1
elif xoy == 2:
x = x - 1
elif xoy == 3:
y = y + 1
elif xoy == 4:
y = y - 1
food = food - 1
print ('the cords are ', x, " ", y)
print ('The food supply is ', food)
You need to put the if statement in a while loop. But ALSO be sure to have some kind of exit code. Below, I used the keypress esc to stop the while loop:
import random
import keyboard
food = 5
x = 0
y = 0
while True:
keyboard.read_key() # an important inclusion thanks to #wkl
if keyboard.is_pressed('esc'):
break
elif keyboard.is_pressed('space'):
bobsDecision = random.randint(0,1)
if bobsDecision == 1:
print ('bob ate')
food = 5
else:
xoy = random.randint(1,4)
if xoy == 1:
x = x + 1
elif xoy == 2:
x = x - 1
elif xoy == 3:
y = y + 1
elif xoy == 4:
y = y - 1
food = food - 1
print ('the cords are ', x, " ", y)
print ('The food supply is ', food)

Conway's game of life - python: cells wont die

I'm am beginning my journey into the world of python. I have done a couple of small projects, but the game of life really piqued my interest. Unfortunately, when I tried to replicate the game, everything worked except for the death of my cells. Per the rules, if a live cell has less than 2 neighbors, or more than 3, it should die. Cells are being born, but alas, they seem to be immortal. Can anyone spot my mistake? I'm including the entire code because I have no idea where I went wrong.
import random, time, copy
height = 10
width = 10
next = []
for x in range(width):
column = []
for y in range(height):
if random.randint(0, 1) == 0:
column.append(" ")
else:
column.append("#")
next.append(column)
while True:
print("\n\n\n\n")
current = copy.deepcopy(next)
for y in range(height):
for x in range(width):
print(current[x][y], end=" ")
print()
for x in range(width):
for y in range(height):
leftco = (x - 1) % width
rightco = (x + 1) % width
botco = (y - 1) % height
topco = (y + 1) % height
neighbors = 0
if current[leftco][topco] == "#":
neighbors = neighbors + 1
if current[leftco][y] == "#":
neighbors = neighbors + 1
if current[leftco][botco] == "#":
neighbors = neighbors + 1
if current[x][topco] == "#":
neighbors = neighbors + 1
if current[x][botco] == "#":
neighbors = neighbors + 1
if current[rightco][topco] == "#":
neighbors = neighbors + 1
if current[rightco][y] == "#":
neighbors = neighbors + 1
if current[rightco][botco] == "#":
neighbors = neighbors + 1
if current[x][y] == "#" and (neighbors == 2 or neighbors == 3):
next[x][y] = "#"
elif current[x][y] == " " and neighbors == 3:
next[x][y] == "#"
else:
next[x][y] == " "
time.sleep(1)
In this section, you confused == and = when you try to assign to a value of next[x][y]
if current[x][y] == "#" and (neighbors == 2 or neighbors == 3):
next[x][y] = "#"
elif current[x][y] == " " and neighbors == 3:
next[x][y] == "#"
else:
next[x][y] == " "
So it should be:
if current[x][y] == "#" and (neighbors == 2 or neighbors == 3):
next[x][y] = "#"
elif current[x][y] == " " and neighbors == 3:
next[x][y] = "#"
else:
next[x][y] = " "
By the way, you see next is highlighted as a special name. That's because next() is a special function in Python standard library, and you shouldn't name your own variables like that. It's harmless in your current program, because you don't use it, but develop a habit to use more specific names, that don't shadow the standard ones

Solving a maze by eliminating junctions

We are trying to make a program that solves any maze by recognising all junctions and eliminating the ones that do not lead to the entrance. We managed to create such a program but we are struggling to get the dots to connect to create a proper path. Does anybody have an idea how to do this because we are out of clues...Picture of the result, but the dots aren't connect by a line
The maze is basically a (n)x(n) grid in a numpy array with walls (true) and paths (false) see:picture of maze as seen from the variable explorer
import numpy as np
import maze_utils as mu
import matplotlib.pyplot as plt
size = 101
maze, start = mu.make_maze(size)
start = [start[1],start[0]]
#------------------------------------------------------------------------------
def junctions_finder(maze, size, start):
junctions = [start]
end = []
for y, row in enumerate(maze):
for x, column in enumerate(row):
if maze[x,y] == False:
if x == 0 or x == (size-1) or y == 0 or y == (size-1):
junctions.append([y,x])
end.append([y,x])
while True:
if x+1 < size and y+1 < size and\
maze[x+1,y] == False and maze[x,y+1] == False\
or x+1 < size and y-1 > 0 and\
maze[x+1,y] == False and maze[x,y-1] == False\
or x-1 > 0 and y-1 > 0 and\
maze[(x-1),y] == False and maze[x,(y-1)] == False\
or x-1 > 0 and y+1 < size and\
maze[(x-1),y] == False and maze[x,(y+1)] == False:
junctions.append([y,x])
break
else:
break
return junctions, end
#------------------------------------------------------------------------------
def eliminate_coor(junctions, end, start):
eliminated = []
for row in junctions:
a = row[1]
b = row[0]
connections = 0
U = False
D = False
L = False
R = False
UW = False
DW = False
LW = False
RW = False
SE = False
if row == start or row == end[0]:
connections = 2
SE = True
for i in range(1,size):
if SE == False:
if a+i <= size-1 and DW == False and D == False:
if maze[a+i, b] == True:
DW = True
else:
for coor in junctions:
if [coor[1],coor[0]] == [a+i,b]:
connections = connections + 1
D = True
if a-i >= 0 and UW == False and U == False:
if maze[a-i, b] == True:
UW = True
else:
for coor in junctions:
if [coor[1],coor[0]] == [a-i,b]:
connections = connections + 1
U = True
if b+i <= size-1 and RW == False and R == False:
if maze[a, b+i] == True:
RW = True
else:
for coor in junctions:
if [coor[1],coor[0]] == [a,b+i]:
connections = connections + 1
R = True
if b-i >= 0 and LW == False and L == False:
if maze[a, b-i] == True:
LW = True
else:
for coor in junctions:
if [coor[1],coor[0]] == [a,b-i]:
connections = connections + 1
L = True
if connections < 2:
eliminated.append([b,a])
return eliminated
#------------------------------------------------------------------------------
def junction_remover(junctions, eliminated):
counter = 0
for index, row in enumerate(junctions):
for erow in (eliminated):
if erow == row:
junctions[index] = -1
counter = counter + 1
for times in range(counter):
junctions.remove(-1)
return junctions, counter
#------------------------------------------------------------------------------
junctions, end = junctions_finder(maze, size, start)
counter = 1
while counter > 0:
eliminated = eliminate_coor(junctions, end, start)
junctions, counter = junction_remover(junctions, eliminated)
start = [start[1],start[0]]
junctions.pop(0)
pyjunc = np.array(junctions)
mu.plot_maze(maze, start=start)
plt.plot(pyjunc[:,0], pyjunc[:,1], 'o')
plt.plot(pyjunc[:,0], pyjunc[:,1]) would connect the dots... Or did you mean you have a bug you can't trace? In your picture it seems there's a beginning, but no end, so it retraces back to the beginning?
plt.plot(pyjunc[:,0], pyjunc[:,1], 'o')
plots the data points in the list with the circle marker 'o'. But you haven't defined a linestyle.
The quickest way to do this is to add it the format shorthand:
plt.plot(pyjunc[:,0], pyjunc[:,1], 'o-')
Which says to use a circle marker and a solid line '-'.
Expanding that out to how matplotlib interprets it, you could write:
plt.plot(pyjunc[:,0], pyjunc[:,1], marker='o', linestyle='-')
You can see the full documentation for plt.plot more ways to customise your plot

"while" loop exiting prematurely (python 3)

The while loop only runs once and exits as though the condition has been met, however, when debugging for whether the condition has been met externally (after the loop) it has not.
Here is my code:
iFile = open("snakein.txt")
line = iFile.readline()
finXStr,finYStr = line.split()
finX = int(finXStr)
finY = int(finYStr)
moves = []
snkX = 0
snkY = 0
while snkX != finX and snkY != finY:
if finX > 0 and finX != snkX:
moves.append("R")
snkX += 1
print("x moves")
elif finX < 0 and finX != snkX:
moves.append("L")
snkX -= 1
print("x moves")
elif finX == snkX:
moves.append("L")
snkX -= 1
print("x moves")
if finY < 0 and moves[-1] == "R":
moves.append("R")
snkY -= 1
print("y moves")
elif finY < 0 and moves[-1] == "L":
moves.append("L")
snkY -= 1
print("y moves")
elif finY > 0 and moves[-1] == "R":
moves.append("L")
snkY += 1
print("y moves")
elif finY > 0 and moves[-1] == "L":
moves.append("R")
snkY += 1
print("y moves")
elif finY == snkY:
moves.appebd("L")
snakeY -= 1
print("y moves")
output = moves
oFile = open("snakeout.txt", "w")
oFile.write(str(output))
The program is trying to make a "snake" move in the most efficient way to a specific target via certain moves, on a "cartesian plane" like setting.
It looks like while snkX != finX or snkY != finY: might make more sense in your context...

IndentationError in the Following Python Script

My code is not running although everything is properly indented and I have been using Python for a while now, so I am no longer in the world of programming. I couldn't find the solution.
def revisedRussianRoulette(doors):
counter = 0
for i in range(0, len(doors), 2):
i = int(i)
if doors[i] == 1 & counter == 0:
counter += 1
elif doors[i] == 1 & counter == 1:
doors[i] = 0
doors[i-2] = 0
doors[i+2] = 0
elif doors[i] == 0 & counter == 1:
doors[i-2] = 0
return doors
n = int(input().strip())
doors = list(map(int, input().strip().split(' ')))
result = revisedRussianRoulette(doors)
print (" ".join(map(str, result)))
The thing I want to do with this code does not matter. I just want to ask if the syntax is correct because I am getting the following error.
C:\Users\lenovo\Desktop\Practice Files>2nd_answer_week_of_code_36.py
File "C:\Users\lenovo\Desktop\PracticeFiles\2nd_answer_week_of_code_36.py", line 13
return doors
^
IndentationError: unindent does not match any outer indentation level
Please, could anyone tell me the solution fast?
EDIT:
The solution provided by Vikas was accurate, although there were no differences between his and my code.
Do indenation like this :
def revisedRussianRoulette(doors):
counter = 0
for i in range(0, len(doors), 2):
i = int(i)
if doors[i] == 1 & counter == 0:
counter += 1
elif doors[i] == 1 & counter == 1:
doors[i] = 0
doors[i-2] = 0
doors[i+2] = 0
elif doors[i] == 0 & counter == 1:
doors[i-2] = 0
return doors
def revisedRussianRoulette(doors):
counter = 0
for i in range(0, len(doors), 2):
i = int(i)
condition_one = doors[i] == 1 & counter == 0
condition_two = doors[i] == 1 & counter == 1
condition_three = doors[i] == 0 & counter == 1
if condition_one:
counter += 1
elif condition_two:
doors[i] = 0
doors[i-2] = 0
doors[i+2] = 0
elif condition_three:
doors[i-2] = 0
return doors
n = int(input().strip())
doors = list(map(int, input().strip().split()))
result = revisedRussianRoulette(doors)
print (" ".join(map(str, result)))

Categories