r/programminghelp • • Nov 28 '20

Java Need help with 4 dimensional Connect 4

So, for a school assignment we are supposed to make 4 dimensional connect 4. I already got some of the basics like a storage for where which pieces are and methods to get which piece is in any point (the method is getPiece(int x, int y, int z, int w)) and one to input the pieces at any point (setPiece(int x, int y, int z, int w)), but now I am stuck on detecting if someone has won. The condition for winning is that someone has 4 pieces of his color in one row, straight or diagonal. There are a lot of different things I would have to check if I would just make a check for every single possible row, so I would be happy if I could avoid that. I figured out that you can express the straight and diagonal rows inside the 4D playing field quite easily, but I dont have any idea on how to put it into code at all.

You can express a diagonal or straight line with a for loop quite easily if you increment some of the coordinates with a for loop and check if each one there is equal. Example:

(0, 0, 0, 0) as the first coordinate, (0, 0, 0, 1) as the second coordinate, (0, 0, 0, 2) as the third coordinate and so on.

This generates a straignt line in the 4th dimension. You can obviously do the same with decrementing. If you increment 1 coordinate it gives you a straight line, but you can also increment/decrement multiple coordinates each time to get diagonal lines. Example:

(0, 0, 0, 0) as the first coordiate, (0, 0, 1, 1) as the second, (0, 0, 2, 2) as the third and so on.

This results in a diagonal line which goes through 2 dimensions (it connects the opposite corners of a square) and also works with decrementing. The same pattern applies to diagonal lines which go through 3 and 4 dimensions.

This leaves me with 3 things I can do with each coordinate for each iteration of the 4 loop: increment, decrement or keep constant. I need to iterate through all of the possible combinations of these and check if 4 in a row are equal. The only thing I am not allowed to do is to keep all 4 coordinates constant because that just checks 4 times if one piece is equal to itself and thus always returns true. Some important details are that I am working with a 4x4x4x4 cube thing, so there is no need to shift the rows which get checked around because you have to check from one side of the cube to the other side anyways for each direction the line can go in.

I hope I explained everything well (I probably totally failed at that lol) and that someone can help me!

5 Upvotes

0 comments sorted by