deem
deem
CC#
Created by deem on 4/18/2024 in #help
TicTacToe Game not working
Hello.
8 replies
CC#
Created by deem on 6/28/2023 in #help
✅ What is the best way to fix StackOverflow when methods are calling each other?
Here is all the relevant code to the question When Checkmate is called, it calls Stalemate, which calls AllPossibilitesOfPlayer, which calls RemovesCheck, which calls Check, which calls AllPossibilitesOfPlayer, which calls RemovesCheck, which calls Check and so on. What is the best way to fix this problem? I can duplicate some functions and I think it will fix it, but is there any other better solution?
public List<int> AllPossiblitiesOfPlayer(int player, Board b)
{
List<int> allMoves = new List<int>(), playerPositions = player == 0 ? whitePositions : blackPositions; ;
for (int i = 0; i < playerPositions.Count; i++)
{
List<int> possibles = new Find(playerPositions[i], board[playerPositions[i]].piece, player, this).FindMoves();
for (int j = 0; j < possibles.Count; j++)
{
if (!RemovesCheck(i, possibles[j], player, b))
{
possibles.RemoveAt(j);
}
}
allMoves.Concat(possibles).ToList();
}
return allMoves;
}
public int Stalemate(Board b, int player)
{
if (AllPossiblitiesOfPlayer(player, b).Count() == 0)
return player;
else return -1;
}
public int Checkmate(Board b, int player)
{
if (Stalemate(b, player) == player && Check(player, b))
return player == 0 ? 1 : player;
return -1;
}
public bool Check(int player, Board b)
{
return AllPossiblitiesOfPlayer(player == 0 ? 1 : player, b).Contains(FindKingPos(player, b));
}
public bool RemovesCheck(int source, int dest, int player, Board b)
{
var copy = b.Clone(b);
Move(source, dest, player, copy);
return !Check(player, copy);
}
public List<int> AllPossiblitiesOfPlayer(int player, Board b)
{
List<int> allMoves = new List<int>(), playerPositions = player == 0 ? whitePositions : blackPositions; ;
for (int i = 0; i < playerPositions.Count; i++)
{
List<int> possibles = new Find(playerPositions[i], board[playerPositions[i]].piece, player, this).FindMoves();
for (int j = 0; j < possibles.Count; j++)
{
if (!RemovesCheck(i, possibles[j], player, b))
{
possibles.RemoveAt(j);
}
}
allMoves.Concat(possibles).ToList();
}
return allMoves;
}
public int Stalemate(Board b, int player)
{
if (AllPossiblitiesOfPlayer(player, b).Count() == 0)
return player;
else return -1;
}
public int Checkmate(Board b, int player)
{
if (Stalemate(b, player) == player && Check(player, b))
return player == 0 ? 1 : player;
return -1;
}
public bool Check(int player, Board b)
{
return AllPossiblitiesOfPlayer(player == 0 ? 1 : player, b).Contains(FindKingPos(player, b));
}
public bool RemovesCheck(int source, int dest, int player, Board b)
{
var copy = b.Clone(b);
Move(source, dest, player, copy);
return !Check(player, copy);
}
20 replies