output.go raw

   1  package world
   2  
   3  import (
   4  	"fmt"
   5  	"io"
   6  	"log"
   7  	"os"
   8  )
   9  
  10  // ToFile - Print the world description to a file
  11  func (w *World) ToFile(filename string) {
  12  
  13  	output, err := os.OpenFile(filename, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0755)
  14  	if err != nil {
  15  
  16  		log.Fatal(err)
  17  	}
  18  
  19  	defer output.Close()
  20  
  21  	w.Print(output)
  22  }
  23  
  24  // Print the plain text document that encodes the current in memory data structure to an io.Writer
  25  func (w *World) Print(output io.Writer) {
  26  
  27  	for i := range w.Lookup.Index {
  28  
  29  		// skip the first, empty city in the index
  30  		if i == 0 {
  31  
  32  			continue
  33  		}
  34  
  35  		output.Write([]byte(w.Lookup.Index[i]))
  36  
  37  		for n := 0; n < 4; n++ {
  38  
  39  			neighbour := w.Cities[i].Neighbour[n]
  40  
  41  			// only append the item if it doesn't refer to the empty city
  42  			if neighbour != 0 {
  43  
  44  				fmt.Fprintf(output, " %s=%s", Dirs[n], w.Lookup.Index[neighbour])
  45  			}
  46  		}
  47  
  48  		fmt.Fprint(output, "\n")
  49  	}
  50  
  51  }
  52