我如何解決 C# 中的井字棋問題。
游戲規則是,在一個3*3的方格內,玩家輪流進行。玩家將 3 個標記水平或垂直對齊時獲勝。
player1Marker = new List<(int x, int y)>
{
(x:2, y:2),
(x:1, y:1),
(x:0, y:2),
(x:2, y:0),
}
player2Marker = new List<(int x, int y)>
{
(x:0, y:1),
(x:0, y:0),
(x:1, y:2)
}
游戲從 player1 開始。Player1 第 1 步:[2,2] Player2 第 1 步:[0,1] 以此類推。
玩家 1 獲勝,輸出為 [[1,1],[0,2],[2,0]]
public List<(int x, int y)> GetWinningCombo(List<(int x, int y)> player1Markers, List<(int x, int y)> player2Markers)
{
return new List<(int x, int y)>();
}
uj5u.com熱心網友回復:
這是一種方法:
public List<(int x, int y)> GetWinningCombo(List<(int x, int y)> player1Markers, List<(int x, int y)> player2Markers)
{
// make the board
int[,] brd = new int[3, 3];
// add player1 markers
foreach ((int x, int y) mrk in player1Markers)
{
brd[mrk.x, mrk.y] = 1;
}
// add player2 markers
foreach ((int x, int y) mrk in player2Markers)
{
brd[mrk.x, mrk.y] = 2;
}
// check horizontals
for(int i=0; i<=2; i )
{
if (brd[i, 0] > 0 && brd[i, 0] == brd[i, 1] && brd[i, 1] == brd[i, 2])
return new List<(int x, int y)> { (i, 0), (i, 1), (i, 2) };
}
// check veritcals
for (int i = 0; i <= 2; i )
{
if (brd[0, i] > 0 && brd[0, i] == brd[1, i] && brd[1, i] == brd[2, i])
return new List<(int x, int y)> { (0, i), (1, i), (2, i) };
}
// check diagonals
if (brd[0, 0] > 0 && brd[0, 0] == brd[1, 1] && brd[1, 1] == brd[2, 2])
return new List<(int x, int y)> { (0, 0), (1, 1), (2, 2) };
if (brd[2, 0] > 0 && brd[2, 0] == brd[1, 1] && brd[1, 1] == brd[0, 2])
return new List<(int x, int y)> { (2, 0), (1, 1), (0, 2) };
// no wins, return empty list
return new List<(int x, int y)>();
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/340395.html
上一篇:Ksum的演算法總結
下一篇:大量重復的無偏洗牌
