Reputation: 67
I am trying to create a basic tic tac toe game. When I first created this the user would click on an image box, that image box would then change to the respective players counter. The image location would be stored in a variable and applied similar to this:
string Cross = "ProjectFile/etc/..";
Image1.ImageLocation = Cross;
In order to see if the player had completed a row of three I'd have 2 if statements like so, one for a cross and one for a circle:
if(image1.ImageLocation == Cross && Image2.ImageLocation == Cross && Image3.ImageLocation == Cross)
{
//Display message box, you've won etc.
}
This worked fine however I realized that when publishing this file the image location would not exist on a different computer. So I put the images into a resource file. and used them like so:
Position1.Image = Properties.Resources.Cross;
this works fine when loading the images onto the game however when it comes to checking whether or not the player has won, it does not recognise a complete row, I am currently using an if statement like this:
if ((Position1.Image == Properties.Resources.Cross && Position2.Image == Properties.Resources.Cross && Position3.Image == Properties.Resources.Cross) || //etc.
how can I see if the the image that the picture box is using is the same as the image in the resources file?
Upvotes: 1
Views: 488
Reputation: 7259
I would re-architect the game logic to not check the images, but instead create a 3x3 matrix of int
values. Then assign blank to be 0, X to be 1, and O to be 2. (UPDATED: Now enum
values)
On your image box OnClick
event, take the specific image box, figure out its index into the matrix, and set the value to the appropriate value. Then check to see if there is a winner.
Winning logic could me something like this: (Updated to have enum
instead of int. Thanks Matt Burland!)
enum TicTacToeSquare
{
Blank,
X,
O
}
...
private TicTacToeSquare[][] _board;
...
public bool IsWinner(TicTacToeSquare player)
{
if(player == TicTacToeSquare.Blank)
return false;
if(_board.Any(i => i.All(ii => ii == player)))
return true;
for(int i = 0; i < 3; i++)
{
if(_board.All(item => item[i] == player))
return true;
}
if(_board[0][0] == _board[1][1] && _board[1][1] == _board[2][2])
return true;
if(_board[0][2] == _board[1][1] && _board[1][1] == _board[2][0])
return true;
return false;
}
That was just a quick stab, I'd check it before you finalize it.
Upvotes: 2
Reputation: 1043
You are trying to compare references. Position1.Image
is a reference to that image, Properties.Resources.Cross
is a different reference, possibly to the same image, but also possibly not. I would create a new object that contains some sort of image ID or image name and rather than trying to compare the images directly, compare the names or IDs. Alternatively, you can override both the Equals
and GetHashCode
methods to allow you to directly compare 2 image objects but that is more work than what I prefer to do when it comes OOP.
Upvotes: 0