# Can you tell me why the index is out of range?

package main

import (

"fmt"

"math/rand"

)

const(

width = 80

height = 15

)

type Universe [][]bool

func NewUniverse() Universe{

un:=make(Universe,height)

for i:= range un{

un[i]=make([]bool,width)

}

return un

}

func (u Universe)Show() {

for i:=0;i<height;i++ {

for j:=0;j<width;j++{

if u[i][j] {

fmt.Print("*")

} else {

fmt.Print(" ")

}

}

fmt.Println("\n")

}

}

func (u Universe) Seed() {

for count:=0;count<0.25*width*height;count++{

w :=rand.Intn(width)

h :=rand.Intn(height)

if u[h][w]{

continue

} else {

u[h][w]=true

}

}

}

func (u Universe)Alive(x,y int) bool{

return u[y%height][x%width]

}

func (u Universe)Neighbours(x,y int)int{

countnum:=0

if u.Alive(x-1,y-1){

countnum+=1

}

if u.Alive(x,y-1){

countnum+=1

}

if u.Alive(x+1,y-1){

countnum+=1

}

if u.Alive(x-1,y){

countnum+=1

}

if u.Alive(x+1,y){

countnum+=1

}

if u.Alive(x-1,y+1){

countnum+=1

}

if u.Alive(x,y+1){

countnum+=1

}

if u.Alive(x+1,y+1){

countnum+=1

}

return countnum

}

func (u Universe)Next(x,y int)bool {

al:=u.Alive(x,y)

nb:=u.Neighbours(x,y)

if al{

if nb<2{

return false

} else if nb <= 3 {

return true

} else{

return false

}

} else{

if nb==3{

return true

} else{

return false

}

}

}

func step(a,b Universe){

for i:=0;i<height;i++{

for j:=0;j<width;j++{

if a.Next(j,i) {

b[i][j]= true

} else {

b[i][j] = false

}

}

}

a,b=b,a

}

func main() {

u1:=NewUniverse()

fmt.Println("A new universe is created")

u1.Seed()

u1.Show()

u2:=NewUniverse()

for i:=0;i<10;i++{

step(u1,u2)

fmt.Printf("After %v step,the population is like this",i+1)

u1.Show()

}

}