Go Fish/Go: Difference between revisions

Less idiosyncratic and gofmt'ed.
No edit summary
(Less idiosyncratic and gofmt'ed.)
Line 5:
package main
 
import "fmt"(
"fmt"
import "math/rand"
"math/rand"
import "sort"
"sort"
import "time"
"time"
)
 
var kCardscards = [13]string{"2", "3", "4", "5", "6", "7", "8", "9",
"10", "J", "Q", "K", "A"}
 
//GoFishGame Stores the game state.
type GoFishGame struct {
_Handshands [][]string
_Deckdeck []string
_Turnturn int
_Scoresscores []int
}
 
// checkForBooks looks for fours of a kind
/*
*// Weand scorescores a pointthem if we have fourthem.
*// ofIf awe kind.run Soout of cards, we sortdraw our handmore.
func (gm *GoFishGame) checkForBooks() {
* and if we have four in a row of
sort.Strings(gm.hands[gm.turn])
* the same pip, we take them out
prev := ""
* of our hand and get a point.
count := 1
*/
for _, card := range gm.hands[gm.turn] {
func (self *GoFishGame) checkForBooks() {
if card == prev {
sort.Strings(self._Hands[0])
count++
sort.Strings(self._Hands[1])
if count == 4 {
tPrev := ""
fmt.Printf("Book of %s.\n", card)
tCount := 1
gm.stealCards(card, gm.turn)
for _, tChar := range self._Hands[self._Turn] {
gm.scores[gm.turn]++
if tChar == tPrev {
if gm.isHandEmpty() {
tCount++
gm.drawCard()
if tCount == 4 {
fmt.Println("Book of", tChar)
self.removeOccurences(tChar, self._Turn)
self._Scores[self._Turn]++
if self.isHandEmpty() {
self.drawCard()
}
}
} else {
tCountcount = 1
}
tPrevprev = tCharcard
}
}
 
// drawCard takes a card from the deck
/*
*// Safelyadding drawit ato card and put itthe incurrent yourplayer's hand.
func (gm *GoFishGame) drawCard() {
*/
if !gm.isDeckEmpty() {
func (self *GoFishGame) drawCard() {
card := gm.deck[0]
if !self.isDeckEmpty() {
tCardgm.deck := selfgm._Deckdeck[01:]
if gm.turn == 0 {
self._Deck = self._Deck[1:]
fmt.Printf("You drew a %s.\n", card)
if self._Turn == 0 {
fmt.Println("Drew", tCard)
}
selfgm._Handshands[selfgm._Turnturn] = append(selfgm._Handshands[selfgm._Turnturn], tCardcard)
//Check for books
selfgm.checkForBooks()
}
}
 
// endPly ends the current person's turn.
/*
// It then either calls the next person's
* See if the game has ended.
// turn or prints a game over message.
* Else, let the next person go.
func (gm *GoFishGame) endPly() {
*/
gameOver := gm.isGameOver()
func (self *GoFishGame) endPly() {
if gameOver {
tGameOver := self.isGameOver()
gm.printGameOverMessage()
if tGameOver {
} else if gm.turn == 1 {
self.printGameOverMessage()
gm.playerTurn(getPickComputer)
} else if self._Turn == 1 {
self.playerTurn(getPickComputer)
} else {
selfgm.playerTurn(getPickUser)
}
}
 
// getPickComputer handles the computer's card choices.
/*
// We do the moderately smart thing of pick a random
* Pick a card that the computer has
// card from our hand
* randomly.
func getPickComputer(gm *GoFishGame) string {
*/
hand := gm.hands[1]
func getPickComputer(self *GoFishGame) string {
choice := "A"
tHand := self._Hands[1]
if len(hand) > 0 {
tChoice := "A"
choice = hand[rand.Intn(len(hand))]
if len(tHand) > 0 {
tChoice = tHand[rand.Intn(len(tHand))]
}
fmt.PrintlnPrintf("Computer picks %s.\n", tChoicechoice)
return tChoicechoice
}
 
// getPickUser gets the user's move.
/*
// If it's not valid, then the user just wastes
* Ask the user what they want to pick.
// their turn.
*/
func getPickUser(selfgm *GoFishGame) string {
fmt.Println("What card do you want?")
var tCardcard string
fmt.Scanf("%s\n", &tCardcard)
return tCardcard
}
 
// isDeckEmpty returns if the deck is empty.
/*
func (gm *GoFishGame) isDeckEmpty() bool {
* Convenience function.
return len(gm.deck) == 0
*/
func (self *GoFishGame) isDeckEmpty() bool {
return len(self._Deck) == 0
}
 
// isHandEmpty returns if the current player's hand is empty.
/*
func (gm *GoFishGame) isHandEmpty() bool {
* Convenience function.
return len(gm.hands[gm.turn]) == 0
*/
func (self *GoFishGame) isHandEmpty() bool {
return len(self._Hands[self._Turn]) == 0
}
 
// isGameOver returns if the game is over.
/*
*// TheThis game is overhappens when all 13 pips have been made into sets.
func (gm *GoFishGame) isGameOver() bool {
* been made into sets.
return gm.scores[0]+gm.scores[1] == 13
*/
func (self *GoFishGame) isGameOver() bool {
return self._Scores[0]+self._Scores[1] == 13
}
 
// makeDeck makes a deck.
/*
*// Make aThe deck containsis 452 copiescards with 4 of each pip.
* card and shuffle it.
*/
func makeDeck() []string {
rand.Seed(time.Now().UTC().UnixNano())
tDeckdeck := make([]string, 52)
tPermperm := rand.Perm(52)
for tIndexindx := range tPermperm {
tVal := tPermperm[tIndexindx]
tCardcard := kCardscards[tVal/4]
tDeckdeck[tIndexindx] = tCardcard
}
return tDeckdeck
}
 
// opponentHas returns if the opponent's hand has a card.
/*
func (gm *GoFishGame) opponentHas(find string) bool {
* returns true if the opponent's hand contains an aCard.
for _, card := range gm.hands[(gm.turn+1)%2] {
*/
if card == find {
func (self *GoFishGame) opponentHas(aCard string) bool {
for _, tCard := range self._Hands[(self._Turn+1)%2] {
if tCard == aCard {
return true
}
Line 155 ⟶ 140:
}
 
// playerTurn handles the major game logic.
/*
*// HandleIt's used for both the playersplayer's and computerscomputer's turns.,
*// Differenceswith betweenthe themdifferent arebehavior handled by checkingthe getPick param.
func (gm *GoFishGame) playerTurn(getPick func(*GoFishGame) string) {
* whose turn it is manually and through the getPick
opponent := (gm.turn + 1) % 2
* parameter.
gm.checkForBooks()
*/
if opponent == 1 {
func (self *GoFishGame) playerTurn(getPick func(*GoFishGame) string) {
gm.printHand()
tOpponent := (self._Turn + 1) % 2
self.checkForBooks()
if tOpponent == 1 {
self.printHand()
}
if selfgm.isHandEmpty() {
selfgm.drawCard()
}
tGameOvergameOver := selfgm.isGameOver()
if !tGameOvergameOver {
tCardcard := getPick(selfgm)
if selfgm.opponentHas(tCardcard) {
tCountcount := selfgm.removeOccurencesstealCards(tCardcard, tOpponentopponent)
for tIndexindx := 0; tIndexindx < tCountcount; tIndexindx++ {
selfgm._Handshands[selfgm._Turnturn] = append(selfgm._Handshands[selfgm._Turnturn], tCardcard)
}
selfgm.checkForBooks()
} else {
selffmt.drawCardPrintln("GO FISH!")
gm.drawCard()
self._Turn = tOpponent
gm.turn = opponent
}
}
selfgm.endPly()
}
 
// printGameOverMessage prints the appropriate end message.
/*
func (gm *GoFishGame) printGameOverMessage() {
* Determine and say who won.
fmt.Printf("Final score is %d to %d.\n", gm.scores[0], gm.scores[1])
*/
if gm.scores[0] > gm.scores[1] {
func (self *GoFishGame) printGameOverMessage() {
fmt.Println("Final score is", self._Scores[0], "to", self._Scores[1])
if self._Scores[0] > self._Scores[1] {
fmt.Println("Player wins!")
} else if selfgm._Scoresscores[0] == selfgm._Scoresscores[1] {
fmt.Println("It's a tie.")
} else {
Line 201 ⟶ 182:
}
 
// printHand print's the player's hand and current score.
/*
func (gm *GoFishGame) printHand() {
* Print player's hand and current score.
sort.Strings(gm.hands[0])
*/
fmt.Printf("You have: %s.\n", gm.hands[0])
func (self *GoFishGame) printHand() {
fmt.Printf("Score is %d to %d.\n", gm.scores[0], gm.scores[1])
sort.Strings(self._Hands[0])
sort.Strings(self._Hands[1])
fmt.Println("You have:", self._Hands[0])
fmt.Println("Score is", self._Scores[0], "to", self._Scores[1])
}
 
// stealCards removes all instances of a card from side's hand.
/*
func (gm *GoFishGame) stealCards(purge string, side int) int {
* Remove all occurences of aElem from the hand
count := 0
* represented by aSide.
tList := gm.hands[side]
*/
var filtered []string
func (self *GoFishGame) removeOccurences(aElem string, aSide int) int {
for _, card := range tList {
tCount := 0
if purge == card {
tList := self._Hands[aSide]
count++
var tFiltered []string
for _, tCard := range tList {
if tCard == aElem {
tCount++
} else {
tFilteredfiltered = append(tFilteredfiltered, tCardcard)
}
}
selfgm._Handshands[aSideside] = tFilteredfiltered
return tCountcount
}
 
// main creates the deck and initial hands.
/*
* Set up and begin the game.
*/
func main() {
tDeckdeck := makeDeck()
tPlayerHandplayerHand := tDeckdeck[0:9]
tCompHandcompHand := tDeckdeck[9:18]
tDeckdeck = tDeckdeck[18:]
tHandshands := make([][]string, 2, 2)
tHandshands[0] = tPlayerHandplayerHand
tHandshands[1] = tCompHandcompHand
tScoresscores := make([]int, 2, 2)
tScoresscores[0] = 0
tScoresscores[1] = 0
tGamegame := GoFishGame{tHandshands, tDeckdeck, 0, tScoresscores}
tGamegame.playerTurn(getPickUser)
}
</lang>