GO 小游戏在线试水
Playground
三子棋
package mainimport ("cogentcore.org/core/core""cogentcore.org/core/events""cogentcore.org/core/styles""cogentcore.org/core/styles/units"
)type user struct {Username stringPassword string
}type item struct {Done bool `display:"checkbox"`Task string
}func main() {b := core.NewBody()//tf := core.NewTextField(b).SetPlaceholder("Name")//tf.AddContextMenu(func(m *core.Scene) {// core.NewButton(m).SetText("Build")// core.NewButton(m).SetText("Run")//})//core.NewButton(b).SetText("Hello World!").OnClick(func(e events.Event) {// core.MessageSnackbar(b, "Hello, "+tf.Text())//})u := &user{}pg := core.NewPages(b)pg.AddPage("Sign in", func(pg *core.Pages) {core.NewForm(pg).SetStruct(u)core.NewButton(pg).SetText("Sign in").OnClick(func(e events.Event) {pg.Open("Home")})})pg.AddPage("Home", func(pg *core.Pages) {core.NewText(pg).SetText("Welcom, " + u.Username).SetType(core.TextHeadlineSmall)current := "X"squares := [9]string{}status := core.NewText(pg)status.Updater(func() {sets := [][3]int{{0, 1, 2}, {3, 4, 5}, {6, 7, 8}, {0, 3, 6}, {1, 4, 7}, {2, 5, 8}, {0, 4, 8}, {2, 4, 6},}for _, set := range sets {if squares[set[0]] != "" && squares[set[0]] == squares[set[1]] && squares[set[1]] == squares[set[2]] {status.SetText(squares[set[0]] + " wins!")current = ""return}}status.SetText("Next Player:" + current)})grid := core.NewFrame(pg)grid.Styler(func(s *styles.Style) {s.Display = styles.Grids.Columns = 3})for i := range 9 {bt := core.NewButton(grid).SetType(core.ButtonAction)bt.Styler(func(s *styles.Style) {s.Border.Width.Set(units.Dp(1))s.Border.Radius.Zero()s.Min.Set(units.Em(2))})bt.OnClick(func(e events.Event) {if squares[i] != "" {return}squares[i] = currentif current == "X" {current = "O"} else {current = "X"}bt.Update()status.Update()})bt.Updater(func() {bt.SetText(squares[i])})}core.NewButton(pg).SetText("Reset").OnClick(func(e events.Event) {squares = [9]string{}current = "X"grid.Update()})core.NewButton(pg).SetText("Sign out").OnClick(func(e events.Event) {*u = user{}pg.Open("Sign in")})})//items := []item{{Task: "Code"}, {Task: "Eat"}}//var table *core.Table//core.NewButton(b).SetText("Add").SetIcon(icons.Add).OnClick(func(e events.Event) {// table.NewAt(0)//})//table = core.NewTable(b).SetSlice(&items)b.RunMainWindow()
}
效果
参考
https://dl.google.com/go/go1.24.3.windows-amd64.zip
Playground
GitHub - cogentcore/core: A free and open source framework for building powerful, fast, elegant 2D and 3D apps that run on macOS, Windows, Linux, iOS, Android, and web with a single Go codebase, allowing you to Code Once, Run Everywhere.
cogentcore: Cogent Core 是一个免费的开源框架,用于构建功能强大、快速且优雅的 2D 和 3D 应用