Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
My AI code for a computer player is not working as expected. I want it to play a random move, but block an opponent's incoming winning turn. However, it sometimes stops working altogether, and other times plays a specific move even though there is no incoming win combo. My computer AI code is below.
public void compturn()
{
count++ ;
if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
{
letter = "O" ;
}
else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
{
letter = "X" ;
}
if (b1.getText() == b2.getText() && b2.getText() != "" && b3.getText() == "")
{
b3.setText(letter);
b3bool = false ;
}
else if (b4.getText() == b5.getText() && b6.getText() == "")
{
b6.setText(letter);
b6bool = false ;
}
else if (b7.getText() == b8.getText() && b9.getText() == "")
{
b9.setText(letter);
b9bool = false ;
}
else if (b1.getText() == b4.getText() && b4.getText() != "" && b7.getText() == "")
{
b7.setText(letter);
b7bool = false ;
}
else if (b2.getText() == b5.getText() && b8.getText() == "")
{
b8.setText(letter);
b8bool = false ;
}
else if (b3.getText() == b6.getText() && b9.getText() == "")
{
b9.setText(letter);
b9bool = false ;
}
else if (b1.getText() == b5.getText() && b5.getText() != "" && b9.getText() == "")
{
b9.setText(letter) ;
b9bool = false ;
}
else if (b3.getText() == b5.getText() && b7.getText() == "")
{
b7.setText(letter);
b7bool = false ;
}
else
{
randomMove();
}
}
public void randomMove()
{
int randomnum = (int)(Math.random() * 10);
if(randomnum == 1 )
{
if(b1.getText().equals("X") || b1.getText().equals("O"))
{
randomMove();
}
else
{
b1.setText(letter);
}
}
if(randomnum == 2 )
{
if(b2.getText().equals("X") || b2.getText().equals("O"))
{
randomMove();
}
else
{
b2.setText(letter);
}
}
if(randomnum == 3 )
{
if(b3.getText().equals("X") || b3.getText().equals("O"))
{
randomMove();
}
else
{
b3.setText(letter);
}
}
if(randomnum == 4 )
{
if(b4.getText().equals("X") || b4.getText().equals("O"))
{
randomMove();
}
else
{
b4.setText(letter);
}
}
if(randomnum == 5 )
{
if(b5.getText().equals("X") || b5.getText().equals("O"))
{
randomMove();
}
else
{
b5.setText(letter);
}
}
if(randomnum == 6 )
{
if(b6.getText().equals("X") || b6.getText().equals("O"))
{
randomMove();
}
else
{
b6.setText(letter);
}
}
if(randomnum == 7 )
{
if(b7.getText().equals("X") || b7.getText().equals("O"))
{
randomMove();
}
else
{
b7.setText(letter);
}
}
if(randomnum == 8 )
{
if(b8.getText().equals("X") || b8.getText().equals("O"))
{
randomMove();
}
else
{
b8.setText(letter);
}
}
if(randomnum == 9 )
{
if(b9.getText().equals("X") || b9.getText().equals("O"))
{
randomMove();
}
else
{
b9.setText(letter);
}
}
}
And my complete code for the main game is here
public int oneplayergame()
{
// ----=---------------------- CREATING ALL JBUTTONS ON THE GAME SCREEN AND ADDING ACTION LISTENERS AND REACTIONS -----------------------------------------
b1 = new JButton("");
b1.setToolTipText("Mark this box");
b1.setFont(TToeFont);
b1.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent onclickb1)
{
if (b1bool == true){ count++;
if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
{
letter = "O" ;
}
else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
{
letter = "X" ;
}
b1.setText(letter);
b1bool = false ;
calculatevictory();
compturn();
processturn();
}}});
b2 = new JButton("");
b2.setFont(TToeFont);
b2.setToolTipText("Mark this box");
b2.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent onclickb1)
{
if (b2bool == true){ count++;
if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
{
letter = "O" ;
}
else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
{
letter = "X" ;
}
b2.setText(letter);
b2bool = false ;
calculatevictory();
compturn();
processturn();
}}
});
b3 = new JButton("");
b3.setToolTipText("Mark this box");
b3.setFont(TToeFont);
b3.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent onclickb1)
{
if(b3bool == true){
count++;
if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
{
letter = "O" ;
}
else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
{
letter = "X" ;
}
b3.setText(letter);
b3bool = false ;
calculatevictory();
compturn();
processturn();
}}
});
b4 = new JButton("");
b4.setToolTipText("Mark this box");
b4.setFont(TToeFont);
b4.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent onclickb1)
{
if(b4bool == true){
count++;
if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
{
letter = "O" ;
}
else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
{
letter = "X" ;
}
b4.setText(letter);
b4bool = false ;
calculatevictory();
compturn();
processturn();
}}
});
b5 = new JButton("");
b5.setToolTipText("Mark this box");
b5.setFont(TToeFont);
b5.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent onclickb1)
{
if (b5bool == true){
count++;
if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
{
letter = "O" ;
}
else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
{
letter = "X" ;
}
b5.setText(letter);
b5bool = false ;
calculatevictory();
compturn();
processturn();
}}
});
b6 = new JButton("");
b6.setToolTipText("Mark this box");
b6.setFont(TToeFont);
b6.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent onclickb1)
{
if (b6bool == true){
count++;
if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
{
letter = "O" ;
}
else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
{
letter = "X" ;
}
b6.setText(letter);
b6bool = false ;
calculatevictory();
compturn();
processturn();
}}
});
b7 = new JButton("");
b7.setToolTipText("Mark this box");
b7.setFont(TToeFont);
b7.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent onclickb1)
{
if (b7bool == true){
count++;
if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
{
letter = "O" ;
}
else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
{
letter = "X" ;
}
b7.setText(letter);
b7bool = false ;
calculatevictory();
compturn();
processturn();
}}
});
b8 = new JButton("");
b8.setToolTipText("Mark this box");
b8.setFont(TToeFont);
b8.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent onclickb1)
{
if(b8bool == true){
count++;
if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
{
letter = "O" ;
}
else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
{
letter = "X" ;
}
b8.setText(letter);
b8bool = false ;
calculatevictory();
compturn();
processturn();
}}
});
b9 = new JButton("");
b9.setToolTipText("Mark this box");
b9.setFont(TToeFont);
b9.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent onclickb1)
{
if(b9bool == true){
count++;
if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
{
letter = "O" ;
}
else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
{
letter = "X" ;
}
b9.setText(letter);
b9bool = false ;
calculatevictory();
compturn();
processturn();
}}
});
//CREATING GAME SCREEN LAYOUT
//CREAING GAME SCREEN CONTENT PANE AND ADDING BUTTONS TO IT
// This method checks if someone won the game every time you click a button
public void calculatevictory(){
if (b1.getText() == b2.getText() && b2.getText() == b3.getText() && b1.getText() != "")
{
win = true ;
}
else if (b4.getText() == b5.getText() && b5.getText() == b6.getText() && b4.getText() != "")
{
win = true ;
}
else if (b7.getText() == b8.getText() && b8.getText() == b9.getText() && b7.getText() != "")
{
win = true ;
}
else if (b1.getText() == b4.getText() && b4.getText() == b7.getText() && b1.getText() != "")
{
win = true ;
}
else if (b2.getText() == b5.getText() && b5.getText() == b8.getText() && b2.getText() != "")
{
win = true ;
}
else if (b3.getText() == b6.getText() && b6.getText() == b9.getText() && b3.getText() != "")
{
win = true ;
}
else if (b1.getText() == b5.getText() && b5.getText() == b9.getText() && b1.getText() != "")
{
win = true ;
}
else if (b3.getText() == b5.getText() && b5.getText() == b7.getText() && b3.getText() != "")
{
win = true ;
}
else
{
win = false ;
}
}
// This method sends the win message
public void processturn()
}
// This method resets all game variables
public void resetgame()
{
count = 1 ;
b1bool = true ;
b2bool = true ;
b3bool = true ;
b4bool = true ;
b5bool = true ;
b6bool = true ;
b7bool = true ;
b8bool = true ;
b9bool = true ;
win = false ;
gameinit = true ;
b1.setText("");
b2.setText("");
b3.setText("");
b4.setText("");
b5.setText("");
b6.setText("");
b7.setText("");
b8.setText("");
b9.setText("");
}
public void compturn()
{
}
public void randomMove()
{
}
}
Welcome to AI... there are numerous ways you can do this. I'll give you a few tips.
I assume count is used to determine who's turn it is. I'd suggest you rather create an integer 'turn' and then simply do this:
turn = 1 -turn
...where you currently increment count. If it's 0 than it's o's turn, else x's. You can then remove those two long if statements. (You can also use a boolean flag and just not it each time, like so turn = !turn.)
Now the rest... I see you have no arrays. Are you comfortable using them?
If so, rather define, winning sequences. For example:
int[][] win = new int[][]{{1,2,3}, {4,5,6}, {7,8,9}, {1,4,7}, ...}
Then all you do to determine if you can win, go is to see if you have two of your tokens in spot win[i][0], win[i][1] or win[i][2]. If the third spot it empty, you can win and should move there,
If you can't win, repeat the above process to defend.
If you do not have to defend and you cannot win, move in the centre. If the centre is taken, take a corner, else move random.
This will give you an AI that can still lose sometimes, but will show some intelligence. If you really want to build something unbeatable have a look at the minimax search algorithm.
Good luck!
Related
The phone numbers that I will check have two formats:
(555) 555-5555 and 555-555-5555
However, my if condition keeps failing in the code below. I am trying to check if the str.charAt(0) is a ( or a number
public static boolean isPhoneNumber(String str) {
if (str.contains("-")) {
for (int i = 0; i < str.length(); i++) {
if ((i == 0 && str.charAt(0) != '(')
|| (i == 0 && Character.isDigit(str.charAt(0)) == false)) {
System.out.println(Character.isDigit(str.charAt(0)));
return false;
}
if (i == 4 && str.charAt(4) != ')' || i == 4 && !(Character.isDigit(str.charAt(4)))) {
System.out.println("here2");
return false;
}
if (i == 3 && str.charAt(3) != '-'
|| i == 3 && (Character.isDigit(str.charAt(3)) == false)) {
System.out.println(str.charAt(3));
return false;
}
if (i == 5 && str.charAt(5) != ' ' || i == 5 && !(Character.isDigit(str.charAt(5)))) {
System.out.println("here4");
return false;
}
if (i == 7 && str.charAt(i) != '-' || i == 7 && !(Character.isDigit(str.charAt(i)))) {
System.out.println("here5");
return false;
}
if (i == 9 && str.charAt(9) != '-' || i == 9 && !(Character.isDigit(str.charAt(9)))) {
System.out.println("here6");
return false;
}
if (i != 0 && i != 3 && i != 5 && i != 7 && i != 9 && !(Character.isDigit(str.charAt(i)))) {
System.out.println("here7");
return false;
}
}
return true;
} else {
return false;
}
}
A general regex pattern which might work here is:
^(?:\(\d{3}\)\s*|\d{3}-)\d{3}-\d{4}$
Here is an explanation of the above regex:
^ from the start of the input
(?:
\(\d{3}\) match (xxx)
\s* followed by optional whitespace
| OR
\d{3}- xxx-
)
\d{3}-\d{4} match xxx-xxxx
$ end of the input
Demo
This would cover both versions of the phone number you gave above. In Java, we can use String#matches here:
String phone1 = "(555) 555-5555";
String phone2 = "555-555-5555";
if (phone1.matches("(?:\\(\\d{3}\\)\\s*|\\d{3}-)\\d{3}-\\d{4}")) {
System.out.println(phone1 + " is in a valid format");
}
if (phone2.matches("(?:\\(\\d{3}\\)\\s*|\\d{3}-)\\d{3}-\\d{4}")) {
System.out.println(phone2 + " is in a valid format");
}
I have a quick question. I want to make my code shorter and I'm wondering whether I can put in some way below checkboxes into loop. The sense of this part of code is to enable "Find" button in case when at least one of checkbox is selected. Thank you in advance for every tip.
if (checkBoxes[0].isSelected() == true || checkBoxes[1].isSelected() == true
|| checkBoxes[2].isSelected() == true || checkBoxes[3].isSelected() == true || checkBoxes[4].isSelected() == true
|| checkBoxes[5].isSelected() == true || checkBoxes[6].isSelected() == true || checkBoxes[7].isSelected() == true
|| checkBoxes[8].isSelected() == true || checkBoxes[9].isSelected() == true || checkBoxes[10].isSelected() == true
|| checkBoxes[11].isSelected() == true || checkBoxes[12].isSelected() == true || checkBoxes[13].isSelected() == true
|| checkBoxes[14].isSelected() == true || checkBoxes[15].isSelected() == true || checkBoxes[16].isSelected() == true
|| checkBoxes[17].isSelected() == true || checkBoxes[18].isSelected() == true || checkBoxes[19].isSelected() == true
|| checkBoxes[20].isSelected() == true || checkBoxes[21].isSelected() == true) {
button.setEnabled(true);
Of course you can :
boolean found = false;
for (int i = 0; i < checkBoxes.length && !found; i++) {
found = checkBoxes[i].isSelected();
}
if (found) {
button.setEnabled(true);
}
or you can avoid the boolean variable and break out of the loop when you find the first selected checkbox :
for (int i = 0; i < checkBoxes.length; i++) { // you can also replace this with enhanced
// for loop
if (checkBoxes[i].isSelected()) {
button.setEnabled(true);
break;
}
}
Why not to use stream?
if (Arrays.stream(checkBoxes).anyMatch(checkbox -> checkbox.isSelected())) {
button.setEnabled(true);
}
As you have an array of course you can use a loop.
Here is a version with an enhanced loop :
for (Checkbox checkBox : checkBoxes){
if (checkBox.isSelected()){
button.setEnabled(true);
break;
}
}
try this:
for(int i=0; i < checkBoxes.length; i++) {
if(checkBoxes[i].isSelected()) {
button.setEnabled(true);
break;
}
}
Boolean j = false;
for (byte i = 0; i <= 21)
if (checkBoxes[i].isSelected() == true) {
j = true;
break;
if (j == true) {
//your code
}
you van use this code
it is so easy
need to get the card issuer along with the number, only outputs "Unknown".
(the bottom is just tester code).
am i trying to test the wrong variable, am i incorrectly using indexOf()? please, any help would be appreciated
public class CreditCard
{
private String card_number;
private boolean is_number;
private String number_string = "";
public String issuer_name = "";
public CreditCard(String card_number)
{
this.card_number = card_number;
}
public String toString()
{
for (int x = 0; x < card_number.length(); x++)
{
char y = card_number.charAt(x);
is_number = Character.isDigit(y);
if (is_number)
{
number_string += y;
}
}
String s = number_string + " was issued by " + getIssuer();
return s;
}
public void setIssuer(String issuer)
{
issuer_name = issuer;
}
public String getIssuer()
{
String issuer_Name;
if (card_number.indexOf('4') == 0 && card_number.length() == 13 || card_number.length() == 16)
{
issuer_Name = "VISA";
}
if (card_number.indexOf('3') == 0 && card_number.indexOf('0') == 1 && card_number.indexOf('0') == 2 && number_string.length() == 14)
{
issuer_Name = "Diner's Club";
}
if (card_number.indexOf('3') == 0 && card_number.indexOf('0') == 1 && card_number.indexOf('5') == 2 && number_string.length() == 14)
{
issuer_Name = "Diner's Club";
}
if (card_number.indexOf('3') == 0 && card_number.indexOf('6') == 1 && card_number.length() == 14)
{
issuer_Name = "Diner's Club";
}
if (card_number.indexOf('3') == 0 && card_number.indexOf('8') == 1 && card_number.length() == 14)
{
issuer_Name = "Diner's Club";
}
if (card_number.indexOf('3') == 0 && card_number.indexOf('4') == 1 && card_number.length() == 15)
{
issuer_Name = "American Express";
}
if (card_number.indexOf('3') == 0 && card_number.indexOf('7') == 1 && card_number.length() == 15)
{
issuer_Name = "American Express";
}
if (card_number.indexOf('5') == 0 && card_number.indexOf('1') == 1 && card_number.length() == 16)
{
issuer_Name = "MasterCard";
}
if (card_number.indexOf('5') == 0 && card_number.indexOf('5') == 1 && card_number.length() == 16)
{
issuer_Name = "MasterCard";
}
if (card_number.indexOf('6') == 0 && card_number.indexOf('0') == 1 && card_number.indexOf('1') == 2 && number_string.indexOf('1') == 3 && number_string.length() == 16)
{
issuer_Name = "Discover";
}
else
{
issuer_Name = "Unknown";
}
return issuer_Name;
}
public static void main(String[] args)
{
System.out.println(new CreditCard("42225-22222222"));
System.out.println(new CreditCard("76009644571"));
System.out.println(new CreditCard("50197170-10103742"));
System.out.println(new CreditCard("6331101899890016"));
}
}
The if else clause would start something like
if (card_number.indexOf('4') == 0 && card_number.length() == 13 || card_number.length() == 16) {
issuer_Name = "VISA";
} else if (card_number.indexOf('3') == 0 && card_number.indexOf('0') == 1 && card_number.indexOf('0') == 2 && number_string.length() == 14) {
issuer_Name = "Diner's Club";
} else if (card_number.indexOf('3') == 0 && card_number.indexOf('0') == 1 && card_number.indexOf('5') == 2 && number_string.length() == 14) {
issuer_Name = "Diner's Club";
} else if (card_number.indexOf('3') == 0 && card_number.indexOf('6') == 1 && card_number.length() == 14) {
issuer_Name = "Diner's Club";
} else {
issuer_Name = "Other";
}
Note I am not looking at the correctness of the algorithm, but you asked for how to do the if/else
if (card_number.indexOf('6') == 0 && card_number.indexOf('0') == 1 && card_number.indexOf('1') == 2 && number_string.indexOf('1') == 3 && number_string.length() == 16)
{
issuer_Name = "Discover";
}
else
{
issuer_Name = "Unknown";
}
Check this Code.
If a card issuer is not Discover, the output ALWAYS "Unknow"
if (true) {
n=1;
}
if (true) {
n=2;
}
if (true) {
n=3;
}
else {
n=0;
}
The n is either 3 or 0, cannot be 1 or 2.
Because the last if-else will override the n
You can fix this issue by changing "if" to "else if"
So I've been coding my TicTacToe project as a side project for some time now, and have hit another obstacle. I want to use a JButton in more than one method, but I don't know how to go about doing that. Here's my code till now.
`
import java.util.Random ;
import java.util.Scanner ;
import javax.swing.JOptionPane ;
import javax.swing.JFrame ;
import javax.swing.JPanel ;
import java.util.InputMismatchException ;
import java.awt.BorderLayout ;
import java.awt.* ;
import java.awt.event.* ;
import javax.swing.JTextArea ;
import javax.swing.JButton ;
import javax.swing.JRadioButton ;
class TicTacToe
{
public int count = 1 ;
public String letter;
public boolean b1bool = true ;
public boolean b2bool = true ;
public boolean b3bool = true ;
public boolean b4bool = true ;
public boolean b5bool = true ;
public boolean b6bool = true ;
public boolean b7bool = true ;
public boolean b8bool = true ;
public boolean b9bool = true ;
public boolean win = false ;
public void main(String []args)
{
popupintroscreen();
}
public void popupintroscreen()
{
JTextArea introtext = new JTextArea("Welcome to TicTacToe v1.0. This is a Simple Tic Tac Toe app coded by Abhishek Pisharody. Press the button below to play, or view the instructions first, if you prefer. We hope you enjoy playing. Thank you.");
introtext.setEditable(false);
introtext.setLineWrap(true);
JButton startgamebutton = new JButton("Start Game");
startgamebutton.setToolTipText("Start a game of Tic-Tac-Toe");
startgamebutton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent gamestart)
{
JOptionPane.showMessageDialog(null, "Loading.....done!");
tictactoe();
}
});
JButton showinstructions = new JButton("Show Instructions");
showinstructions.setToolTipText("View game instructions. Worth checking out even if you know how to play.");
showinstructions.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent displayinstructionsprompt)
{
JOptionPane.showMessageDialog(null, "Nothing to see here..yet..off you go!");
}
});
JButton highscoresbutton = new JButton("High Scores");
highscoresbutton.setToolTipText("Show high scores for the game");
highscoresbutton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent highscoresbuttonclicked)
{
JOptionPane.showMessageDialog(null,"Not coded yet!");
}
});
JButton quitgamebutton = new JButton("Quit Game");
quitgamebutton.setToolTipText("Quit the game. But why? :(");
quitgamebutton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent onquitgamebuttonclick)
{
JOptionPane.showConfirmDialog(null, "Really quit?");
System.exit(0);
}
});
JPanel gamebuttonsholder = new JPanel(new BorderLayout());
gamebuttonsholder.setSize(400,100);
gamebuttonsholder.add(introtext,BorderLayout.PAGE_START);
gamebuttonsholder.add(startgamebutton,BorderLayout.PAGE_END);
gamebuttonsholder.add(showinstructions,BorderLayout.LINE_START);
gamebuttonsholder.add(highscoresbutton,BorderLayout.CENTER);
gamebuttonsholder.add(quitgamebutton,BorderLayout.LINE_END);
JFrame introscreen = new JFrame("Tic Tac Toe");
introscreen.setSize(400,400);
introscreen.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
introscreen.setLocationRelativeTo(null);
introscreen.add(gamebuttonsholder);
introscreen.setVisible(true);
}
public int tictactoe()
{
final JButton b1 = new JButton("");
b1.setToolTipText("Mark this box");
b1.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent onclickb1)
{
if (b1bool == true){ count++;
if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
{
letter = "O" ;
}
else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
{
letter = "X" ;
}
b1.setText(letter);
b1bool = false ;
calculatevictory();
processturn();
}}});
final JButton b2 = new JButton("");
b2.setToolTipText("Mark this box");
b2.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent onclickb1)
{
if (b2bool == true){ count++;
if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
{
letter = "O" ;
}
else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
{
letter = "X" ;
}
b2.setText(letter);
b2bool = false ;
calculatevictory();
processturn();
}}
});
final JButton b3 = new JButton("");
b3.setToolTipText("Mark this box");
b3.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent onclickb1)
{
if(b3bool == true){
count++;
if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
{
letter = "O" ;
}
else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
{
letter = "X" ;
}
b3.setText(letter);
b3bool = false ;
calculatevictory();
processturn();
}}
});
final JButton b4 = new JButton("");
b4.setToolTipText("Mark this box");
b4.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent onclickb1)
{
if(b4bool == true){
count++;
if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
{
letter = "O" ;
}
else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
{
letter = "X" ;
}
b4.setText(letter);
b4bool = false ;
calculatevictory();
processturn();
}}
});
final JButton b5 = new JButton("");
b5.setToolTipText("Mark this box");
b5.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent onclickb1)
{
if (b5bool == true){
count++;
if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
{
letter = "O" ;
}
else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
{
letter = "X" ;
}
b5.setText(letter);
b5bool = false ;
calculatevictory();
processturn();
}}
});
final JButton b6 = new JButton("");
b6.setToolTipText("Mark this box");
b6.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent onclickb1)
{
if (b6bool == true){
count++;
if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
{
letter = "O" ;
}
else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
{
letter = "X" ;
}
b6.setText(letter);
b6bool = false ;
calculatevictory();
processturn();
}}
});
final JButton b7 = new JButton("");
b7.setToolTipText("Mark this box");
b7.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent onclickb1)
{
if (b7bool == true){
count++;
if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
{
letter = "O" ;
}
else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
{
letter = "X" ;
}
b7.setText(letter);
b7bool = false ;
calculatevictory();
processturn();
}}
});
final JButton b8 = new JButton("");
b8.setToolTipText("Mark this box");
b8.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent onclickb1)
{
if(b8bool == true){
count++;
if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
{
letter = "O" ;
}
else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
{
letter = "X" ;
}
b8.setText(letter);
b8bool = false ;
calculatevictory();
processturn();
}}
});
final JButton b9 = new JButton("");
b9.setToolTipText("Mark this box");
b9.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent onclickb1)
{
if(b9bool == true){
count++;
if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
{
letter = "O" ;
}
else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
{
letter = "X" ;
}
b9.setText(letter);
b9bool = false ;
calculatevictory();
processturn();
}}
});
GridLayout gamescreenlayout = new GridLayout(3,3);
JPanel gamescreencontent = new JPanel();
gamescreencontent.setLayout(gamescreenlayout);
gamescreencontent.setSize(400,400);
gamescreencontent.add(b1);
gamescreencontent.add(b2);
gamescreencontent.add(b3);
gamescreencontent.add(b4);
gamescreencontent.add(b5);
gamescreencontent.add(b5);
gamescreencontent.add(b6);
gamescreencontent.add(b7);
gamescreencontent.add(b8);
gamescreencontent.add(b9);
JFrame gamescreen = new JFrame("Tic-Tac-Toe");
gamescreen.setSize(400,400) ;
gamescreen.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gamescreen.setLocationRelativeTo(null);
gamescreen.add(gamescreencontent);
gamescreen.setVisible(true);
int sexyshit = 1 ;
return sexyshit ;
}
public void calculatevictory(){
if (b1.getText() == b2.getText() && b2.getText() == b3.getText() && b1.getText() != "")
{
win = true ;
}
else if (b4.getText() == b5.getText() && b5.getText() == b6.getText() && b4.getText() != "")
{
win = true ;
}
else if (b7.getText() == b8.getText() && b8.getText() == b9.getText() && b7.getText() != "")
{
win = true ;
}
else if (b1.getText() == b4.getText() && b4.getText() == b7.getText() && b1.getText() != "")
{
win = true ;
}
else if (b2.getText() == b5.getText() && b5.getText() == b8.getText() && b2.getText() != "")
{
win = true ;
}
else if (b3.getText() == b6.getText() && b6.getText() == b9.getText() && b3.getText() != "")
{
win = true ;
}
else if (b1.getText() == b5.getText() && b5.getText() == b9.getText() && b1.getText() != "")
{
win = true ;
}
else if (b3.getText() == b5.getText() && b5.getText() == b7.getText() && b3.getText() != "")
{
win = true ;
}
else
{
win = false ;
}
}
public void processturn()
{
if (win == true)
{
JOptionPane.showMessageDialog(null, letter + "wins!");
}
else if ( count == 9 && win == false)
{
JOptionPane.showMessageDialog(null, "Tie Game");
}
}
}`
When I try to run this, it tells me that the compiler couldn't find symbol b1. Would I have to make the buttons public(if so, how?), or use Inheritance? If it's the latter, please explain in simple terms, because I really haven't begun to learn inheritance yet.
Thank you in advance.
Declare your JButton outside the method, in the same place as where you are declaring your int, String, and booleans. In other words, something like
class TicTacToe
{
//...
JButton b1;
//...
public int TicTacToe()
{
b1 = new JButton(); //note that you don't need the ""
}
}
Incidentally, I'd recommend using arrays and looping through them rather than having 9 of everything and having to copy-paste code lots of times.
I've almost put the wraps on my program, but I want to add some way for users to play against the computer. For this, I need to create some kind of conditional logic based AI, but can't see which approach to take.
I don't want the computer to take its turn randomly, I want it to actually play like a human player. Would I have to use a deeply nested if statements and multiple moves for each possible turn, or use some kind of for or while loop?
My code reduced to just the WinChecker is here:
public void calculatevictory(){
if (b1.getText() == b2.getText() && b2.getText() == b3.getText() && b1.getText() != "")
{
win = true ;
}
else if (b4.getText() == b5.getText() && b5.getText() == b6.getText() && b4.getText() != "")
{
win = true ;
}
else if (b7.getText() == b8.getText() && b8.getText() == b9.getText() && b7.getText() != "")
{
win = true ;
}
else if (b1.getText() == b4.getText() && b4.getText() == b7.getText() && b1.getText() != "")
{
win = true ;
}
else if (b2.getText() == b5.getText() && b5.getText() == b8.getText() && b2.getText() != "")
{
win = true ;
}
else if (b3.getText() == b6.getText() && b6.getText() == b9.getText() && b3.getText() != "")
{
win = true ;
}
else if (b1.getText() == b5.getText() && b5.getText() == b9.getText() && b1.getText() != "")
{
win = true ;
}
else if (b3.getText() == b5.getText() && b5.getText() == b7.getText() && b3.getText() != "")
{
win = true ;
}
else
{
win = false ;
}
}
My code so far is here:
/* PROGRAM NAME : TIC TAC TOE
* AUTHOR : Jack Robinson
* DATE : 7/17/2014
*/
// Importing necessary classes and directories
import java.util.Random ;
import java.util.Scanner ;
import javax.swing.JOptionPane ;
import javax.swing.JFrame ;
import javax.swing.JPanel ;
import java.util.InputMismatchException ;
import java.awt.BorderLayout ;
import java.awt.* ;
import java.awt.event.* ;
import javax.swing.JTextArea ;
import javax.swing.JButton ;
import javax.swing.JRadioButton ;
import java.awt.Font ;
//Creating class
class TicTacToe
{
//Declaring all instance members
public int count = 1 ;
public String letter;
public boolean b1bool = true ;
public boolean b2bool = true ;
public boolean b3bool = true ;
public boolean b4bool = true ;
public boolean b5bool = true ;
public boolean b6bool = true ;
public boolean b7bool = true ;
public boolean b8bool = true ;
public boolean b9bool = true ;
public boolean win = false ;
public boolean gameinit = true ;
private JButton b1 ;
private JButton b2 ;
private JButton b3 ;
private JButton b4 ;
private JButton b5 ;
private JButton b6 ;
private JButton b7 ;
private JButton b8 ;
private JButton b9 ;
private JFrame gamescreen ;
private JFrame introscreen ;
public Font TToeFont = new Font("Arial",Font.PLAIN,40);
// Main method
public static void main(String []args)
{
// Calls the method which pops up the intro screen ;
TicTacToe runnext = new TicTacToe();
runnext.popupintroscreen();
}
public void popupintroscreen()
{
//Creating introduction text and it's wrapper
JTextArea introtext = new JTextArea("Welcome to TicTacToe v1.0. This is a Simple Tic Tac Toe app coded by Abhishek Pisharody. Press the button below to play, or view the instructions first, if you prefer. We hope you enjoy playing. Thank you.");
introtext.setEditable(false);
introtext.setLineWrap(true);
// ----------------------------------- DECLARING ALL JBUTTONS IN THE INTRO SCREEN AND ADDING ACTION LISTENERS ---------------------------------------------------
JButton startgamebutton = new JButton("Start Game");
startgamebutton.setToolTipText("Start a game of Tic-Tac-Toe");
startgamebutton.setFont(TToeFont);
startgamebutton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent gamestart)
{
if(gameinit == true){
JOptionPane.showMessageDialog(null, "Loading.....done!");
tictactoe();
gameinit = false;
} else {
JOptionPane.showMessageDialog(null, "The game is already running" , "Error" , JOptionPane.ERROR_MESSAGE);
}
}
});
JButton showinstructions = new JButton("Show Instructions");
showinstructions.setToolTipText("View game instructions. Worth checking out even if you know how to play.");
showinstructions.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent displayinstructionsprompt)
{
JOptionPane.showMessageDialog(null, "Nothing to see here..yet..off you go!");
}
});
JButton highscoresbutton = new JButton("High Scores");
highscoresbutton.setToolTipText("Show high scores for the game");
highscoresbutton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent highscoresbuttonclicked)
{
JOptionPane.showMessageDialog(null,"Not coded yet!");
}
});
JButton quitgamebutton = new JButton("Quit Game");
quitgamebutton.setToolTipText("Quit the game. But why? :(");
quitgamebutton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent onquitgamebuttonclick)
{
int response = JOptionPane.showConfirmDialog(null, "Are you sure you want to quit the game?" , "Really quit?" , JOptionPane.YES_NO_OPTION );
if(response == JOptionPane.YES_OPTION)
{
System.exit(0);
}
}
});
//Creating intro screen content pane and adding buttons to it
JPanel gamebuttonsholder = new JPanel(new BorderLayout());
gamebuttonsholder.setSize(400,100);
gamebuttonsholder.add(introtext,BorderLayout.PAGE_START);
gamebuttonsholder.add(startgamebutton,BorderLayout.PAGE_END);
gamebuttonsholder.add(showinstructions,BorderLayout.LINE_START);
gamebuttonsholder.add(highscoresbutton,BorderLayout.CENTER);
gamebuttonsholder.add(quitgamebutton,BorderLayout.LINE_END);
//Creating the screen itself and setting it visible
introscreen = new JFrame("Tic Tac Toe");
introscreen.setSize(400,400);
introscreen.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
introscreen.setLocationRelativeTo(null);
introscreen.add(gamebuttonsholder);
introscreen.setVisible(true);
}
// Creating the method which powers the game ;
public int tictactoe()
{
// ----=---------------------- CREATING ALL JBUTTONS ON THE GAME SCREEN AND ADDING ACTION LISTENERS AND REACTIONS -----------------------------------------
b1 = new JButton("");
b1.setToolTipText("Mark this box");
b1.setFont(TToeFont);
b1.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent onclickb1)
{
if (b1bool == true){ count++;
if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
{
letter = "O" ;
}
else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
{
letter = "X" ;
}
b1.setText(letter);
b1bool = false ;
calculatevictory();
processturn();
}}});
b2 = new JButton("");
b2.setFont(TToeFont);
b2.setToolTipText("Mark this box");
b2.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent onclickb1)
{
if (b2bool == true){ count++;
if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
{
letter = "O" ;
}
else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
{
letter = "X" ;
}
b2.setText(letter);
b2bool = false ;
calculatevictory();
processturn();
}}
});
b3 = new JButton("");
b3.setToolTipText("Mark this box");
b3.setFont(TToeFont);
b3.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent onclickb1)
{
if(b3bool == true){
count++;
if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
{
letter = "O" ;
}
else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
{
letter = "X" ;
}
b3.setText(letter);
b3bool = false ;
calculatevictory();
processturn();
}}
});
b4 = new JButton("");
b4.setToolTipText("Mark this box");
b4.setFont(TToeFont);
b4.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent onclickb1)
{
if(b4bool == true){
count++;
if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
{
letter = "O" ;
}
else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
{
letter = "X" ;
}
b4.setText(letter);
b4bool = false ;
calculatevictory();
processturn();
}}
});
b5 = new JButton("");
b5.setToolTipText("Mark this box");
b5.setFont(TToeFont);
b5.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent onclickb1)
{
if (b5bool == true){
count++;
if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
{
letter = "O" ;
}
else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
{
letter = "X" ;
}
b5.setText(letter);
b5bool = false ;
calculatevictory();
processturn();
}}
});
b6 = new JButton("");
b6.setToolTipText("Mark this box");
b6.setFont(TToeFont);
b6.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent onclickb1)
{
if (b6bool == true){
count++;
if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
{
letter = "O" ;
}
else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
{
letter = "X" ;
}
b6.setText(letter);
b6bool = false ;
calculatevictory();
processturn();
}}
});
b7 = new JButton("");
b7.setToolTipText("Mark this box");
b7.setFont(TToeFont);
b7.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent onclickb1)
{
if (b7bool == true){
count++;
if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
{
letter = "O" ;
}
else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
{
letter = "X" ;
}
b7.setText(letter);
b7bool = false ;
calculatevictory();
processturn();
}}
});
b8 = new JButton("");
b8.setToolTipText("Mark this box");
b8.setFont(TToeFont);
b8.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent onclickb1)
{
if(b8bool == true){
count++;
if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
{
letter = "O" ;
}
else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
{
letter = "X" ;
}
b8.setText(letter);
b8bool = false ;
calculatevictory();
processturn();
}}
});
b9 = new JButton("");
b9.setToolTipText("Mark this box");
b9.setFont(TToeFont);
b9.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent onclickb1)
{
if(b9bool == true){
count++;
if(count == 1||count == 3 || count == 5 || count == 7 || count == 9 || count == 11)
{
letter = "O" ;
}
else if ( count == 2 || count == 4 || count == 6 || count == 8 || count == 10)
{
letter = "X" ;
}
b9.setText(letter);
b9bool = false ;
calculatevictory();
processturn();
}}
});
//CREATING GAME SCREEN LAYOUT
GridLayout gamescreenlayout = new GridLayout(3,3);
//CREAING GAME SCREEN CONTENT PANE AND ADDING BUTTONS TO IT
JPanel gamescreencontent = new JPanel();
gamescreencontent.setLayout(gamescreenlayout);
gamescreencontent.setSize(400,400);
gamescreencontent.add(b1);
gamescreencontent.add(b2);
gamescreencontent.add(b3);
gamescreencontent.add(b4);
gamescreencontent.add(b5);
gamescreencontent.add(b5);
gamescreencontent.add(b6);
gamescreencontent.add(b7);
gamescreencontent.add(b8);
gamescreencontent.add(b9);
// CREATING GAME SCREEN AND SETTING IT VISIBLE
gamescreen = new JFrame("Tic-Tac-Toe");
gamescreen.setSize(400,400) ;
gamescreen.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gamescreen.setLocationRelativeTo(null);
gamescreen.add(gamescreencontent);
gamescreen.setVisible(true);
int gamestuff = 1 ;
return gamestuff ;
}
// This method checks if someone won the game every time you click a button
public void calculatevictory(){
if (b1.getText() == b2.getText() && b2.getText() == b3.getText() && b1.getText() != "")
{
win = true ;
}
else if (b4.getText() == b5.getText() && b5.getText() == b6.getText() && b4.getText() != "")
{
win = true ;
}
else if (b7.getText() == b8.getText() && b8.getText() == b9.getText() && b7.getText() != "")
{
win = true ;
}
else if (b1.getText() == b4.getText() && b4.getText() == b7.getText() && b1.getText() != "")
{
win = true ;
}
else if (b2.getText() == b5.getText() && b5.getText() == b8.getText() && b2.getText() != "")
{
win = true ;
}
else if (b3.getText() == b6.getText() && b6.getText() == b9.getText() && b3.getText() != "")
{
win = true ;
}
else if (b1.getText() == b5.getText() && b5.getText() == b9.getText() && b1.getText() != "")
{
win = true ;
}
else if (b3.getText() == b5.getText() && b5.getText() == b7.getText() && b3.getText() != "")
{
win = true ;
}
else
{
win = false ;
}
}
// This method sends the win message
public void processturn()
{
if (win == true)
{
int restart = JOptionPane.showConfirmDialog(null, letter + " wins! Play again? " ,letter + " Wins!" , JOptionPane.YES_NO_OPTION);
if(restart == JOptionPane.NO_OPTION)
{
gamescreen.dispose();
resetgame();
}
else {
resetgame();
}}
else if ( count == 10 && win == false)
{
JOptionPane.showMessageDialog(null, "Tie Game");
resetgame();
}
}
// This method resets all game variables
public void resetgame()
{
count = 1 ;
b1bool = true ;
b2bool = true ;
b3bool = true ;
b4bool = true ;
b5bool = true ;
b6bool = true ;
b7bool = true ;
b8bool = true ;
b9bool = true ;
win = false ;
gameinit = true ;
b1.setText("");
b2.setText("");
b3.setText("");
b4.setText("");
b5.setText("");
b6.setText("");
b7.setText("");
b8.setText("");
b9.setText("");
}
}
// END OF PROGRAM
Here you go, an entire tic-tac-toe in less than 70 lines of code (in Scala - totally impossible to be this concise in many other languages). First argument to the application is a "true" or "false" to specify human first. Second argument is an integer that will control the depth in which the AI will think (how many moves ahead). Use coordinates to specify your move (starting at 0,0). The App will print the board each move and stop when the game has ended.
It uses a simple brute force lookahead AI, which by the way is very slow for the first couple of moves. You could optimize this either by:
Adding memoization so game trees are not recomputed
Adding a lookup table for opening moves
Just optimize the code, so using mutable data structures and such
code:
import scalaz.syntax.id._
import scala.collection.immutable.IndexedSeq
import scala.util.Try
case class Board(moves: List[(Int, Int)], maxDepth: Int = 4) {
val grid: IndexedSeq[(Int, Int)] = (0 to 2).flatMap(i => (0 to 2).map((_, i)))
def isThree(l: List[(Int, Int)], axis: ((Int, Int)) => Int): Boolean =
l.map(_.swap |> axis).distinct.size == 3 && (l.map(axis).distinct.size == 1 ||
l.map(axis) == l.map(_.swap |> axis) || l.map(axis) == l.map(_.swap |> axis).reverse)
def playerWon(player: List[((Int, Int), Int)]): Boolean =
player.map(_._1).combinations(3).map(_.sortBy(_._1)).exists(p => isThree(p, _._1) || isThree(p, _._2))
def hasWinner: Boolean = {
val (crosses, circles) = moves.zipWithIndex.partition(_._2 % 2 == 0)
playerWon(crosses) || playerWon(circles)
}
def computerMove: Board = Board({
val remainingMoves = grid.filterNot(moves.contains)
var (mvOpt, badMoves, depth) = (Option.empty[(Int, Int)], Set.empty[(Int, Int)], 1)
while (mvOpt.isEmpty && depth <= maxDepth) {
val lookAheadFunc: ((Int, Int)) => Boolean = mv => Board(mv +: moves, maxDepth) |>
List.fill[Board => Board](depth - 1)(_.computerMove).foldLeft[Board => Board](identity)(_ compose _) |>
(_.hasWinner)
if (remainingMoves.size >= depth) mvOpt = if (depth % 2 == 0) {
badMoves ++= remainingMoves.filter(lookAheadFunc)
val okMoves = remainingMoves.filterNot(badMoves)
if (okMoves.size == 1) okMoves.headOption else None
} else remainingMoves.filterNot(badMoves).find(lookAheadFunc)
depth += 1
}
mvOpt.getOrElse(remainingMoves.filterNot(badMoves).headOption.getOrElse(remainingMoves.head))
} +: moves, maxDepth)
def print: Board = {
(0 to 2).reverse.foreach(i => println((moves.reverse.zipWithIndex.map(p =>
if (p._2 % 2 == 0) (p._1, "X") else (p._1, "O")) ++
grid.filterNot(moves.contains).map((_, "B"))).filter(_._1._2 == i).sortBy(_._1._1).map(_._2).mkString))
this
}
def humanAttempt: Try[Board] = Try({
val Array(x, y) = readLine("Your move (of form x,y) $ ").split(",").map(_.toInt)
require(!(x > 2 || x < 0 || y > 2 || y < 0 || moves.contains((x, y))), "Move not valid: " +(x, y))
Board((x, y) +: moves, maxDepth)
})
def humanMove: Board = {
var moveAttempt = humanAttempt
while (moveAttempt.isFailure) {
println("Bad move: " + moveAttempt.failed.get.getMessage)
moveAttempt = humanAttempt
}
moveAttempt.get
}
}
object TicTacToe extends App {
var (board, humanNext) = (Board(Nil, args.drop(1).headOption.map(_.toInt).getOrElse(4)).print, args(0).toBoolean)
while (!board.hasWinner && board.moves.size != 9) {
board = (if (humanNext) board.humanMove else {
println("Computer moving")
board.computerMove
}).print
humanNext = !humanNext
}
}