We've been tasked with writing a program which simulates a 1-dimensional Game of Life. We are supposed to create a spider pattern. I've gotten this to work, however there needs to be an obscene amount of spaces in the first string initialisation for it to print the entire figure, as each line loses 2 spaces. What should the range in my for-loop be for it to print the entire figure, regardless of the initialisation?
Note: We are not supposed to use arrays, matrices or any other clever methods or approaches. I know of them, but they are only expecting if-statements, while/for -loops, and variables (primarily).
I've written this code:
def main():
a=" ****** "
print(a)
empty=False
while (empty==False):
b=""
for i in range(len(a)-2):
alive_cells=0
if (i==0):
if(a[i+1]=="*"):
alive_cells+=1
if(a[i+2]=="*"):
alive_cells+=1
elif (i==1):
if(a[i-1]=="*"):
alive_cells+=1
if(a[i+1]=="*"):
alive_cells+=1
if(a[i+2]=="*"):
alive_cells+=1
else:
if(a[i-2]=="*"):
alive_cells+=1
if(a[i-1]=="*"):
alive_cells+=1
if(a[i+1]=="*"):
alive_cells+=1
if(a[i+2]=="*"):
alive_cells+=1
if (a[i]==" " and (alive_cells==1 or alive_cells==4 or alive_cells==0)):
b+=" "
elif(a[i]==" " and (alive_cells==2 or alive_cells==3)):
b+="*"
elif(a[i]=="*" and (alive_cells==0 or alive_cells==1 or alive_cells==3)):
b+=" "
elif(a[i]=="*" and (alive_cells==2 or alive_cells==4)):
b+="*"
if (b.isspace()==True):
empty=True
break
a=b
print(a)
main()
Which prints the following output:
******
** ** **
* * ** * *
********
** ****
* *
*
It's supposed to print this:
******
** ** **
* * ** * *
********
** **** **
* * * *
* *
Instead of adding those extra spaces at the start, I'd just append three spaces each round. Then you also don't need the extra edge case distinction:
def main():
a=" ******"
print(a)
empty=False
while (empty==False):
b=""
a += " "
for i in range(len(a)-2):
alive_cells=0
if(a[i-2]=="*"):
alive_cells+=1
if(a[i-1]=="*"):
alive_cells+=1
if(a[i+1]=="*"):
alive_cells+=1
if(a[i+2]=="*"):
alive_cells+=1
if (a[i]==" " and (alive_cells==1 or alive_cells==4 or alive_cells==0)):
b+=" "
elif(a[i]==" " and (alive_cells==2 or alive_cells==3)):
b+="*"
elif(a[i]=="*" and (alive_cells==0 or alive_cells==1 or alive_cells==3)):
b+=" "
elif(a[i]=="*" and (alive_cells==2 or alive_cells==4)):
b+="*"
if (b.isspace()==True):
empty=True
break
a=b
print(a)
main()
Output (Attempt This Online!):
******
** ** **
* * ** * *
********
** **** **
* * * *
* *