GoNightハッカソンいってきた

とりあえずライフゲーム書いてみた

GoNight on Zusaar

package main

import (
  "fmt"
  "time"
  "math/rand"
)

const (
  WIDTH = 25
  HEIGHT = 20
)

func IsActive(field []bool, x int, y int) bool {
  if x < 0 || x >= WIDTH  { return false }
  if y < 0 || x >= HEIGHT { return false }
  return field[x + y * HEIGHT]
}

func ShowField(field []bool) {
  for i := 0; i < HEIGHT; i++ {
    start := i*HEIGHT
    row := field[start:start+WIDTH]

    b := make([]byte, WIDTH)
    for i := range(row){
      if row[i]{
        b[i] = '*'
      } else {
        b[i] = ' '
      }
    }
    fmt.Println(string(b[:len(b)]))
  }
}

func CountActive(field []bool, x int, y int) int {
  count := 0
  for dx := -1 ; dx <= 1; dx++ {
    for dy := -1 ; dy <= 1; dy++ {
      // ignore itself
      if dx == 0 && dy == 0 { continue }
      if IsActive(field, x + dx, y + dy){
        count++
      }
    }
  }
  return count
}

func Step(field []bool) []bool {
  next := make([]bool, WIDTH * HEIGHT)

  for x := 0; x < WIDTH; x++ {
    for y := 0; y < HEIGHT; y++ {
      count := CountActive(field, x, y)
      next_active := false

      if IsActive(field, x, y) {
        switch count {
        case 2, 3:
          next_active = true
        }
      } else {
        switch count {
        case 3:
          next_active = true
        }
      }
      next[x + y * HEIGHT] = next_active
    }
  }
  return next
}

func Randomize(field []bool){
  for i := range(field) {
    field[i] = rand.Intn(2) == 0
  }
}

func main() {
  rand.Seed(time.Now().Unix())
  field := make([]bool, WIDTH * HEIGHT)
  Randomize(field)

  for i := 0; i < 10; i++ {
    field = Step(field)
    ShowField(field)
    fmt.Println("=========================")
    time.Sleep(1000 * 1000 * 1000)
  }
}