当然,我可以为您提供 Golang 的五子棋代码。以下是一个简单的示例:

package main

import (
	"fmt"
	"strings"
)

const (
	boardSize   = 15
	playerBlack = 'X'
	playerWhite = 'O'
	emptyCell   = '-'
)

type gameBoard [boardSize][boardSize]string

func main() {
	board := initializeBoard()
	currentPlayer := playerBlack

	for {
		printBoard(board)
		fmt.Printf("当前玩家: %s\n", currentPlayer)

		fmt.Print("输入行号和列号,以逗号分隔(例如:3,4):")
		var row, col int
		fmt.Scanf("%d,%d", &row, &col)

		if !isValidMove(row, col, board) {
			fmt.Println("无效的移动,请重试。")
			continue
		}

		board[row][col] = currentPlayer

		if isWinningMove(row, col, currentPlayer, board) {
			printBoard(board)
			fmt.Printf("恭喜!%s玩家获胜。\n", currentPlayer)
			break
		}

		if isBoardFull(board) {
			printBoard(board)
			fmt.Println("平局!游戏结束。")
			break
		}

		currentPlayer = switchPlayer(currentPlayer)
	}
}

func initializeBoard() gameBoard {
	var board gameBoard
	for i := 0; i < boardSize; i++ {
		for j := 0; j < boardSize; j++ {
			board[i][j] = emptyCell
		}
	}
	return board
}

func printBoard(board gameBoard) {
	fmt.Println("   A B C D E F G H I J K L M N O")
	for i := 0; i < boardSize; i++ {
		row := strings.Join(board[i][:], " ")
		fmt.Printf("%2d %s\n", i, row)
	}
}

func isValidMove(row, col int, board gameBoard) bool {
	if row < 0 || row >= boardSize || col < 0 || col >= boardSize {
		return false
	}
	if board[row][col] != emptyCell {
		return false
	}
	return true
}

func isWinningMove(row, col int, player string, board gameBoard) bool {
	directions := [][]int{{0, 1}, {1, 0}, {1, 1}, {1, -1}}
	for _, dir := range directions {
		if countConsecutive(row, col, player, dir[0], dir[1], board) >= 5 {
			return true
		}
	}
	return false
}

func countConsecutive(row, col int, player string, rowInc, colInc int, board gameBoard) int {
	count := 1
	r, c := rowInc, colInc
	for i := 0; i < 4; i++ {
		newRow := row + r
		newCol := col + c
		if newRow >= 0 && newRow < boardSize && newCol >= 0 && newCol < boardSize &&
			board[newRow][newCol] == player {
			count++
			r += rowInc
			c += colInc
		} else {
			break
		}
	}
	return count
}

func isBoardFull(board gameBoard) bool {
	for i := 0; i < boardSize; i++ {
		for j := 0; j < boardSize; j++ {
			if board[i][j] == emptyCell {
				return false
			}
		}
	}
	return true
}

func switchPlayer(player string) string {
	if player == playerBlack {
		return playerWhite
	}
	return playerBlack
}

这是一个简单的控制台游戏,玩家可以交替进行移动,并判断游戏是否结束。请注意,此代码中的判定规则可能有所不足,您可以根据自己的需求进行修改和扩展。祝您玩得愉快!


原文地址: https://www.cveoy.top/t/topic/dpYy 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录