I am making a Tic-Tac-Toe game with a computer player. However, whenever I call the computer's makeMove method, the computer continues to play without the user being able to do anything. Just to be sure that the function stopped, I made it return after each move, but it still plays the entire game without the user's input.
Here are the relevant parts:
Board Class:
public String addToBoard(char c, int square) {
if (!spaceFull(board, square)) {
int[] coords = getRowAndColumn(square);
//System.out.println("[" + coords[0] + "][" + coords[1] + "]");
board[coords[0]][coords[1]] = c;
return "VALID";
} else {
System.out.println("Space Is Occupied");
return "OCCUPIED";
}
}
public boolean spaceFull(char[][] b, int square) {
return (twoDimenToOneDimen(b).get(square - 1) == 'X' || twoDimenToOneDimen(b).get(square - 1) == 'O');
}
Computer Class
public void makeMove() {
int square;
//Checks For Any Winning Computer Moves
System.out.println("Here");
if ((square = nextMoveWinCheck(playerChar)) != 0) {
board.addToBoard(playerChar, square);
return;
//Checks For Any Opponent Winning Moves
} else if ((square = nextMoveWinCheck(opponentChar)) != 0) {
board.addToBoard(playerChar, square);
return;
} else {
//Checks If Computer Has First Move
if (boardEmpty()) {
board.addToBoard(playerChar, 9);
return;
} else {
//Moves Into Opposite Corner if Bottom Corner is Occupied By Itself
if (!board.spaceFull(board.board,1) && board.board[2][2] == playerChar) {
board.addToBoard(playerChar, 1);
return;
//Move Into Center If Second Move or Possible
} else if (!board.spaceFull(board.board,5)) {
board.addToBoard(playerChar, 5);
return;
} else if ((square = emptyCorner()) != 0) {
board.addToBoard(playerChar, square);
return;
} else {
board.addToBoard(playerChar, randomEmptySpot());
return;
}
}
}
}
If you want the full code, it's:
Computer
Board
Player
Tic-Tac-Toe Main Class
Your problem lies in your class Computer. On line 57, you assign board.board to tempBoard. However tempBoard still holds the reference to the object board.board, so whatever modifications you make there is reflected on the actual board. To resolve this, COPY the board values to tempboard:
http://www.java2s.com/Code/Java/Collections-Data-Structure/clonetwodimensionalarray.htm
Related
So i have a game where if my user collides with an image it will increase the score by 1. However because i use this method of collision detection and an if statement to increment my score, during the duration of the collision the score will go up by about 30 as the collision method detects it colliding multiple times as they pass through each other. How would i stop it from incrementing by more than one each time.
Here is my code:
void draw () {
if (gameMode == Active) {
if(crash() == false) {
drawBackground();
textSize(32);
fill(22,100,8);
text("Score: " + score ,20,40); //calls the drawBackground method
alien1.update();
alien2.update(); //constantly calls the move and render method for the alien and defender
alien3.update();
user1.render();
Burger.update();
if(Bcrash() == true) {
if(Bcrash() == false) {
score = score + 1;
}
}
} else {
gameMode = End;
textSize(32);
fill(22,100,8);
text("Game Over, press 'r' to restart",150,200);
}
}
}
boolean Bcrash() {
return user1.crash(Burger));
}
// Burger.class (Editor's note: I guess it's User.class)
public class User {
boolean crash(Burger A) {
return(abs(x-A.x)<=30) && abs(y-A.y)<=30;
}
}
Check to see if collision is false before allowing it to add another number.
something like:
Boolean collisionInProgress = false;
if(collision == true && collisionInProgress == false){
score = score+1;
collisionInProgess = true;
}
…loop…
if(collision == false){
collisionInProgess = false;
}
In my method under the if statement:
if (currentLocationX == 0 && currentLocationY == 4)
I have a break statement that should make the program exit out of the while loop and return true for 'answer' and for the method. Yet after some testing it seems that after returning true for 'answer', it goes back into the while loop giving the wrong results int the end. Why is my break statement not doing what it's supposed to? Thank you!
P.S. (this method calls on some other method that were not relevant to mention here)
public boolean solveMaze()
{
boolean answer = false;
int currentLocationX;
int currentLocationY;
//push starting location
pushX(2);
pushY(1);
while((isEmptyX() == false) && (isEmptyY() == false))
{
printMaze();
System.out.println();
currentLocationX = popX();
currentLocationY = popY();
//mark current location as visited
visited(currentLocationX, currentLocationY, maze);
System.out.println("Current Location: " + currentLocationX + ", " + currentLocationY);
if (currentLocationX == 0 && currentLocationY == 4)
{
answer = true;
break;
}
else
{
//push all unvisited OPEN neighbor locations into stack
if (checkEast(currentLocationX, currentLocationY) == 0)
{
pushX(eastX(currentLocationX));
pushY(eastY(currentLocationY));
}
else;
if (checkSouth(currentLocationX, currentLocationY)== 0)
{
pushX(southX(currentLocationX));
pushY(southY(currentLocationY));
}
else;
if (checkWest(currentLocationX, currentLocationY)== 0)
{
pushX(westX(currentLocationX));
pushY(westY(currentLocationY));
}
else;
if (checkNorth(currentLocationX, currentLocationY)== 0)
{
pushX (northX(currentLocationX));
pushY(northY(currentLocationY));
}
else;
}
}
return answer;
}
I wrote out the basic logic of your method as
public static boolean solveMaze() {
boolean answer = false;
int currentLocationX = 0;
int currentLocationY = 4;
while (true) {
if (currentLocationX == 0 && currentLocationY == 4) {
System.out.println("Hit the break");
break;
} else {
System.out.println("Missed the break");
}
}
return answer;
}
and if you execute it you get Hit the break. So your solveMaze() method is fine in terms of breaking out of the loop once it satisfies your if-statement. I would say that if you see your code subsequently going back into the while loop, it must be that solveMaze() was called a second time.
I am working with googlecode lanterna libraries. One of it's methods is "moveCursor(int x, int y)". I have a terminal field, and I want to move a character in it. But I'm having two problems:
The cursor does not go in the proper way it should. When I press Left Arrow after I have been pressing Right Arrow, it goes some steps down, than goes the right way. That happens for all arrows.
And the second question. Can anyone help me to move a character in the terminal field? Should I build any class or any method? Or I should modify this?
Thank you!
public void movePlayer()
{
int xLocation = s.getXLocation();
int yLocation = s.getYLocation();
while (true)
{
Key key = t.readInput();
if (key!=null)
{
if (key.getKind() == Key.Kind.ArrowLeft)
{
t.moveCursor(xLocation-1, yLocation);
xLocation--;
}
else if (key.getKind() == Key.Kind.ArrowRight)
{
t.moveCursor(xLocation+1, yLocation);
xLocation++;
}
else if (key.getKind() == Key.Kind.ArrowUp)
{
t.moveCursor(xLocation, yLocation+1);
yLocation--;
}
else if (key.getKind() == Key.Kind.ArrowDown)
{
t.moveCursor(xLocation, yLocation-1);
yLocation++;
}
}
}
}
If you do it like this the cursor moves properly and without any complications.
public static void movePlayer() {
int xLocation = s.getXLocation();
int yLocation = s.getYLocation();
while (true) {
Key key = t.readInput();
if (key != null) {
if (key.getKind() == Key.Kind.ArrowLeft) {
t.moveCursor(xLocation - 1, yLocation);
xLocation--;
} else if (key.getKind() == Key.Kind.ArrowRight) {
t.moveCursor(xLocation + 1, yLocation);
xLocation++;
} else if (key.getKind() == Key.Kind.ArrowUp) {
t.moveCursor(xLocation, yLocation - 1);
yLocation--;
} else if (key.getKind() == Key.Kind.ArrowDown) {
t.moveCursor(xLocation, yLocation + 1);
yLocation++;
}
}
}
}
I hope I could help you with your Problem.
To your second question I can't give an answer so far.
Hi I'm writing a checkers engine and defining a canEat(Point1,Point2) method for player class which returns true or false based on if player can eat eat the piece at the specified points by checking if the pieces and landing path is on board, if the two pieces belong to the same player or not and also considering the king/super status of piece.
Anyways it works pretty pleasantly without recursion, but without recursion method must get points of the pieces instead of the landing piece which is okay if I manage the recursion. But I want the method to also consider if it gets the landing point instead of piece location. When I run the code it fixes the location and calls itself again there is no problem with that but. I get NullPointerException on
caneat = Checker2.isAlive() ? true : false; because Checker2 is null. My pointToChecker method returns null on this guy so Checker2 is null. What is causing this I'm new to recursion, even OOP to be honest and
Here is my code and console error log
public boolean canEat(Point Piece, Point target)
{
//INITIALIZING
//POINT1 & CHECKER1-> piece which eats
//POINT2 & CHECKER2-> piece to eat
//POINT3 & CHECKER3-> landing path
if (samePoint(Piece, target))
return false;
boolean caneat = true;
boolean king1 = false;
Point Point1,Point2,Point3;
Checker Checker1,Checker2,Checker3;
int ownerID, victimID,axis;
axis = getDirection(Piece, target);
//CHECK IF PLAYER POINTED THE SQUARE AHEAD TARGET PIECE OR THE PIECE TO EAT
int distance = getStep(Piece, target);
if(distance == 2)
{
boolean resolution;
System.err.println("Recoordinated target");
Point fixed = getBackwards(target, axis);
System.err.println("Fixed is: " + Piece + " " + fixed);
resolution = canEat(Piece, fixed);
return resolution;
}
Point1 = Piece;
Point2 = target;
Point3 = findMovePosition(target, axis);
if(!inBoard(Point1) || !inBoard(Point2) || !inBoard(Point3))
{
System.err.println("Error: Invalid Move --> Thinking outside the box");
return false;
}
Checker1 = PointToPiece(Point1);
Checker2 = PointToPiece(Point2);
Checker3 = PointToPiece(Point3);
//CHECK IF PIECES ARE ALIVE
caneat = Checker1.isAlive() ? true : false;
caneat = Checker2.isAlive() ? true : false;
if(!Checker2.isAlive())
{
return false;
}
//THERE SHOULD BE TARGET AND VICTIM PIECES AND AN EMPTY LANDING POINT
if(!isOccupied(Piece))
{
System.err.println("#OccupyChecker invalid piece to move");
return false;
}
if(!isOccupiedbyEnemy(target))
{
System.err.println("#OccupyChecker invalid piece to eat");
return false;
}
if(!(Checker3 == null))
{
System.err.println("#OccupyChecker landing piece error");
return false;
}
ownerID = Checker1.getOwner().getID();
victimID = Checker2.getOwner().getID();
if(ownerID == victimID)
{
System.err.println("owner ID: " + ownerID + " victimID: " + victimID);
System.err.println("#OCCUPY identity");
return false;
}
if(ownerID == 1 && king1)
{
if(axis == 3 || axis == 4)
System.err.println("#OccupyPoint wrong axis");
caneat = false;
}
if(ownerID == 2 && king1)
{
if(axis == 1 || axis == 2)
System.err.println("#OccupyPoint wrong axis");
caneat = false;
}
return caneat;
}
Checker PointToPiece(Point piece)
{
Checker[] allPieces = allPieces();
Checker found = null;
for(Checker k : allPieces)
{
if(samePoint(k.getPosition(), piece))
found = k;
}
return found;
}
I'm working on the n-queens problem and am testing what I have so far to see if my logic is correct. My loop stops stops outputting and goes into an infinite loop after adjusting the 2nd queen piece so that there is no conflict.
I didn't think I'd get an infinite loop with my logic, which is basically:
Push (1,1)
Check for conflict
If conflict, adjust the top queen, if it can't be adjusted, pop off, adjust the new top
If no conflict and the size < 8, push (size+1, 1) -which would obviously be a conflict
Check for conflict
etc
public static boolean conflictCheck() {
QueenNode temp = head;
//walk through stack and check for conflicts
while(temp!=null) {
//if there is no next node, there is no conflict with it
if (temp.getNext() == null){
System.out.println("No next node");
if (queens.size() < 8 ) {
System.out.println("No problems");
return false;
}
}
else if (temp.getRow() ==temp.getNext().getRow() || temp.getColumn() == temp.getNext().getColumn() ||
diagonal(temp, temp.getNext())){
System.out.println("There's a conflict");
return true;
}
}
return false;
}
public static void playChess() {
System.out.println("Playing chess");
if (conflictCheck()) {
if (head.getColumn() == 8) {
queens.pop();
}
if (!queens.isEmpty()) {
System.out.println("Adjusting head");
head.setColumn(head.getColumn()+1);
System.out.println("Head is now " + head.getRow() + ", " + head.getColumn());
playChess();
}
}
else if (!conflictCheck() && queens.size() < 8) {
System.out.println("Stack isn't full yet");
queens.push(queens.size()+1,1);
playChess();
}
else {
success= true;
System.out.println("Success");
queens.viewPieces();
return;
}
}
public static void main(String[] args) {
queens.push(1, 1);
queens.viewPieces();
success = false;
playChess();
}
}
My output is:
The stack
1, 1
End of stack
Playing chess
No next node
No problems
No next node
No problems
Stack isn't full yet
Playing chess
There's a conflict
Adjusting head
Head is now 2, 2
Playing chess
problem
There's a conflict
Adjusting head
Head is now 2, 3
Playing chess
Was missing an extra else statement that determined when something wasn't a conflict