I have my tic tac toe game 90% finished, and had a form of computer AI, but that did not turn out too well. I am looking for a new easier source of generating a spot for the computer to move on the game board.
I need this computer move selection to pick a spot, but to also make sure that spot is freely available and there are no 'X's in that spot. Any ideas as to how to make the computer choose a spot?
/* I have 3 other methods drawing the board, and determining a tie, a loss, and a win not shown here for simplicity*/
public static void main(String[] args) {
//Variable declaration
Scanner kbReader = new Scanner(System.in);
char[][] Board = new char[3][3];
String MenuInput;
int BoardOutput;
int UserSpotChoice;
int ComputerSpotChoice = 0;
int UserTurn = 0;
int Winner = 0;
Board[0][0] = '-';
Board[0][1] = '-';
Board[0][2] = '-';
Board[1][0] = '-';
Board[1][1] = '-';
Board[1][2] = '-';
Board[2][0] = '-';
Board[2][1] = '-';
Board[2][2] = '-';
//Welcome
System.out.println("Welcome to Alex Montague's Tic Tac Toe game!");
System.out.println("");
System.out.println("If you wish to play, type 'Play'");
System.out.println("If you wish to read the instructions, type 'Instructions'");
System.out.println("If you wish to exit, type 'Exit'");
MenuInput = kbReader.next();
do {
if (MenuInput.equals("Play") || MenuInput.equals("play")) {
while (!GameOver) {
System.out.println("\f");
System.out.println(" Tic Tac Toe");
BoardOutput = DrawBoard(Board);
System.out.println(" 1 2 3");
System.out.println(" 4 5 6");
System.out.println(" 7 8 9");
System.out.println("Please enter the number you would like to move your spot to");
UserSpotChoice = kbReader.nextInt();
if (UserSpotChoice == 1) Board[0][0] = 'X';
if (UserSpotChoice == 2) Board[0][1] = 'X';
if (UserSpotChoice == 3) Board[0][2] = 'X';
if (UserSpotChoice == 4) Board[1][0] = 'X';
if (UserSpotChoice == 5) Board[1][1] = 'X';
if (UserSpotChoice == 6) Board[1][2] = 'X';
if (UserSpotChoice == 7) Board[2][0] = 'X';
if (UserSpotChoice == 8) Board[2][1] = 'X';
if (UserSpotChoice == 9) Board[2][2] = 'X';
do {
ComputerSpotChoice = (int)(Math.random() * 9) + 1;
}
while (Board[(ComputerSpotChoice - 1) / 3][(ComputerSpotChoice - 1) % 3] != '-'); //HERE IS THE OLD COMPUTER SPOT GENERATION THAT DID NOT WORK
if (ComputerSpotChoice == 1) Board[0][0] = 'O';
if (ComputerSpotChoice == 2) Board[0][1] = 'O';
if (ComputerSpotChoice == 3) Board[0][2] = 'O';
if (ComputerSpotChoice == 4) Board[1][0] = 'O';
if (ComputerSpotChoice == 5) Board[1][1] = 'O';
if (ComputerSpotChoice == 6) Board[1][2] = 'O';
if (ComputerSpotChoice == 7) Board[2][0] = 'O';
if (ComputerSpotChoice == 8) Board[2][1] = 'O';
if (ComputerSpotChoice == 9) Board[2][2] = 'O';
Winner(Board);
Loser(Board);
Tie(Board);
} //While loop
//if (GameOver) System.exit (0) ;
} //If play
else if (MenuInput.equals("Instructions") || MenuInput.equals("instructions")) {
System.out.println("\f");
System.out.println("You will be playing the game of Tic Tac Toe against the computer.");
System.out.println("The object of this game is to get three of your own x's or o's in a line.");
System.out.println("You take turns placing the x's and o's and whoever gets three in a row first wins.");
System.out.println("Good Luck!");
System.out.println("");
System.out.println("If you wish to play, type 'Play'");
System.out.println("If you wish to exit, type 'Exit'");
MenuInput = kbReader.next();
} else if (MenuInput.equals("Exit") || MenuInput.equals("exit")) {
System.out.println("Thank you for using Alex Montague's Tic Tac Toe game!");
System.exit(0);
} else {
System.out.println("Sorry, that is not a valid choice.");
System.out.println("If you wish to play, type 'Play'");
System.out.println("If you wish to read the instructions, type 'Instructions'");
System.out.println("If you wish to exit, type 'Exit'");
MenuInput = kbReader.next();
}
} //do while
while (!MenuInput.equals("Instructions") || !MenuInput.equals("instructions") || !MenuInput.equals("Play") || !MenuInput.equals("play") || !MenuInput.equals("Exit") || !MenuInput.equals("exit"));
Create a method public static boolean isSpotAvailable(int x, int y). Check after randomly finding a spot for pc, if it is available, use it, if not then choose a new spot.
A simplistic approach could be that, for every square you have, you check how many rows of 3 items you can create from that row. So for instance, the square in the middle would yield 4 (since you can create a horizontal row passing from the middle, a vertical row passing from the middle and two diagonals). On the other hand, squares at the edges would yield a value of 2 (since you can have 1 vertical and 1 horizontal).
If you want to have a more robust approach, then I think that the recommended way would be to use a MiniMax Tree. This will allow you to build a decision tree so that your algorithm decides where to place the next piece. An example of such an approach for tic tac toe can be found here.
You can keep track of the indices by using a HashSet object. As long as you can add a position between 1 to 9 into the set object successfully, the position is available. The other way is to use an ArrayDequeue object. Everytime a spot is used, the relevant spot index will be "removed" and if it is already out, the computer cannot use it.
/* For HashSet<Integer> object - Integer is an immutable wrapper class for int */
spotObj.add(spotLoc); // Returns falls if the spot already exists i.e. used
/* For ArrayDequeue<Integer> object */ - Implementation of Queue interface */
spotObj.remove(spotLoc); returns false if it is already removed i.e. used
Hope this helps you solve your problem
There is an easy way to improve your AI by a lot.
First: check the current state of the board and find all of the possible moves for the AI (which means: find all fields which are empty).
Second: find an opportunity to win this game which means you should simulate all of those possible moves from our first step and see if any of them lets you win the game.
-> if so: do that move!
-> if not: do a random move.
By doing this your AI would already be improved. But you can go even further by using a simple database. Keep track of all those moves your AI and the enemy does.
Whenever you find yourself from now on in a situation where you would do a random move just check your database if you ever were in this situation before and how it turned out for you. According to the outcome of the former game in your database it might be a good idea to do the same move again or try out something different (by doing a random move).
Just append every game and its outcome to this database and you will see how your AI will get better from game to game.
If you need any code-examples just let me know.
Greetings Tim
Related
I am writing a tic tac toe game and everything seems to work except the checks (horizontal/vertical and diagonal). I am using an array (int [3][3]) to make the board.
These are my checks:
private boolean wonStraightLines( int player)
{
boolean answer = false;
if (
((board[0][0] & board[0][1] & board[0][2]) == (player * 3)) ||
((board[1][0] & board[1][1] & board[1][2]) == (player * 3)) ||
((board[2][0] & board[2][1] & board[2][2]) == (player * 3)) ||
((board[0][0] & board[1][0] & board[2][0]) == (player * 3)) ||
((board[0][1] & board[1][1] & board[2][1]) == (player * 3)) ||
((board[0][2] & board[1][2] & board[2][2]) == (player * 3))
)
{
answer = true;
}
else {
answer = false;
}
return answer;
}
and for the diagonal:
private boolean wonDiagonal( int player)
{
boolean answer = false;
if (
((board[0][0] & board[1][1] & board[2][2]) == (player * 3)) || ((board[0][2] & board[1][1] & board[2][0]) == (player * 3))
)
{
answer = true;
}
else {
answer = false;
}
return answer;
}
when I run the program whenever X or O get 3 from any direction the game keeps running rather than throwing out a "you win" message. Any help would be appreciated. Not sure if any other parts of the code are needed or not.
EDIT: I also tried using the + instead of the & between the board array values but did not work as well.
I'm assuming there are 3 unique values for the states of each element such as for example:
board[row][col] = 0 // no entry
board[row][col] = 1 // player 1
board[row][col] = 2 // player 2
Without being clever a horizontal check for player (using row-major structure) would look like:
(board[0][0] == player && board[0][1] == player && board[0][2] == player)
and repeat for each row.
And similar for vertical, repeating for each column:
(board[0][0] == player && board[1][0] == player && board[2][0] == player)
And one diagonal:
(board[0][0] == player && board[1][1] == player && board[2][2] == player)
If you were determined to use an arithmetic operation then you'd have to change the "player" values to avoid overlap, as in player 1 == 1 and player 2 == 4, such as:
board[row][col] = 0 // no entry
board[row][col] = 1 // player 1
board[row][col] = 4 // player 2
Then you could do something like for a horizontal row:
((board[0][0] + board[0][1] + board[0][2]) == (player * 3))
Note in Java 8 and later adding an int array (a row or column in your case) can be slightly more succinct:
// sum the first row
(IntStream.of(board[0]).sum() == (player * 3))
Now if you really wanted to use the bit-wise "and" operation then this is your check assuming the initial element values (0,1,2) as stated at top:
// check if the player's "bit" is set in all elements of first row.
(board[0][0] & board[0][1] & board[0][2]) == player
I just started coding with more complex methods than the main method. I was given an assignment to make a race with three coins. Whichever coin flips 2 heads and 2 tails first in that order wins. I coded an if else statement to determine which coin wins but neither of the if statements are ever executed. Please tell me if you see an error in my if else statements or somewhere else. I also have to other programs of code that include other methods.
public class FlipRace
{
public static void main (String[] args)
{
final int GOALHEAD = 2;
final int GOALTAIL = 2;
int count1 = 0, count2 = 0, count3 = 0, count10 = 0, count20 = 0, count30 = 0;
// Create three separate coin objects
Coin coin1 = new Coin();
Coin coin2 = new Coin();
Coin coin3 = new Coin();
while (count1 <= GOALHEAD && count10 <= GOALTAIL || count2 <= GOALHEAD && count20 <= GOALTAIL || count3 <= GOALHEAD && count30 <= GOALTAIL)
{
coin1.flip();
coin2.flip();
coin3.flip();
// Print the flip results (uses Coin's toString method)
System.out.print ("Coin 1: " + coin1);
System.out.println (" Coin 2: " + coin2);
System.out.println (" Coin 3: " + coin3);
// Increment or reset the counters
if (coin1.isHeads())
count1++;
else
count10++;
if (coin2.isHeads())
count2++;
else
count20++;
if (coin3.isHeads())
count3++;
else
count30++;
}
// Determine the winner
if (count1 == GOALHEAD && count10 == GOALTAIL)
System.out.println ("Coin 1 wins!");
else if (count2 == GOALHEAD && count20 == GOALTAIL)
System.out.println ("Coin 2 wins!");
else if (count3 == GOALHEAD && count30 == GOALTAIL)
System.out.println ("Coin 3 wins!");
else
System.out.println ("It's a TIE!");
}
}
Here is my output:
Coin 1: Heads Coin 2: Heads
Coin 3: Tails
Coin 1: Heads Coin 2: Heads
Coin 3: Heads
Coin 1: Heads Coin 2: Tails
Coin 3: Heads
Coin 1: Heads Coin 2: Heads
Coin 3: Tails
Coin 1: Heads Coin 2: Tails
Coin 3: Heads
It's a TIE!// this message comes up every time because something is wrong
try changing your comparison to
if (count1 >= GOALHEAD && count10 >= GOALTAIL)
System.out.println ("Coin 1 wins!");
else if (count2 >= GOALHEAD && count20 >= GOALTAIL)
System.out.println ("Coin 2 wins!");
else if (count3 >= GOALHEAD && count30 >= GOALTAIL)
System.out.println ("Coin 3 wins!");
else
System.out.println ("It's a TIE!");
of course another way would to simply debug your code and inspect the values
I don't understand how your code would solve the problem. If I understand it right, you want the first coin that shows the combination H-H-T-T. Now, you are counting the heads and tails in ANY order. So, if you have H-T-H-T for the first coin and H-H-H-T and H-T-T-T for the second and third respectively, the first one wins.
In order to solve the problem considering the order of heads and tails, I think you should change the if-else statement for each coin (I'll make it only for coin1 here):
if (coin1.isHeads()) {
if (count1 < 2 && count2 == 0) { //less than 2 heads and zero tails
count1++;
} else {
count1 = 0;
count10 = 0;
}
} else { //tails
if (count1 == 2 && count10 < 2) { //we already have two heads and 0 or 1 tail
count10++;
} else { // either less than two heads or too many tails - we have to restart!
count1 = 0;
count10 = 0;
}
}
You should also change the while statement... You want to stop when you have two heads ant two tails for any coin. So, it'd be something like this:
while (!(count1 == 2 && count10 == 2) && !(count2 == 2 && count20 == 2) && ....) {...}
I'm building a simple fighting game to test out loops and if statements, however I've run into a kind of complex logic issue.
The loop ends when either the player or enemy HP hits zero however I've discovered that my code can't detect which HP hits zero first results in the player always winning.
Is there a simple way of tracking which number hits zero first therefor breaking the loop?
do {
#SuppressWarnings("resource")
Scanner reader = new Scanner(System.in);
System.out.println("1: Attack. 2: Defend");
int n = reader.nextInt();
if (n == 1){
PHP = (PHP-EATK);
EHP = (EHP-PATK);
} else if (n == 2){
PHP = (PHP-Math.max(0, EATK-PDEF));
}
System.out.println("P "+PHP);
System.out.println(EHP);
}
while (PHP >= 1 || EHP >= 1);
if(PHP <= 0){
System.out.println("You Lose!");
}else if (EHP <= 0){
System.out.println("You win!");
}
Look at your loop continuation condition:
while (PHP >= 1 || EHP >= 1)
It means "while the player or his enemy can fight, go on". In other words, you continue fighting until they both die, at which point you declare the player the winner, even though it's a draw.
Changing the condition to ""while the player and his enemy can fight" will fix this problem.
change while (PHP >= 1 || EHP >= 1); to while (PHP >= 1 && EHP >= 1);.
You using OR operation where you want AND
I am trying to create the scissors-paper-stone-game in Java with a do-while loop. The computer will randomly select 1, and the user makes his choice. The exit condition is if the user wins twice (userWin) or the computer wins twice (compWin). If there is a draw, neither counter increases.
// Scissors, paper, stone game. Best of 3.
// scissors = 0; paper = 1; stone = 2;
import java.util.Scanner;
public class Optional2 {
public static void main(String[] args) {
int userWin = 0;
int compWin = 0;
do {
//comp choice
int comp = 1; //TEST CASE
// int comp = (int) (Math.random() * (2 - 0 + 1) + 0);
//user choice
System.out.println("0 for scissors, 1 for paper, 2 for stone");
Scanner sc = new Scanner(System.in);
int user = sc.nextInt();
//Draw
if (comp == user) {
System.out.println("Draw");
//Win =)
} else if (comp == 0 && user == 2 || comp == 1 && user == 0 ||
comp == 2 && user == 1) {
System.out.println("WIN!");
userWin++;
//Lose =(
} else {
System.out.println("Lose =(");
compWin++;
}
} while (compWin < 2 || userWin < 2);
System.out.println("You won " + userWin + " times!");
}
}
For int comp, it should be random, but I am setting it to 1 (paper) for easy testing.
However, presently only the 1st condition will exit the loop if it becomes true. I am expecting the 2nd condition to exit the loop too if it becomes true with the || operator, but the loop just keeps looping even if it comes true.
ie. if I put while (userWin < 2 || compWin < 2), it will exit if the user wins twice but not if the computer wins twice. If I put while (compWin < 2 || userWin < 2), it will exit if the computer wins twice but not if the user wins twice.
I tried changing it to while ((userWin < 2) || (compWin < 2)) too but it doesn't work.
but the loop just keeps looping even if it comes true
A while loops keeps looping as long as the condition remains true.
I think the problem is that you should rewrite the condition to:
while ((userWin < 2) && (compWin < 2))
with && instead of ||. Indeed: now the while loop is something like: "Keep looping as long as the the user has not won two or more times, and the computer has not won two or more times."
You should use && instead:
while (userWin < 2 && compWin < 2);
This is because you want to be in the loop as long as none of the user or comp gets 2 consecutive wins
That is translated into
userWin < 2 && (=AND) compWin < 2
Which means: as long as both the user AND the comp has less than 2 consecutive wins, stays in the loop.
Or in other words, as you have phrased it: if any of user or comp gets two consecutive wins, gets out from the loop.
Try replace with &&. You need both less that 2 to keep loop going on
The aim of this program is to make a Rock Paper Scissors game. I have succeeded in making it however I can not get it to loop no matter what I try. I tried:
while (index = 0)
while (index < gamesCount)
However, while my index is 0 and my condition says while (index != 0), it seems to be the only condition that runs the program but it will not loop regardless. How can I get my game to loop?
import java.util.Scanner;
import java.util.Random;
public class RockPaperScissors {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Random randomGen = new Random();
//Variables
String player1;
int cpu;
int start = 1;
int end = 3;
int index = 0;
// 1 = Rock | 2 = Scissors | 3 = Paper
//Code
System.out.println("Welcome to Rock, Paper, Scissors!");
while (index != 0) {
System.out.print("Rock, Paper, or Scissors?: ");
player1 = in.nextLine();
cpu = randomGen.nextInt(3);
System.out.println(cpu);
if (player1.equals("Rock") && (cpu == 2)) {
System.out.println("You lose!");
} else if (player1.equals("Rock") && (cpu == 1)) {
System.out.println("You win!");
} else if (player1.equals("Rock") && (cpu == 0)) {
System.out.println("Draw!");
}
// --------------------
if (player1.equals("Scissors") && (cpu == 2)) {
System.out.println("Draw!");
} else if (player1.equals("Scissors") && (cpu == 1)) {
System.out.println("You win!");
} else if (player1.equals("Scissors") && (cpu == 0)) {
System.out.println("You lose!");
}
//---------------------
if (player1.equals("Paper") && (cpu == 2)) {
System.out.println("You lose!");
} else if (player1.equals("Paper") && (cpu == 1)) {
System.out.println("You win!");
} else if (player1.equals("Paper") && (cpu == 0)) {
System.out.println("Draw!");
}
}
}
}
You have your index variable set to 0. The condition of the while loop is saying, if index does not equal 0, execute the code in the loop. Since your index equals 0, the instructions in the loop will not be executed. Also, you will need to update the index variable in the loop so that if the condition you are looking for is met, the code will stop looping.
ie:
int gamesPlayed = 0;
int gamesRequested = 3; // or get this from the user
while (gamesPlayed < gamesRequested){
String player1Choice = in.nextLine();
if(!"".equals(player1)){
// your code
gamesPlayed++;
} else {
System.out.print("Rock, Paper, or Scissors?: ");
}
}
Two mistakes:
while (index != 0);
this is the entire loop. it ends either at the end of the { } block (which you don't have), or at the first ; which is immediately after the statement.
Correct this, though, and it still won't loop:
int index = 0;
// 1 = Rock | 2 = Scissors | 3 = Paper
//Code
System.out.println("Welcome to Rock, Paper, Scissors!");
while (index != 0);
index = 0, so (index != 0) will never return true.
Your index variable is set to a value of 0.
Your while loop says
while (index != 0);
Which means, while the index isn't 0, run my code. The problem is your code will never run then because your index value is always 0.
Try changing it to another value (say 5 for example), and it should work now.
:)