Reputation: 169
I am building a Connect 4 game and I was wondering if it is possible to build int arrays into methods. It would be easier for me to just show the code, so I've shown the method below (and dependencies). The commented out bit is how it works at the moment
//Defend 4 horizontal to the right (xxx-)
for(int y=0;y<board.get_ysize();y++){
boolean breakfor=false;
for(int x=0;x<(board.get_xsize()-3);x++){
if(board.get_state(x,y)==1
&& board.areSame(board, {(x+1),y}, {x,y})
&& board.areSame(board, {(x+2),y}, {x,y})
&& board.areSame(board, {(x+3),y}, {0})
// How the code works at the moment:
// board.get_state((x+1),y)==board.get_state(x,y)
// && board.get_state((x+2),y)==board.get_state(x,y)
// && board.get_state((x+3),y)==0)
{
if(y==0){
return (x+3);
}
else if((y-1)==0){
return (x+3);
}
else{
breakfor=true;
break;
}
}
}
if(breakfor){
break;
}
}
get_state():
public int get_state(int x, int y) {
return layout[x][y];
}
(layout[x][y] returns a 0, 1 or 2 for the position. 0 is empty and 1 and 2 are player counters)
areSame():
public boolean areSame(GameBoard board, int[] initialspace, int[] comparespace){
if(board.get_state(initialspace[0],initialspace[1])==board.get_state(comparespace[0], comparespace[1])){
return true;
}
return false;
}
It's not necessary as the code works the old way, but I was just wondering if there is a way to make this array method work?
Thanks
Upvotes: 0
Views: 414
Reputation: 4843
You may want to check for a defense against a vertical and horizontal threat to win on next move by using a check like (for horizontal shown below, make an analog for vertical threat)
boolean threat;
int playX = -1;
int playY;
for (int y=0; y < board.get_ysize; y++) {
for (int x=0, x < board.get_xsize; x++) {
int count1;
int count2;
for (int i=0; i < 4; i++) {
switch (board.get_state(x+i, y)) {
case 0:
if (playX == -1) {playX = x+i; playY = y;}
break;
case 1:
count1++;
break;
case 2:
count2++;
break;
default:
// handle error
break;
}
}
if (count1 == 3 && count2 == 0) {
// should be able to defend
// play player 2 at playX, playY
break; // could go on to see if imminent loss anyway
}
}
Upvotes: 1