Files
work_cation/views/gamesViews.go
T

126 lines
2.7 KiB
Go

package views
import (
"fmt"
"fyne.io/fyne/v2"
"fyne.io/fyne/v2/container"
"fyne.io/fyne/v2/dialog"
"fyne.io/fyne/v2/theme"
"fyne.io/fyne/v2/widget"
"slices"
"sync"
)
func TenChinaGameView() {
myApp := fyne.CurrentApp()
myWindow := myApp.NewWindow("Game")
gridWrap := container.NewGridWrap(fyne.NewSize(100, 100))
game := NewTenGame(2, func(i int) {
fmt.Println("win", i)
dialog.ShowInformation("游戏结束", fmt.Sprintf("%d 获得胜利", i), myWindow)
//myWindow.Close()
})
for _, i := range game.Items {
gridWrap.Add(container.NewBorder(nil, nil, nil, nil, i))
}
myWindow.SetContent(container.NewScroll(gridWrap))
myWindow.Resize(fyne.NewSize(320, 318))
myWindow.CenterOnScreen()
myWindow.Show()
}
type TenGame struct {
lock sync.Mutex
playerMax int
CurrentRoundPlayer int
players [][]int
Items []*widget.Button
winCallback func(int)
}
func NewTenGame(playerMax int, winCallback func(int)) *TenGame {
game := &TenGame{
playerMax: playerMax,
CurrentRoundPlayer: 0,
players: make([][]int, playerMax),
winCallback: winCallback,
}
var items = make([]*widget.Button, 9)
for i := 0; i < 9; i++ {
var itemIndex = i
var item = widget.NewButton("", func() {
game.Play(0, itemIndex)
})
item.SetIcon(theme.FyneLogo())
items[i] = item
}
game.Items = items
return game
}
func (t *TenGame) Play(userIndex int, pos int) error {
t.lock.Lock()
defer t.lock.Unlock()
//if t.CurrentRoundPlayer != userIndex {
// return errors.New("not your turn")
//}
t.play(pos)
t.CurrentRoundPlayer++
if t.CurrentRoundPlayer+1 > t.playerMax {
t.CurrentRoundPlayer = 0
}
return nil
}
/*
1, 2, 3
4, 5, 6
7, 8, 9
*/
func (t *TenGame) play(pos int) {
// TODO
playerIntList := t.players[t.CurrentRoundPlayer]
playerIntList = append(playerIntList, pos)
// 刷新数据
if t.CurrentRoundPlayer == 1 {
t.Items[pos].SetIcon(theme.ConfirmIcon())
} else {
t.Items[pos].SetIcon(theme.CancelIcon())
}
// check 胜利 判断
slices.Sort(playerIntList)
t.players[t.CurrentRoundPlayer] = playerIntList
if t.winCheck(playerIntList) {
t.winCallback(t.CurrentRoundPlayer)
}
}
func (t *TenGame) winCheck(playerIntList []int) bool {
fmt.Println("playerIntList:", playerIntList)
if isArithmeticSequence(playerIntList, 1) ||
isArithmeticSequence(playerIntList, 2) ||
isArithmeticSequence(playerIntList, 3) ||
isArithmeticSequence(playerIntList, 4) {
return true
}
return false
}
func isArithmeticSequence(numbers []int, diff int) bool {
if len(numbers) <= 2 {
return false
}
for i := 1; i < len(numbers); i++ {
if numbers[i]-numbers[i-1] != diff {
return false
}
}
return true
}