golang制作一个斗地主游戏服务器[2]:一副扑克牌

前一章写的是单张的扑克牌, 这里要写一整副扑克牌

首先定义一个扑克牌的切片

// TCards 
type TCards []*TCard

新建卡牌的时候, 分配空间, 并且随机洗牌

package main

import (
	"log"
	"math/rand"
	"sort"
	"time"
)

func init() {
	//以时间作为初始化种子
	rand.Seed(time.Now().UnixNano())
}

// TCards 排序用
type TCards []*TCard

// NewCards 新建卡牌
func NewCards(nLen int) TCards {
	cards := make(TCards, nLen)
	// 给牌堆里面的牌赋初始值
	for i := 0; i < nLen; i++ {
		pCard := NewCard(i + 1) // 这里是从1开始
		cards[i] = pCard
	}

	cards.randomize()

	return cards
}

// randomize 洗牌
func (self TCards) randomize() {
	for i := 0; i < len(self); i++ {
		nRand := rand.Intn(len(self) - 1) // 从 0 - 53 开始
		// 两两指针进行交换
		self.Swap(i, nRand)
	}
}

加上排序用的 Sort 的 Interface 三件套


// 长度
func (self TCards) Len() int {
	return len(self)
}

// 比较大小
func (self TCards) Less(i, j int) bool {
	// 先比较点数
	if self[i].nPoint == self[j].nPoint {
		// 点数相同比较花色
		return self[i].nFlower > self[j].nFlower
	}
	return self[i].nPoint < self[j].nPoint
}

// 交换两个牌的牌值
func (self TCards) Swap(i, j int) {
	// self[i].Swap(self[j])
	self[i], self[j] = self[j], self[i]
}
// 三件套出处写的很明白了已经
// Package sort provides primitives for sorting slices and user-defined
// collections.
package sort

// A type, typically a collection, that satisfies sort.Interface can be
// sorted by the routines in this package. The methods require that the
// elements of the collection be enumerated by an integer index.
type Interface interface {
	// Len is the number of elements in the collection.
	Len() int
	// Less reports whether the element with
	// index i should sort before the element with index j.
	Less(i, j int) bool
	// Swap swaps the elements with indexes i and j.
	Swap(i, j int)
}

最后补足一些打印之类的函数

// 输出
func (self TCards) tostr() string {
	// 顺带打印看结果
	strResult := ""
	for i := range self {
		strResult = strResult + self[i].tostr() + ","
	}
	return strResult
}

// 打印
func (self TCards) print() {
	log.Println(self.tostr())
}

// 排序
func (self TCards) sort() {
	sort.Sort(self)
}

猜你喜欢

转载自blog.csdn.net/warrially/article/details/88562710