gpt4 book ai didi

go - 添加列时进行矩阵变异

转载 作者:行者123 更新时间:2023-12-01 22:14:56 25 4
gpt4 key购买 nike

我正在用go玩纸牌游戏。我将游戏中的纸牌放置在一个 slice 矩阵(3行,n列)中,并将普通纸牌放置在牌组中

type Game struct {
Deck []Card `json:"-"`
InPlay [][]Card `json:"in_play,omitempty"`
}

type Card struct {
Number *int64 `json:"number"`
Suit *int64 `json:"suit"`
}

在某些情况下,我想添加另一行卡片
func(g *Game) AddCards() {
g.InPlay[0] = append(g.InPlay[0], g.Deck[0])
g.InPlay[1] = append(g.InPlay[1], g.Deck[1])
g.InPlay[2] = append(g.InPlay[2], g.Deck[2])
g.Deck = g.Deck[3:]
}

最终没有添加新的牌列,而是添加了该列,而且还更改了我正在玩的牌。
1 4 7            1  4 7 10              1 4 7 10
2 5 8 becomes 10 5 8 11 instead of 2 5 8 11
3 6 9 11 6 9 12 3 6 9 12

奇怪的是,如果我添加另一列,它将遵循此模式
1  4 7 10            1  4  7 10 13              1  4 7 10 13
10 5 8 11 becomes 10 13 8 11 14 instead of 10 5 8 11 14
11 6 9 12 11 14 9 12 15 11 6 9 12 15

它仅发生在列中卡片的底部,在新列添加位置的左边3列

编辑

甲板创建与
func New() *Deck {
rand.Seed(time.Now().UnixNano())

deck := Deck{}
cards := []Card{}

// Constant integers
for _, number := range NUMBERS {
for _, suit := range SUITS {
card := Card{
Number: ptr.int64(number), // turns int64 to pointer
Suit: ptr.int64(suit),
}
cards = append(cards, card)
}
}

deck.Cards = cards
deck.Shuffle()
return &deck
}

初始矩阵是用
func (g *Game) Deal() {
inPlay := [][]deck.Card{[]deck.Card{}, []deck.Card{}, []deck.Card{}}
inPlay[0] = g.Deck.Cards[0:4]
inPlay[1] = g.Deck.Cards[4:8]
inPlay[2] = g.Deck.Cards[8:12]

g.InPlay = inPlay
g.Deck.Cards = g.Deck.Cards[12:]
return
}

最佳答案

这是一个简单的方法:

func(c *Card) Copy() *Card {
return &Card{
Number: c.Number,
Suit: c.Suit,
}
}

func(g *Game) AddCards() {
g.InPlay[0] = append(g.InPlay[0], g.Deck[0].Copy())
g.InPlay[1] = append(g.InPlay[1], g.Deck[1].Copy())
g.InPlay[2] = append(g.InPlay[2], g.Deck[2].Copy())
g.Deck = g.Deck[3:]
}

func (g *Game) Deal() {
inPlay := [][]deck.Card{[]deck.Card{}, []deck.Card{}, []deck.Card{}}
for i, row := range inPlay {
for j := 0; j < 3; j++ {
row = append(row, g.Deck.Cards[j].Copy())
}
g.Deck.Cards = g.Deck.Cards[3:]
}
g.InPlay = inPlay
return
}

关于go - 添加列时进行矩阵变异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61049048/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com