-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
243 lines (202 loc) · 7.27 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
package main
import (
"fmt"
"image"
"image/color"
"image/draw"
"image/png"
"io/ioutil"
"math/rand"
"os"
)
var config Config
func main() {
//parse arguments from json file
pwd, err := os.Getwd()
if err != nil {
panic(err)
}
config = readConfig(pwd)
//stop here and ask to continue, else end
//import image as go image
board := importPNG(config.Filepath)
//generate rectangles from input points
firstTile := Tile{config.FirstRect.Origin, config.FirstRect.OppositeCorner}
tileArray := generateTileArray(firstTile, config.NextRectOrigin, config.NumRows, config.NumColumns)
//create window showing image with rectangles highlighted, ask to continue
//save subsets of bingo board into array
subImageArray := generateSubImageArray(tileArray, board)
// add subsets of any extra squares we want to shuffle in
subImageArray = addExtraSquares(config.ExtraSquares, tileArray, subImageArray)
//if we're testing, blank out the board so we can clearly see where the tiles are defined
board = prepareTestBoard(board, config.Test)
r := rand.New(rand.NewSource(config.Seed))
permutations := generatePermutation(r, config.NumRows, config.NumColumns, len(config.Names), len(subImageArray), config.Test)
//loop over list of names
for perm, person := range config.Names {
shuffledArr := permutations[perm]
fmt.Println(person)
fmt.Println(shuffledArr)
//shuffle board
newBoard := shuffleBoard(board, subImageArray, tileArray, shuffledArr)
//save new copy of image
writeImage(newBoard, fmt.Sprintf("%s.png", person))
}
}
// function to read config from file (filename string) Config
func readConfig(pwd string) Config {
configPath := pwd + "/bingo-config.json"
dat, err := ioutil.ReadFile(configPath)
if err != nil {
fmt.Println(err)
fmt.Println("Writing template config file to your current directory")
err = ioutil.WriteFile(configPath, []byte(configTemplate), 0644)
if err != nil {
panic(err.Error())
}
os.Exit(0)
}
// fmt.Println(string(dat))
return parseConfig(string(dat))
}
// function to get photo (filename string) go image
func importPNG(filename string) draw.Image {
existingImageFile, err := os.Open(filename)
if err != nil {
panic(err)
}
defer existingImageFile.Close()
// Alternatively, since we know it is a png already
// we can call png.Decode() directly
loadedImage, err := png.Decode(existingImageFile)
if err != nil {
panic(err)
}
b := loadedImage.Bounds()
m := image.NewRGBA(image.Rect(0, 0, b.Dx(), b.Dy()))
draw.Draw(m, m.Bounds(), loadedImage, b.Min, draw.Src)
return m
}
// addExtraSquares runs through each extra board defined in the config, and for each of these it
// appends the correct number of generated image tiles to the given subImageArray
func addExtraSquares(extras []ExtraSquare, tiles []Tile, subImageArray []draw.Image) []draw.Image {
for _, extraBoard := range extras {
numExtras := extraBoard.NumOfSquares
if numExtras > len(tiles) {
fmt.Println("Your config calls for too many extra squares from a single board")
numExtras = len(tiles)
}
extraBoardImg := importPNG(extraBoard.Filepath)
extraSubImageArray := generateSubImageArray(tiles, extraBoardImg)
subImageArray = append(subImageArray, extraSubImageArray[0:numExtras-1]...)
}
return subImageArray
}
// function to create array of rectangles (first Rectangle, nextCorner Point) []Tiles
func generateTileArray(first Tile, nextCorner image.Point, rows, columns int) []Tile {
origin := first.Origin
tileWidth := first.OppositeCorner.X - first.Origin.X
tileHeight := first.OppositeCorner.Y - first.Origin.Y
gapWidth := nextCorner.X - first.OppositeCorner.X
gapHeight := nextCorner.Y - first.OppositeCorner.Y
fmt.Printf("Tile Width and Height: %d x %d\n", tileWidth, tileHeight)
fmt.Printf("Gap Width and Height: %d x %d\n", gapWidth, gapHeight)
tileArray := []Tile{}
for row := 0; row < rows; row++ {
for column := 0; column < columns; column++ {
// index = 5*row + column
tileOriginX := origin.X + column*(tileWidth+gapWidth)
tileOriginY := origin.Y + row*(tileHeight+gapHeight)
tileOppositeX := tileOriginX + tileWidth
tileOppositeY := tileOriginY + tileHeight
tileArray = append(tileArray, newTile(tileOriginX, tileOriginY, tileOppositeX, tileOppositeY))
}
}
return tileArray
}
func generateSubImageArray(tiles []Tile, img draw.Image) []draw.Image {
imgArray := []draw.Image{}
for _, tile := range tiles {
imgArray = append(imgArray, getSubImage(img, tile))
}
return imgArray
}
// function to create subset of image (image goimage, bounds Rectangle) goimage
func getSubImage(img draw.Image, bounds Tile) (subImage *image.RGBA) {
x, y, _ := bounds.getDimensions()
subImage = image.NewRGBA(image.Rect(0, 0, x, y))
for row := 0; row < y; row++ {
for column := 0; column < x; column++ {
subImage.Set(column, row, img.At(column+bounds.Origin.X, row+bounds.Origin.Y))
}
}
return
}
func writeImage(img draw.Image, filename string) {
// fmt.Println("Attempting to write " + filename)
// outputFile is a File type which satisfies Writer interface
outputFile, err := os.Create(filename)
if err != nil {
panic(err)
}
// Encode takes a writer interface and an image interface
// We pass it the File and the RGBA
png.Encode(outputFile, img)
// Don't forget to close files
outputFile.Close()
}
// takes in a Rand object and dimensions of the board and number of Names, calculates all random permutation of tile indices
func generatePermutation(r *rand.Rand, rows, columns, numNames, numTiles int, testing bool) [][]int {
indices := []int{}
permutations := [][]int{}
useFreespace := false
freespace := 0
for ii := 0; ii < numTiles; ii++ {
indices = append(indices, ii)
if ii < columns*rows {
useFreespace = !useFreespace
}
}
if useFreespace {
freespace = (columns*rows - 1) / 2
fmt.Sprintf("freespace is...%d\n", freespace)
indices = append(indices[:freespace], indices[freespace+1:]...) //slice out the freespace before shuffling
}
for ii := 1; ii <= numNames; ii++ {
shuffledIndices := []int{}
for q, i := range r.Perm(len(indices)) {
if !testing {
shuffledIndices = append(shuffledIndices, indices[i])
} else {
shuffledIndices = append(shuffledIndices, indices[q]) //if testing, we don't shuffle anyone. Therefore, use the q (counter) instead of randomized i
}
}
if useFreespace {
shuffledIndices = append(shuffledIndices, 0) //lengthen the array
copy(shuffledIndices[freespace+1:], shuffledIndices[freespace:])
shuffledIndices[freespace] = freespace
}
permutations = append(permutations, shuffledIndices[:columns*rows])
}
return permutations
}
// function to create new image from subsets (main goimage, tiles []goimage, rects []Rectangle) goimage
func shuffleBoard(board draw.Image, images []draw.Image, tiles []Tile, newIndices []int) draw.Image {
// //loop over array
for newIndex, shuffledIndex := range newIndices {
tile := tiles[newIndex]
subImage := images[shuffledIndex]
//place subimages in new locations
_, _, sr := tile.getDimensions()
r := image.Rectangle{tile.Origin, tile.Origin.Add(sr.Size())}
draw.Draw(board, r, subImage, sr.Min, draw.Src)
}
return board
}
func prepareTestBoard(board draw.Image, testing bool) draw.Image {
if testing {
magenta := color.RGBA{255, 0, 255, 255}
draw.Draw(board, board.Bounds(), &image.Uniform{magenta}, image.ZP, draw.Src)
}
return board
}