C# 实现九宫格的游戏 的简单例子

C# 实现九宫格的游戏 的简单例子

首页休闲益智缤纷九宫格更新时间:2024-04-19

要在C#中实现九宫格游戏,您可以使用Windows窗体应用程序或控制台应用程序。

以下是一个简单的示例,演示如何在控制台中实现九宫格游戏:

using System; public class Program { private static char[] board = { '1', '2', '3', '4', '5', '6', '7', '8', '9' }; private static char currentPlayer = 'X'; public static void Main() { bool gameEnd = false; while (!gameEnd) { DrawBoard(); int move = GetPlayerMove(); MakeMove(move); if (CheckWin()) { DrawBoard(); Console.WriteLine($"Player {currentPlayer} wins!"); gameEnd = true; } else if (CheckDraw()) { DrawBoard(); Console.WriteLine("It's a draw!"); gameEnd = true; } else { SwitchPlayer(); } } } private static void DrawBoard() { Console.Clear(); Console.WriteLine(" {0} | {1} | {2} ", board[0], board[1], board[2]); Console.WriteLine(" -----------"); Console.WriteLine(" {0} | {1} | {2} ", board[3], board[4], board[5]); Console.WriteLine(" -----------"); Console.WriteLine(" {0} | {1} | {2} ", board[6], board[7], board[8]); } private static int GetPlayerMove() { int move; bool validMove = false; do { Console.Write($"Player {currentPlayer}, enter your move (1-9): "); string input = Console.ReadLine(); if (int.TryParse(input, out move) && move >= 1 && move <= 9 && board[move - 1] != 'X' && board[move - 1] != 'O') { validMove = true; } else { Console.WriteLine("Invalid move. Please try again."); } } while (!validMove); return move; } private static void MakeMove(int move) { board[move - 1] = currentPlayer; } private static bool CheckWin() { // 检查所有可能的获胜组合 if ((board[0] == currentPlayer && board[1] == currentPlayer && board[2] == currentPlayer) || (board[3] == currentPlayer && board[4] == currentPlayer && board[5] == currentPlayer) || (board[6] == currentPlayer && board[7] == currentPlayer && board[8] == currentPlayer) || (board[0] == currentPlayer && board[3] == currentPlayer && board[6] == currentPlayer) || (board[1] == currentPlayer && board[4] == currentPlayer && board[7] == currentPlayer) || (board[2] == currentPlayer && board[5] == currentPlayer && board[8] == currentPlayer) || (board[0] == currentPlayer && board[4] == currentPlayer && board[8] == currentPlayer) || (board[2] == currentPlayer && board[4] == currentPlayer && board[6] == currentPlayer)) { return true; } return false; } private static bool CheckDraw() { // 检查是否所有的格子都已经填满 for (int i = 0; i < 9; i ) { if (board[i] != 'X' && board[i] != 'O') { return false; } } return true; } private static void SwitchPlayer() { currentPlayer = (currentPlayer == 'X') ? 'O' : 'X'; } }

在这个示例中,我们使用一个字符数组board来表示九宫格的状态。

X表示玩家1的棋子,O表示玩家2的棋子。

我们使用一个循环来交替玩家,并在每个回合中进行以下操作:

  1. 调用DrawBoard方法来绘制当前的九宫格状态。
  2. 调用GetPlayerMove方法来获取当前玩家的移动。
  3. 调用MakeMove方法来在九宫格上放置当前玩家的棋子。
  4. 调用CheckWin方法来检查当前玩家是否获胜。
  5. 调用CheckDraw方法来检查游戏是否平局。
  6. 如果有玩家获胜或游戏平局,游戏结束。否则,切换到下一个玩家。

请注意,这只是一个简单的练习示例,没有包含复杂的游戏逻辑或AI。

您可以根据需要进行修改和扩展。

查看全文
大家还看了
也许喜欢
更多游戏

Copyright © 2024 妖气游戏网 www.17u1u.com All Rights Reserved