Debian Codegraph @

shiny/example/goban/main.go

raw symbols SCIP
1 // Copyright 2015 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 //go:build example
6 // +build example
7
8 //
9 // This build tag means that "go install golang.org/x/exp/shiny/..." doesn't
10 // install this example program. Use "go run main.go board.go xy.go" to run it
11 // or "go install -tags=example" to install it.
12
13 // Goban is a simple example of a graphics program using shiny.
14 // It implements a Go board that two people can use to play the game.
15 // TODO: Improve the main function.
16 // TODO: Provide more functionality.
17 package main
18
19 import (
20 "flag"
21 "image"
22 "log"
23 "math/rand"
24 "time"
25
26 "golang.org/x/exp/shiny/driver"
27 "golang.org/x/exp/shiny/screen"
28 "golang.org/x/mobile/event/key"
29 "golang.org/x/mobile/event/lifecycle"
30 "golang.org/x/mobile/event/mouse"
31 "golang.org/x/mobile/event/paint"
32 "golang.org/x/mobile/event/size"
33 )
34
35 var scale = flag.Int("scale", 35, "`percent` to scale images (TODO: a poor design)")
36
37 func main() {
38 flag.Parse()
39
40 rand.Seed(int64(time.Now().Nanosecond()))
41 board := NewBoard(9, *scale)
42
43 driver.Main(func(s screen.Screen) {
44 w, err := s.NewWindow(&screen.NewWindowOptions{
45 Title: "Goban Shiny Example",
46 })
47 if err != nil {
48 log.Fatal(err)
49 }
50 defer w.Release()
51
52 var b screen.Buffer
53 defer func() {
54 if b != nil {
55 b.Release()
56 }
57 }()
58
59 for {
60 switch e := w.NextEvent().(type) {
61 case lifecycle.Event:
62 if e.To == lifecycle.StageDead {
63 return
64 }
65
66 case key.Event:
67 if e.Code == key.CodeEscape {
68 return
69 }
70
71 case mouse.Event:
72 if e.Direction != mouse.DirRelease {
73 break
74 }
75
76 // Re-map control-click to middle-click, etc, for computers with one-button mice.
77 if e.Modifiers&key.ModControl != 0 {
78 e.Button = mouse.ButtonMiddle
79 } else if e.Modifiers&key.ModAlt != 0 {
80 e.Button = mouse.ButtonRight
81 } else if e.Modifiers&key.ModMeta != 0 {
82 e.Button = mouse.ButtonMiddle
83 }
84
85 if board.click(b.RGBA(), int(e.X), int(e.Y), int(e.Button)) {
86 w.Send(paint.Event{})
87 }
88
89 case paint.Event:
90 w.Upload(image.Point{}, b, b.Bounds())
91 w.Publish()
92
93 case size.Event:
94 // TODO: Set board size.
95 if b != nil {
96 b.Release()
97 }
98 b, err = s.NewBuffer(e.Size())
99 if err != nil {
100 log.Fatal(err)
101 }
102 render(b.RGBA(), board)
103
104 case error:
105 log.Print(e)
106 }
107 }
108 })
109 }
110
111 func render(m *image.RGBA, board *Board) {
112 board.Draw(m)
113 }