src

Go monorepo.
git clone git://code.dwrz.net/src
Log | Files | Refs

direction.go (964B)


      1 package direction
      2 
      3 import (
      4 	"math/rand"
      5 	"time"
      6 )
      7 
      8 type Direction int
      9 
     10 const (
     11 	Down Direction = iota
     12 	Left
     13 	Right
     14 	Up
     15 )
     16 
     17 func (d Direction) Opposite() Direction {
     18 	switch d {
     19 	case Down:
     20 		return Up
     21 	case Left:
     22 		return Right
     23 	case Right:
     24 		return Left
     25 	case Up:
     26 		return Down
     27 	default:
     28 		return d
     29 	}
     30 }
     31 
     32 func (d Direction) String() string {
     33 	switch d {
     34 	case Down:
     35 		return "down"
     36 	case Left:
     37 		return "left"
     38 	case Right:
     39 		return "right"
     40 	case Up:
     41 		return "up"
     42 	default:
     43 		return ""
     44 	}
     45 }
     46 
     47 var (
     48 	directions = [4]Direction{Down, Left, Right, Up}
     49 	random     = rand.New(rand.NewSource(time.Now().UnixNano()))
     50 )
     51 
     52 func Directions() [4]Direction {
     53 	return [4]Direction{Down, Left, Right, Up}
     54 }
     55 
     56 func Random() Direction {
     57 	return directions[random.Intn(len(directions))]
     58 }
     59 
     60 func RandomDirections() [4]Direction {
     61 	var dirs = [...]Direction{Down, Left, Right, Up}
     62 
     63 	random.Shuffle(len(dirs), func(i, j int) {
     64 		dirs[i], dirs[j] = dirs[j], dirs[i]
     65 	})
     66 
     67 	return dirs
     68 }