Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
413 lines (374 loc) · 11.2 KB
/
Copy pathmain.go
File metadata and controls
413 lines (374 loc) · 11.2 KB
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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
/*
Copyright © 2026, Vitalii Tereshchuk | DOTOCA.NET All rights reserved.
Homepage: https://dotoca.net/optigrid
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"encoding/json"
"fmt"
"image/color"
"log"
"os"
"path/filepath"
"sort"
"time"
"github.com/hajimehoshi/ebiten/v2"
"github.com/hajimehoshi/ebiten/v2/ebitenutil"
"github.com/hajimehoshi/ebiten/v2/inpututil"
"github.com/hajimehoshi/ebiten/v2/vector"
)
// --- CONSTANTS ---
const (
GridSub = 4 // Visual sub-divisions
AnimSpeed = 0.08
SlideTime = 5.0
SsaaScale = 2.0
CellSize = 40 // Square cell size in pixels
MinGrid = 8
MaxGrid = 50
)
// --- PALETTE ---
var (
ColorBgBlue = color.RGBA{63, 81, 151, 255}
ColorBgLight = color.RGBA{238, 234, 214, 255}
ColorGridGray = color.RGBA{160, 160, 160, 255}
BallDark = color.RGBA{26, 31, 74, 255}
BallWhite = color.RGBA{220, 225, 235, 255}
BallGlare = color.RGBA{255, 255, 255, 255}
BallOutline = color.RGBA{20, 20, 40, 255}
)
// Ball defines properties for a single animated dot
type Ball struct {
x, y, tx, ty float32
color color.RGBA
alpha float32
}
// Update interpolates position and transparency
func (b *Ball) Update(tx, ty float32, visible bool) {
b.tx, b.ty = tx, ty
b.x += (b.tx - b.x) * AnimSpeed
b.y += (b.ty - b.y) * AnimSpeed
targetAlpha := float32(0)
if visible {
targetAlpha = 255
}
b.alpha += (targetAlpha - b.alpha) * AnimSpeed
}
// Cell manages logic for a single grid tile
type Cell struct {
state int
balls [4]*Ball
}
// Game maintains the core application state
type Game struct {
cols int
rows int
cells [][]*Cell
autoMode bool
lastSwitch time.Time
currentIdx int
currentSlotPos int
availableSlots []int
offscreen *ebiten.Image
statusText string
statusTimer time.Time
}
// getExeDir returns the absolute path to the directory where the binary is located
func getExeDir() string {
exePath, err := os.Executable()
if err != nil {
return "."
}
return filepath.Dir(exePath)
}
// NewGame initializes the grid and default settings
func NewGame() *Game {
g := &Game{
cols: 9,
rows: 21,
lastSwitch: time.Now(),
statusText: "Ready. Slots: 1-0 | Resize: [ / ] , - / + | Auto: A",
}
g.resizeGrid()
ebiten.SetWindowSize(g.cols*CellSize, g.rows*CellSize)
return g
}
func (g *Game) resizeGrid() {
g.cells = make([][]*Cell, g.rows)
for r := 0; r < g.rows; r++ {
g.cells[r] = make([]*Cell, g.cols)
for c := 0; c < g.cols; c++ {
isBlue := (r+c)%2 == 0
ballCol := BallDark
if isBlue {
ballCol = BallWhite
}
g.cells[r][c] = &Cell{}
for i := 0; i < 4; i++ {
g.cells[r][c].balls[i] = &Ball{color: ballCol}
}
}
}
g.setStatus(fmt.Sprintf("Grid: %dx%d", g.cols, g.rows))
}
func (g *Game) setStatus(msg string) {
g.statusText = msg
g.statusTimer = time.Now().Add(3 * time.Second)
}
func (g *Game) scanAvailableSlots() {
dir := getExeDir()
pattern := filepath.Join(dir, "slot_*.json")
files, _ := filepath.Glob(pattern)
g.availableSlots = nil
for _, f := range files {
name := filepath.Base(f)
var num int
fmt.Sscanf(name, "slot_%d.json", &num)
g.availableSlots = append(g.availableSlots, num)
}
sort.Ints(g.availableSlots)
}
// Update handles input, physics, and pattern switching
func (g *Game) Update() error {
cw, ch := float32(CellSize), float32(CellSize)
// 1. Handle Mouse Clicks
if inpututil.IsMouseButtonJustPressed(ebiten.MouseButtonLeft) {
mx, my := ebiten.CursorPosition()
c, r := mx/int(cw), my/int(ch)
if c >= 0 && c < g.cols && r >= 0 && r < g.rows {
g.cells[r][c].state = (g.cells[r][c].state + 1) % 8
g.autoMode = false
}
}
// 2. Handle Global Keyboard Actions
if inpututil.IsKeyJustPressed(ebiten.KeyA) {
g.autoMode = !g.autoMode
if g.autoMode {
g.scanAvailableSlots()
g.currentSlotPos = -1
}
g.setStatus(fmt.Sprintf("Auto Mode: %v", g.autoMode))
}
if inpututil.IsKeyJustPressed(ebiten.KeyC) {
for r := 0; r < g.rows; r++ {
for c := 0; c < g.cols; c++ {
g.cells[r][c].state = 0
}
}
g.setStatus("Board Cleared")
}
// Grid resize: horizontal
if inpututil.IsKeyJustPressed(ebiten.KeyBracketLeft) {
if g.cols > MinGrid {
g.cols--
g.resizeGrid()
ebiten.SetWindowSize(g.cols*CellSize, g.rows*CellSize)
}
}
if inpututil.IsKeyJustPressed(ebiten.KeyBracketRight) {
if g.cols < MaxGrid {
g.cols++
g.resizeGrid()
ebiten.SetWindowSize(g.cols*CellSize, g.rows*CellSize)
}
}
// Grid resize: vertical
if inpututil.IsKeyJustPressed(ebiten.KeyMinus) {
if g.rows > MinGrid {
g.rows--
g.resizeGrid()
ebiten.SetWindowSize(g.cols*CellSize, g.rows*CellSize)
}
}
if inpututil.IsKeyJustPressed(ebiten.KeyEqual) {
if g.rows < MaxGrid {
g.rows++
g.resizeGrid()
ebiten.SetWindowSize(g.cols*CellSize, g.rows*CellSize)
}
}
// 3. Pattern Saving and Loading (1-9, 0)
for k := ebiten.Key1; k <= ebiten.Key9; k++ {
if inpututil.IsKeyJustPressed(k) {
slotIdx := int(k - ebiten.Key1 + 1)
if ebiten.IsKeyPressed(ebiten.KeyShift) {
g.saveSlot(slotIdx)
} else {
g.loadSlot(slotIdx)
g.autoMode = false
}
}
}
if inpututil.IsKeyJustPressed(ebiten.Key0) {
if ebiten.IsKeyPressed(ebiten.KeyShift) {
g.saveSlot(10)
} else {
g.loadSlot(10)
g.autoMode = false
}
}
// 4. Auto-mode playlist cycling
if g.autoMode && time.Since(g.lastSwitch).Seconds() > SlideTime && len(g.availableSlots) > 0 {
g.currentSlotPos = (g.currentSlotPos + 1) % len(g.availableSlots)
g.currentIdx = g.availableSlots[g.currentSlotPos]
g.loadSlot(g.currentIdx)
g.lastSwitch = time.Now()
}
// 5. Physics: Update all balls
for r := 0; r < g.rows; r++ {
for c := 0; c < g.cols; c++ {
cell := g.cells[r][c]
bx, by := float32(c)*cw, float32(r)*ch
midX, midY := bx+cw/2, by+ch/2
sw, sh := cw/GridSub, ch/GridSub
pts := [4][2]float32{
{bx + sw/2, by + sh/2}, {bx + cw - sw/2, by + ch - sh/2},
{bx + cw - sw/2, by + sh/2}, {bx + sw/2, by + ch - sh/2},
}
for i, b := range cell.balls {
vis := (cell.state == 1 && i < 2) ||
(cell.state == 2 && i >= 2) ||
(cell.state == 3 && (i == 1 || i == 2)) || // справа
(cell.state == 4 && (i == 0 || i == 3)) || // слева
(cell.state == 5 && (i == 0 || i == 2)) || // сверху
(cell.state == 6 && (i == 1 || i == 3)) || // снизу
(cell.state == 7)
targetX, targetY := midX, midY
if vis {
targetX, targetY = pts[i][0], pts[i][1]
}
b.Update(targetX, targetY, vis)
}
}
}
return nil
}
// Draw renders the frame
func (g *Game) Draw(screen *ebiten.Image) {
winW := g.cols * CellSize
winH := g.rows * CellSize
// Offscreen buffer for SSAA
if g.offscreen == nil || g.offscreen.Bounds().Dx() != winW*SsaaScale || g.offscreen.Bounds().Dy() != winH*SsaaScale {
g.offscreen = ebiten.NewImage(winW*SsaaScale, winH*SsaaScale)
}
canvas := g.offscreen
canvas.Fill(ColorBgLight)
s := float32(SsaaScale)
cw, ch := float32(CellSize), float32(CellSize)
// 1. Draw Checkerboard
for r := 0; r < g.rows; r++ {
for c := 0; c < g.cols; c++ {
if (r+c)%2 == 0 {
vector.DrawFilledRect(canvas, float32(c)*cw*s, float32(r)*ch*s, cw*s, ch*s, ColorBgBlue, true)
}
}
}
// 2. Draw Grid
sw, sh := cw/GridSub, ch/GridSub
for i := 0; i <= g.cols*GridSub; i++ {
vector.StrokeLine(canvas, float32(i)*sw*s, 0, float32(i)*sw*s, float32(winH)*s, 1*s, ColorGridGray, true)
}
for i := 0; i <= g.rows*GridSub; i++ {
vector.StrokeLine(canvas, 0, float32(i)*sh*s, float32(winW)*s, float32(i)*sh*s, 1*s, ColorGridGray, true)
}
// 3. Draw Balls
for r := 0; r < g.rows; r++ {
for c := 0; c < g.cols; c++ {
for _, b := range g.cells[r][c].balls {
if b.alpha < 5 {
continue
}
bc := b.color
bc.A = uint8(b.alpha)
px, py, radius := b.x*s, b.y*s, float32(6*s)
vector.DrawFilledCircle(canvas, px, py, radius, bc, true)
vector.StrokeCircle(canvas, px, py, radius, 1*s, BallOutline, true)
vector.DrawFilledCircle(canvas, px-radius/3, py-radius/3, radius/4, BallGlare, true)
}
}
}
// 4. Blit to Screen with Resize Support
op := &ebiten.DrawImageOptions{}
w, h := screen.Size()
sx := float64(w) / float64(winW*SsaaScale)
sy := float64(h) / float64(winH*SsaaScale)
op.GeoM.Scale(sx, sy)
op.Filter = ebiten.FilterLinear
screen.DrawImage(canvas, op)
// 5. Draw UI Text (Status Bar)
if time.Now().Before(g.statusTimer) || g.autoMode {
msg := g.statusText
if g.autoMode {
msg = fmt.Sprintf("[AUTO] Slot: %d", g.currentIdx)
}
ebitenutil.DebugPrintAt(screen, msg, 10, h-25)
}
}
func (g *Game) saveSlot(idx int) {
data := make([][]int, g.rows)
for r := 0; r < g.rows; r++ {
data[r] = make([]int, g.cols)
for c := 0; c < g.cols; c++ {
data[r][c] = g.cells[r][c].state
}
}
bytes, _ := json.Marshal(data)
path := filepath.Join(getExeDir(), fmt.Sprintf("slot_%d.json", idx))
err := os.WriteFile(path, bytes, 0644)
if err == nil {
g.setStatus(fmt.Sprintf("Saved Slot %d", idx))
} else {
g.setStatus("Save Error!")
}
}
func (g *Game) loadSlot(idx int) {
path := filepath.Join(getExeDir(), fmt.Sprintf("slot_%d.json", idx))
bytes, err := os.ReadFile(path)
if err != nil {
g.setStatus(fmt.Sprintf("Slot %d: File Not Found", idx))
return
}
var data [][]int
if err := json.Unmarshal(bytes, &data); err == nil {
for r := 0; r < g.rows && r < len(data); r++ {
for c := 0; c < g.cols && c < len(data[r]); c++ {
g.cells[r][c].state = data[r][c]
}
}
g.setStatus(fmt.Sprintf("Loaded Slot %d", idx))
}
}
// Layout handles scaling logic for resizing windows
func (g *Game) Layout(w, h int) (int, int) {
return g.cols * CellSize, g.rows * CellSize
}
func main() {
fmt.Println("─────────────────────────────────────────────────")
fmt.Println("'Grid' Optical Illusion - Pattern Studio")
fmt.Println("Copyright © 2026, Vitalii Tereshchuk | DOTOCA.NET")
fmt.Println("Homepage: https://dotoca.net/optigrid")
fmt.Println("─────────────────────────────────────────────────")
fmt.Println("Controls:")
fmt.Println(" Click on cell - Toggle pattern")
fmt.Println(" 1-9, 0 - Load slot")
fmt.Println(" Shift+1-0 - Save slot")
fmt.Println(" A - Toggle auto mode")
fmt.Println(" C - Clear board")
fmt.Println(" [ / ] - Resize horizontal")
fmt.Println(" - / + - Resize vertical")
fmt.Println("─────────────────────────────────────────────────")
ebiten.SetWindowTitle("'Grid' Optical Illusion - Pattern Studio")
ebiten.SetWindowResizingMode(ebiten.WindowResizingModeEnabled)
if err := ebiten.RunGame(NewGame()); err != nil {
log.Fatal(err)
}
}