首页 > 其他分享 >Go实现一个五子棋功能

Go实现一个五子棋功能

时间:2024-08-23 14:38:18浏览次数:6  
标签:功能 return nil fmt 五子棋 Grid Go col row

参考 https://juejin.cn/post/6847902215575699464

package main

import (
	"fmt"
	"math/rand"
	"strconv"
	"strings"
	"time"
)

type hand uint

const (
	NilHand   hand = iota //空白
	BlackHand             //黑手
	WhiteHand             //白手
)

func (h hand) Str() string {
	switch h {
	case NilHand:
		return "."
	case BlackHand:
		return "X"
	case WhiteHand:
		return "O"
	default:
		return "."
	}
}

type Grid struct {
	value  hand
	left   *Grid
	right  *Grid
	top    *Grid
	bottom *Grid
}

func (g *Grid) LeftTop() *Grid {
	if g.left != nil {
		return g.left.top
	}
	return nil
}

func (g *Grid) LeftBottom() *Grid {
	if g.left != nil {
		return g.left.bottom
	}
	return nil
}

func (g *Grid) RightTop() *Grid {
	if g.right != nil {
		return g.right.top
	}
	return nil
}

func (g *Grid) RightBottom() *Grid {
	if g.right != nil {
		return g.right.bottom
	}
	return nil
}

//设置row,col坐标的值, 即 落棋子
func (g *Grid) Set(row, col int, value hand) {
	offset := g
	offset = g.Offset(row, col)
	if offset == nil {
		return
	} else if offset.value == NilHand {
		offset.value = value
	}
	return
}

//获取向右偏移x位的指针
func (g *Grid) RightOffset(col int) *Grid {
	var tmp *Grid
	tmp = g
	if g == nil {
		return nil
	}
	for i := 1; i <= col; i++ {
		if i == col && tmp != nil {
			return tmp
		}
		if tmp == nil {
			return nil
		}
		if tmp.right != nil {
			tmp = tmp.right
		}
	}
	return nil
}

//获取向下偏移y位的指针
func (g *Grid) BottomOffset(row int) *Grid {
	var tmp *Grid
	tmp = g
	if g == nil {
		return nil
	}
	for i := 1; i <= row; i++ {
		if i == row && tmp != nil {
			return tmp
		}
		if tmp == nil {
			return nil
		}
		if tmp.bottom != nil {
			tmp = tmp.bottom
		}
	}
	return nil
}

//获取该表格有几行
func (g *Grid) GetRowLen() int {
	var row int
	tmp := g
	for tmp != nil {
		row++
		tmp = tmp.bottom
	}
	return row
}

//获取该表格有几列
func (g *Grid) GetColLen() int {
	var col int
	tmp := g
	for tmp != nil {
		col++
		tmp = tmp.right
	}
	return col
}

func (g *Grid) Print() {
	fmt.Println("当前棋盘布局为:")
	var colNumStr = ""
	col := g.GetColLen()
	fillC := strconv.Itoa(g.GetColLen())
	for i := 1; i <= col; i++ {
		colNumStr += " " + StrLeftFill(len(fillC), i)
	}
	fmt.Println(StrLeftFill(len(strconv.Itoa(g.GetRowLen())), ""), strings.TrimLeft(colNumStr, " "))

	for row := 1; row <= g.GetRowLen(); row++ {
		var rowStr = ""
		for col := 1; col <= g.GetColLen(); col++ {
			//rowStr += StrLeftFill(len(strconv.Itoa(g.GetColLen())), "") + g.Offset(row, col).value.Str()
			rowStr += " " + StrLeftFill(len(strconv.Itoa(g.GetColLen())), g.Offset(row, col).value.Str())
		}
		fmt.Println(StrLeftFill(len(strconv.Itoa(g.GetRowLen())), row), strings.TrimLeft(rowStr, " "))
	}

	fmt.Println("")
}

/*
获取坐标处的指针
*/
func (g *Grid) Offset(row, col int) *Grid {
	offset := g
	if g == nil {
		return nil
	}
	var i, j int
	i, j = 1, 1
	for i <= row {
		if row == i {
			for j <= col {
				if col == j {
					return offset
				}

				if offset == nil {
					return nil
				}
				offset = offset.right
				j++
			}
		}
		if offset == nil {
			return nil
		}
		offset = offset.bottom
		i++
	}
	return nil
}

//获取某列最后一行的棋子的指针
func (g *Grid) GetLastRow(col int) *Grid {
	offset := g.Offset(1, col)
	for row := 1; row <= g.GetRowLen(); row++ {
		if row == g.GetRowLen() {
			return offset
		}
		offset = offset.bottom
	}
	return nil
}

//获取某一行的最后一列没有落棋子的指针
func (g *Grid) GetEmptyLastRow(col int) *Grid {
	if col <= 0 || col > g.GetColLen() {
		return nil
	}
	last := g.GetLastRow(col)
	if last == nil {
		return nil
	}
	for row := 1; row <= g.GetRowLen(); row++ {
		if last.value == NilHand {
			return last
		}
		last = last.top
		if last == nil {
			return nil
		}
	}
	return nil
}

//棋盘是否已满?
func (g *Grid) IsFull() bool {
	for row := 1; row <= g.GetRowLen(); row++ {
		for col := 1; col <= g.GetColLen(); col++ {
			if g.Offset(row, col).value == NilHand {
				return false
			}
		}
	}
	return true
}

//统计黑手,白手的棋子数量
func (g *Grid) Count() (black, white int) {
	for row := 1; row <= g.GetRowLen(); row++ {
		for col := 1; col <= g.GetColLen(); col++ {
			if g.Offset(row, col).value == BlackHand {
				black++
			} else if g.Offset(row, col).value == WhiteHand {
				white++
			}
		}
	}
	return
}

//检查是否已分出胜负
func (g *Grid) IsWin(row, col int) bool {
	offset := g.Offset(row, col)
	h := offset.value
	if h == NilHand {
		return false
	}
	//检查行
	count := 1
	left := offset.left
	right := offset.right
	for {
		if left == nil {
			break
		}
		if left.value == h {
			count++
		} else {
			break
		}
		left = left.left
	}
	for {
		if right == nil {
			break
		}
		if right.value == h {
			count++
		} else {
			break
		}
		right = right.right
	}
	if count >= 4 {
		switch h {
		case WhiteHand:
			fmt.Println("白手赢", fmt.Sprintf("最后一个落子点为(row:%d,col:%d)", row, col))
		case BlackHand:
			fmt.Println("黑手赢", fmt.Sprintf("最后一个落子点为(row:%d,col:%d)", row, col))
		}
		return true
	}

	//检查列
	count = 1
	top := offset.top
	bottom := offset.bottom
	for {
		if top == nil {
			break
		}
		if top.value == h {
			count++
		} else {
			break
		}
		top = top.top
	}
	for {
		if bottom == nil {
			break
		}
		if bottom.value == h {
			count++
		} else {
			break
		}
		bottom = bottom.bottom
	}
	if count >= 4 {
		switch h {
		case WhiteHand:
			fmt.Println("白手赢", fmt.Sprintf("最后一个落子点为(row:%d,col:%d)", row, col))
		case BlackHand:
			fmt.Println("黑手赢", fmt.Sprintf("最后一个落子点为(row:%d,col:%d)", row, col))
		}
		return true
	}

	//检查左斜边
	count = 1
	leftTop := offset.LeftTop()
	rightBottom := offset.RightBottom()
	for {
		if leftTop == nil {
			break
		}
		if leftTop.value == h {
			count++
		} else {
			break
		}
		leftTop = leftTop.LeftTop()
	}
	for {
		if rightBottom == nil {
			break
		}
		if rightBottom.value == h {
			count++
		} else {
			break
		}
		rightBottom = rightBottom.RightBottom()
	}
	if count >= 4 {
		switch h {
		case WhiteHand:
			fmt.Println("白手赢", fmt.Sprintf("最后一个落子点为(row:%d,col:%d)", row, col))
		case BlackHand:
			fmt.Println("黑手赢", fmt.Sprintf("最后一个落子点为(row:%d,col:%d)", row, col))
		}
		return true
	}

	//检查右斜边
	count = 1
	rightTop := offset.RightTop()
	leftBottom := offset.LeftBottom()
	for {
		if rightTop == nil {
			break
		}
		if rightTop.value == h {
			count++
		} else {
			break
		}
		rightTop = rightTop.RightTop()
	}
	for {
		if leftBottom == nil {
			break
		}
		if leftBottom.value == h {
			count++
		} else {
			break
		}
		leftBottom = leftBottom.LeftBottom()
	}
	if count >= 4 {
		switch h {
		case WhiteHand:
			fmt.Println("白手赢", fmt.Sprintf("最后一个落子点为(row:%d,col:%d)", row, col))
		case BlackHand:
			fmt.Println("黑手赢", fmt.Sprintf("最后一个落子点为(row:%d,col:%d)", row, col))
		}
		return true
	}
	if g.IsFull() {
		fmt.Println("平手")
		return true
	} else {
		return false
	}
}

/*
约定: row,col的起始值为1
*/
func InitGrid(row, col int, head *Grid) *Grid {
	l := &Grid{}

	l = head
	c := col
	for c > 1 {
		var tmp Grid
		tmp.left = l
		l.right = &tmp
		l = &tmp
		c--
	}

	l = head
	r := row
	for r > 1 {
		var tmp Grid
		tmp.top = l
		l.bottom = &tmp
		l = &tmp
		r--
	}

	for i := 2; i <= row; i++ {
		for j := 2; j <= col; j++ {
			top := head.Offset(i-1, j)
			left := head.Offset(i, j-1)
			var tmp Grid
			tmp.top = top
			tmp.left = left

			top.bottom = &tmp
			left.right = &tmp
		}
	}
	return head
}

func TestGrid(row, col int) {
	/*
		简单的测试下棋子
		设置:
				(1,4),(4,3)为黑手
				(3,4),(4,6)为白手
	*/
	grid := InitGrid(row, col, &Grid{})

	grid.Set(1, 4, BlackHand)
	grid.Set(4, 3, BlackHand)
	grid.Set(3, 4, WhiteHand)
	grid.Set(4, 6, WhiteHand)
	grid.Print()
}
func GameOne(row, col int) {
	/*
		游戏规则:
			两个玩家p1,p2轮流放黑白棋子,每个玩家随机抽取一列放入自己的棋子,棋子调入该列最后空白处(可理解为压栈),直到填满.
			(如果该列已经满了,玩家此次机会失效,下一个玩家继续).
		胜出条件:
			棋盘被完全占满(最多的为胜?)
	*/
	grid := InitGrid(row, col, &Grid{})
	rand.Seed(time.Now().Unix())
	i := 0 //
	for {
		if grid.IsFull() {
			black, white := grid.Count()
			if black > white {
				fmt.Println("黑手胜", fmt.Sprintf("黑手:%d;白手:%d", black, white))
			} else if black < white {
				fmt.Println("白手胜", fmt.Sprintf("黑手:%d;白手:%d", black, white))
			} else {
				fmt.Println("平手", fmt.Sprintf("黑手:%d;白手:%d", black, white))
			}
			grid.Print()
			break
		}
		//规定偶数为: 黑手
		h := grid.GetEmptyLastRow(rand.Intn(grid.GetColLen()) + 1)
		if h == nil {
		} else if i%2 == 0 {
			h.value = BlackHand
		} else {
			h.value = WhiteHand
		}
		i++
	}
}

//落子的坐标
type XY struct {
	row int
	col int
}

func GameTwo(row, col int) {
	/*
		游戏规则:(和我们平时玩的规则一样)
			1. 一行连续4个子
			2. 一列连续4个子
			3. 对角线连续4个子
			4. 棋盘被完全填满,还未出现胜负,则平局
	*/
	grid := InitGrid(row, col, &Grid{})

	//生成所有的棋子位置
	xy := map[int]XY{}
	var loop int // 第几次循环
	for r := 1; r <= row; r++ {
		for c := 1; c <= col; c++ {
			xy[loop] = XY{row: r, col: c}
			loop++
		}
	}

	rand.Seed(time.Now().Unix())
	p := XY{1, 1}
	i := 0
	for {
		//if grid.IsFull() {
		//	break
		//}
		if grid.IsWin(p.row, p.col) {
			grid.Print()
			break
		}

		//随机落棋
		for {
			if v, ok := xy[rand.Intn(loop+1)]; ok {
				p = v
				delete(xy, loop) //已取出,删除该坐标
				break
			}
			//棋子坐标非法, continue
		}

		if i%2 == 0 {
			//黑手落棋子
			grid.Set(p.row, p.col, BlackHand)
		} else {
			//白手落棋子
			grid.Set(p.row, p.col, WhiteHand)
		}
		i++
	}
}

//字符串左边填充
func StrLeftFill(s int, value interface{}) string {
	var format = ""
	format = "%" + strconv.Itoa(s) + "v"
	return fmt.Sprintf(format, value)
}

func main() {
	grid := InitGrid(6, 7, &Grid{})

	//空棋盘
	grid.Print()
	TestGrid(6, 7)
	GameOne(6, 7)
	GameTwo(20, 20)
}

标签:功能,return,nil,fmt,五子棋,Grid,Go,col,row
From: https://www.cnblogs.com/qcy-blog/p/18375938

相关文章

  • 第6篇 好用免费的开发AI:FittenCode Chart,功能类似chatgpt
    你所不知道的免费,又好用的AI,帮助你提高工作效率;1.打开vs,点击扩展》管理工具,然后搜索FittenCode,安装下载完成后,重新打开vs2.打开vs,管理工具,就会出现FittenCode,选择openchatwindow,解决方案管理下就会出现FittencodeChart,3.输入问题,就可以对话,fittenCode就会给出解决方......
  • Goolge earth studio 入门6-渲染
    如果我们对现在生成的动画很满意,可以将其渲染出来,以便在EarthStudio之外查看它。点击渲染按钮,进入了渲染设置页面。1)可以更改文件名;默认情况下,它与我们的项目相同;2)还可以选择渲染的帧数,例如,如果我们只想渲染前180帧,可以在这里进行设置,会看到左侧的预览会更新。这是检查裁......
  • Goolge earth studio 入门4-制作你的第一个动画
    1、创建第一个关键帧我们来创建一个东京地区的飞越镜头。首先,构图,当对一切都满意时,点击“关键帧全部”按钮。这会将我这里的所有属性值保存到当前帧。现在这些关键帧已经设置好,如果移动相机,你会看到关键帧变黄,这意味着当前视图与当前关键帧的值不匹配。如果将播放头移出关键......
  • Goolge earth studio 入门5-动画调整
    如果还想对动画进行一定的更改,可以1)跳到最后一帧,在地球上拖动,调整最后一帧的场景,就像刚才做的那样;2)调整各帧视角的高度,比如在这第一帧中,海拔是986米。寻找一种直升机风格的镜头,海拔不变。可以查看海拔值,并点击并左右拖动来调整它并降低其值。这实际上会改变关键帧的值,而不需......
  • 使用光影魔术手的色彩调整功能,让你的照片更具活力
    前言你是否曾经因为处理繁琐的照片而感到无从下手?是否在忙碌的工作中想要快速修整图片,却因为复杂的软件操作而拖延了时间?光影魔术手就是为了解决这些问题而诞生的。它不仅是一款功能强大的批量图像处理工具,更是一位高效的助手,帮助你在繁忙的工作中节省宝贵的时间,提高办公效率,......
  • 基于django+vue汽车维修服务系统【开题报告+程序+论文】计算机毕设
    本系统(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。系统程序文件列表开题报告内容研究背景随着汽车保有量的持续增长和消费者对汽车服务质量要求的不断提高,汽车维修服务行业面临着前所未有的机遇与挑战。传统的手工记录与管理方式......
  • 基于django+vue汽车空调管理系统【开题报告+程序+论文】计算机毕设
    本系统(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。系统程序文件列表开题报告内容研究背景随着汽车工业的快速发展和人们生活水平的提高,汽车已成为现代生活中不可或缺的重要交通工具。汽车空调作为提升驾乘舒适度的关键系统,其性能......
  • 基于django+vue企业物流管理系统【开题报告+程序+论文】计算机毕设
    本系统(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。系统程序文件列表开题报告内容研究背景在全球化与电子商务飞速发展的今天,企业物流管理已成为连接生产与销售、提升供应链效率的关键环节。传统的人工或简单信息化管理方式已难以......
  • iPhone 16 即将推出,,这将是苹果最大的升级, 这里有 7 个你不敢相信 的功能
    iPhone16即将推出,,这将是苹果最大的升级,iphone16有哪些新功能呢?iPhone16值得买么?这里有7个你不敢相信的功能,让我们先睹为快。iphone16有哪些新功能1.您现在可以链接两部iPhone以在iOS18中发送现金2.新的AI智能计算器3.用眼睛控制你的iPhone4.阻止使用面容ID......
  • Django集成腾讯COS对象存储
    前言最近遇到一个场景需要把大量的资源文件存储到OSS里,这里选的是腾讯的COS对象存储(话说我接下来想搞的SnapMix项目也是需要大量存储的,我打算搭个MinIO把24T的服务器利用起来~)为啥腾讯不搞个兼容AmazonS3协议的啊……官方的SDK和文档都奇奇怪怪的,感觉国内的厂......