This repository has been archived on 2021-10-15. You can view files and clone it, but cannot push or open issues or pull requests.
2020-coding-projects/uno/server/helpers.go

88 lines
1.8 KiB
Go
Raw Normal View History

2020-05-05 20:35:48 +00:00
package main
import (
"math/rand"
"strconv"
)
func GetDefaultDeck() []Card {
cards := make([]Card, 0)
for _, color := range []string{"GREEN", "BLUE", "RED", "YELLOW"} {
for i := 0; i < 10; i++ {
cards = append(cards, Card{
color, strconv.Itoa(i),
})
}
cards = append(cards, Card{
color, "RETURN",
})
cards = append(cards, Card{
color, "BLOCK",
})
cards = append(cards, Card{
color, "DRAW2",
})
}
cards = append(cards, Card{
"BLACK", "CHOOSE",
})
cards = append(cards, Card{
"BLACK", "DRAW4",
})
return cards
}
func GetGame(id string) *Game {
return games[id]
}
func GetRandomCard(cards []Card) *Card {
index := rand.Intn(len(cards))
return &cards[index]
}
func FindCard(cards []Card, color string, value string) (*Card, bool) {
for _, card := range cards {
if card.Color == color && card.Value == value {
return &card, true
}
}
return nil, false
}
func FindOnHand(player *Player, card *Card) int {
for index, handCard := range player.Hand {
if handCard.Color == card.Color && handCard.Value == card.Value {
return index
}
}
return -1
}
func RemoveFromHand(player *Player, index int) []*Card {
player.Hand[len(player.Hand)-1], player.Hand[index] = player.Hand[index], player.Hand[len(player.Hand)-1]
return player.Hand[:len(player.Hand)-1]
}
func InitPlayer(game *Game, player *Player) {
player.Game = game
for i := 0; i < 10; i++ {
player.Hand = append(player.Hand, GetRandomCard(game.AvailableCards))
}
}
func DrawNextPlayer(game *Game, count int) {
nextPlayer := game.GetNextPlayer()
for i := 0; i < count; i++ {
nextPlayer.Hand = append(nextPlayer.Hand, GetRandomCard(game.AvailableCards))
}
game.send("card.drawn", map[string]interface{}{
"playerID": nextPlayer.ID,
"count": count,
})
nextPlayer.send("player.hand", map[string]interface{}{
"cards": nextPlayer.Hand,
})
}