github.com/graybobo/golang.org-package-offline-cache@v0.0.0-20200626051047-6608995c132f/x/exp/shiny/example/goban/main.go (about)

     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  // +build ignore
     6  //
     7  // This build tag means that "go install golang.org/x/exp/shiny/..." doesn't
     8  // install this example program. Use "go run main.go board.go xy.go" to run it.
     9  
    10  // Goban is a simple example of a graphics program using shiny.
    11  // It implements a Go board that two people can use to play the game.
    12  // TODO: Improve the main function.
    13  // TODO: Provide more functionality.
    14  package main
    15  
    16  import (
    17  	"flag"
    18  	"image"
    19  	"log"
    20  	"math/rand"
    21  	"time"
    22  
    23  	"golang.org/x/exp/shiny/driver"
    24  	"golang.org/x/exp/shiny/screen"
    25  	"golang.org/x/mobile/event/key"
    26  	"golang.org/x/mobile/event/mouse"
    27  	"golang.org/x/mobile/event/paint"
    28  	"golang.org/x/mobile/event/size"
    29  )
    30  
    31  var scale = flag.Int("scale", 35, "`percent` to scale images (TODO: a poor design)")
    32  
    33  func main() {
    34  	flag.Parse()
    35  
    36  	rand.Seed(int64(time.Now().Nanosecond()))
    37  	board := NewBoard(9, *scale)
    38  
    39  	driver.Main(func(s screen.Screen) {
    40  		w, err := s.NewWindow(nil)
    41  		if err != nil {
    42  			log.Fatal(err)
    43  		}
    44  		defer w.Release()
    45  
    46  		var b screen.Buffer
    47  		defer func() {
    48  			if b != nil {
    49  				b.Release()
    50  			}
    51  		}()
    52  
    53  		for e := range w.Events() {
    54  			switch e := e.(type) {
    55  			case mouse.Event:
    56  				if e.Direction == mouse.DirRelease && e.Button != 0 {
    57  					board.click(b.RGBA(), int(e.X), int(e.Y), int(e.Button))
    58  					w.Send(paint.Event{})
    59  				}
    60  
    61  			case key.Event:
    62  				if e.Code == key.CodeEscape {
    63  					return
    64  				}
    65  
    66  			case paint.Event:
    67  				w.Upload(image.Point{}, b, b.Bounds())
    68  				w.Publish()
    69  
    70  			case size.Event:
    71  				// TODO: Set board size.
    72  				if b != nil {
    73  					b.Release()
    74  				}
    75  				b, err = s.NewBuffer(e.Size())
    76  				if err != nil {
    77  					log.Fatal(err)
    78  				}
    79  				render(b.RGBA(), board)
    80  
    81  			case error:
    82  				log.Print(e)
    83  			}
    84  		}
    85  	})
    86  }
    87  
    88  func render(m *image.RGBA, board *Board) {
    89  	board.Draw(m)
    90  }