How to check if a coordinate is adjacent to another? - java

I am writing a snake game. I want to write a method to check if the head (index 0) is next to any other body part. I am not sure what is going wrong, but this method does not do anything. I have it set so that if it returns true the game ends (for testing purposes)
Here is my code:
public boolean headNextToBody()
{
boolean xClose = false;
boolean yClose = false;
for(int i = 0; i < bodyParts; i++)
{
if( x[i] == (x[0] + 1) || x[i] == (x[0] - 1))
{
xClose = true;
}
if(y[i] == y[0] + 1 || y[i] == y[0] - 1)
{
yClose = true;
}
}
return (xClose && yClose);
}

Firstly, no need to include the head (at position 0) in the test, as it will always be false.
for(int i = 1; i < bodyParts; i++)
The conditions for adjacency are
(y[i] == y[0]) && (x[i] == (x[0] + 1) || x[i] == (x[0] - 1))
or
(x[i] == x[0]) && (y[i] == (y[0] + 1) || y[i] == (y[0] - 1))
If either of these are true for any non-head point on the snake you can return true immediately, otherwise return false.
You can combine the separate tests into a single if statement:
public boolean headNextToBody()
{
for(int i = 1; i < bodyParts; i++)
{
if(((y[i] == y[0]) && (x[i] == (x[0] + 1) || x[i] == (x[0] - 1))) ||
((x[i] == x[0]) && (y[i] == (y[0] + 1) || y[i] == (y[0] - 1)))
{
return true;
}
}
return false;
}
Alternatively you could shorten the test a little by using some math:
public boolean headNextToBody()
{
for(int i = 1; i < bodyParts; i++)
{
if(1 == ((x[i]-x[0])*(x[i]-x[0]) + (y[i]-y[0])*(y[i]-y[0]))
{
return true;
}
}
return false;
}

Related

How to reverse for loop?

I have a method with some logic
first it looked like:
static boolean checkWin(char dot) {
if (map[0][0] == dot && map[0][1] == dot && map[0][2] == dot) {
return true;
}
//more code
if (map[0][2] == dot && map[1][1] == dot && map[2][0] == dot) {
return true;
}
return false;
}
With loops I refactored the method:
static boolean checkWin(char dot) {
for (int i = 0; i <map.length ; i++) {
for (int j = 0; j < map[i].length; j++) {
if (map[0][i] == dot && i == 2) {
return true;
}
if (map[1][i] == dot && i == 2) {
return true;
}
if (map[2][i] == dot && i == 2) {
return true;
}
if (map[i][0] == dot && i == 2) {
return true;
}
if (map[i][1] == dot && i == 2) {
return true;
}
if (map[i][2] == dot && i == 2) {
return true;
}
if (map[i][i] == dot && i == 2) {
return true;
}
if (map[0][2] == dot && map[1][1] == dot && map[2][0] == dot) {
return true;
}
}
}
return false;
}
I have a problem with this line of code:
if (map[0][2] == dot && map[1][1] == dot && map[2][0] == dot)
return true;
}
I need to get map[i][?], ? should assume the value 2, 1 and 0 when i equals to 0, 1 and 2 respectively.
How can I achieve it?
Try to decrease it
for (int i = 2; i > = 0; i--) {
}
i will be 2 1 0
P.S
I think you missed 2 there
P.S
If I understand your question correctly, you need to have 2 1 0 inside loop without modifying for itself? In that case try:
for (int i = 3; i < 3; i++) {
... 2 - i
}

Java - Roman Numeral validity

I am writing a program to add two roman numerals without converting to any bases. I have everything working except I am not sure how to check if my input String is a valid roman numeral or not.
These are the rules to check validity:
Five in a row of any digit is not allowed
Some digits are allowed in runs of up to 4. They are I,X,C, and M. The others (V,L,D) can only appear singly.
Some lower digits can come before a higher digit, but only if they appear singly. E.g. "IX" is ok but "IIIX" is not.
But this is only for pairs of digits. Three ascending numbers in a row is invalid. E.g. "IX" is ok but "IXC" is not.
A single digit with no runs is always allowed
I have not really been able to make much progress with this step and don't have anything working yet. Any help would be great!
Why not use regular expression:
boolean valid = word.matches("^M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$");
Look at the post of paxdiablo:
How do you match only valid roman numerals with a regular expression?
Loop through each character in the string.
Use a if conditions to check which character it is.
Use the if conditions to check for the roman numeral rule violations in the adjacent characters to the selected character.
for(int i = 0; i < s.length(); i++){
if (s[i] == 'V'){
**Check if the character before of after is also 'V'. Then it is a violation
}
else if(s[i] == 'L'){
**Conditions for 'L' etc.
}
}
This is what I have come up with based on my rules. Any thoughts on refactoring this to make it simpler?
public static boolean checkValidity (String s1, HashSet<Character> romanNumerals){
HashSet<Character> alreadyContained = new HashSet<Character>();
if (s1.length() == 1 && romanNumerals.contains(s1.charAt(0))){
return true;
}
int i = 0;
while (i < s1.length()){
if (s1.charAt(i) == 'M'){
if (alreadyContained.contains('M')){
return false;
}
int count = 1;
i++;
while (s1.charAt(i) == 'M'){
i++;
count++;
}
alreadyContained.add('M');
if (count >= 5){
return false;
}
}
else if (s1.charAt(i) == 'D'){
if (alreadyContained.contains('D')){
return false;
}
alreadyContained.add('D');
if (!alreadyContained.contains('M')){
alreadyContained.add('M');
}
i++;
if ((i < s1.length()) && (s1.charAt(i) == 'D')){
return false;
}
}
else if (s1.charAt(i) == 'L'){
if (alreadyContained.contains('L')){
return false;
}
alreadyContained.add('L');
if (!alreadyContained.contains('M')){
alreadyContained.add('M');
}
if (!alreadyContained.contains('D')){
alreadyContained.add('D');
}
if (!alreadyContained.contains('C')){
alreadyContained.add('C');
}
i++;
if ((i < s1.length()) && (s1.charAt(i) == 'L')){
return false;
}
}
else if (s1.charAt(i) == 'V'){
if (alreadyContained.contains('V')){
return false;
}
alreadyContained.add('V');
if (!alreadyContained.contains('M')){
alreadyContained.add('M');
}
if (!alreadyContained.contains('D')){
alreadyContained.add('D');
}
if (!alreadyContained.contains('C')){
alreadyContained.add('C');
}
if (!alreadyContained.contains('L')){
alreadyContained.add('L');
}
if (!alreadyContained.contains('X')){
alreadyContained.add('X');
}
i++;
if ((i < s1.length()) && (s1.charAt(i) == 'V')){
return false;
}
}
else if (s1.charAt(i) == 'C'){
if (alreadyContained.contains('C')){
return false;
}
int count = 1;
i++;
if ((i < s1.length()) &&(s1.charAt(i) == 'M' || s1.charAt(i) == 'D')){
i++;
}
else if (i < s1.length() && s1.charAt(i) == 'C'){
while ((i < s1.length()) && (s1.charAt(i) == 'C')){
i++;
count++;
}
}
alreadyContained.add('C');
if (!alreadyContained.contains('M')){
alreadyContained.add('M');
}
if (!alreadyContained.add('D')){
alreadyContained.add('D');
}
if (count >= 5){
return false;
}
}
else if (s1.charAt(i) == 'X'){
if (alreadyContained.contains('X')){
return false;
}
int count = 1;
i++;
if ((i < s1.length()) && (s1.charAt(i) == 'D' || s1.charAt(i) == 'M')){
return false;
}
while ((i < s1.length()) && s1.charAt(i) == 'X'){
i++;
count++;
}
alreadyContained.add('X');
if (count >= 5){
return false;
}
}
else if (s1.charAt(i) == 'I'){
if (alreadyContained.contains('I')){
return false;
}
alreadyContained.add('I');
i++;
int count = 1;
if ((i < s1.length()) && (s1.charAt(i) != 'I' && s1.charAt(i) != 'X' && s1.charAt(i) != 'V')){
return false;
}
else if (i < s1.length() && s1.charAt(i) == 'I'){
while (i < s1.length() && s1.charAt(i) == 'I'){
i++;
count++;
}
if (count >= 4){
return false;
}
}
}
else if (!romanNumerals.contains(s1.charAt(i))){
return false;
}
}
return true;
}

How do I use a variable that is declared inside of a for loop outside the loop?

I'm creating ATARI BREAKOUT, using the acm.graphics library and I'm trying to access a "brick" outside of my for loop to delete it. I can't figure out any other way to create the bricks without the for loop. Help?
GRect brick = new GRect(brickwidth, brickheight);
for(j = 1; j <= nrows; j++) {
for(i = 0; i < bricksperrow; i++) {
brick.setLocation(i*(brickwidth + brickSep) + 1, brickoffset + j*(brickheight + brickSep));
if(j == 1 || j == 2) {
brick.setColor(Color.RED);
brick.setFilled(true);
}
else if(j == 3 || j == 4) {
brick.setColor(Color.ORANGE);
brick.setFilled(true);
}
else if(j == 5 || j == 6) {
brick.setColor(Color.YELLOW);
brick.setFilled(true);
}
else if(j == 7 || j == 8) {
brick.setColor(Color.GREEN);
brick.setFilled(true);
}
else if(j == 9 || j == 10) {
brick.setColor(Color.CYAN);
brick.setFilled(true);
}
add(brick);
}
}
I guess you want to create many bricks in for loop.
You are doing it wrong, per iteration you are just changing a position of one brick.
You need to create a new brick per iteration and save its reference into some structure preferably a matrix of [nrows, bricksperrow] dimensions.
Here's how:
GRect[][] bricks = new GRect[nrows][bricksperrow];
for(j = 1; j <= nrows; j++) {
for(i = 0; i < bricksperrow; i++) {
bricks[j - 1][i].setLocation(
i*(brickwidth + brickSep) + 1,
brickoffset + j*(brickheight + brickSep));
if(j == 1 || j == 2) {
brick.setColor(Color.RED);
brick.setFilled(true);
}
else if(j == 3 || j == 4) {
brick.setColor(Color.ORANGE);
brick.setFilled(true);
}
else if(j == 5 || j == 6) {
brick.setColor(Color.YELLOW);
brick.setFilled(true);
}
else if(j == 7 || j == 8) {
brick.setColor(Color.GREEN);
brick.setFilled(true);
}
else if(j == 9 || j == 10) {
brick.setColor(Color.CYAN);
brick.setFilled(true);
}
add(bricks[j - 1][i]);
}
}
This way you can have global matrix of bricks from where you can delete any entry.

Minimax algorithm in 4x4 TicTacToe board

I'm working in artificial intelligence project to develop a TicTacToe 4X4 using Minimax algorithm
I have this existing program that run Minimax algorithm in 3x3 TicTacToe board.
I want to extend it to 4x4 TicTacToe
but I couldn't any idea how I can do it ??
import java.util.*;
//defines the point where to place 1 or 2
class Point {
int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
#Override
public String toString() {
return "[" + x + ", " + y + "]";
}
}
//defines the score per point -1,0,1
class PointsAndScores {
int score;
Point point;
PointsAndScores(int score, Point point) {
this.score = score;
this.point = point;
}
}
//defince the game board
class Board {
List<Point> availablePoints;
Scanner scan = new Scanner(System.in);
int[][] board = new int[3][3];
public Board() {
}
public boolean isGameOver() {
//Game is over is someone has won, or board is full (draw)
return (hasXWon() || hasOWon() || getAvailableStates().isEmpty());
}
//check if X have won represented by 1
public boolean hasXWon() {
if ((board[0][0] == board[1][1] && board[0][0] == board[2][2] && board[0][0] == 1) || (board[0][2] == board[1][1] && board[0][2] == board[2][0] && board[0][2] == 1)) {
//System.out.println("O Diagonal Win");
return true;
}
for (int i = 0; i < 3; ++i) {
if (((board[i][0] == board[i][1] && board[i][0] == board[i][2] && board[i][0] == 1)
|| (board[0][i] == board[1][i] && board[0][i] == board[2][i] && board[0][i] == 1))) {
// System.out.println("O Row or Column win");
return true;
}
}
return false;
}
//check if O has won represented by 2
public boolean hasOWon() {
if ((board[0][0] == board[1][1] && board[0][0] == board[2][2] && board[0][0] == 2) || (board[0][2] == board[1][1] && board[0][2] == board[2][0] && board[0][2] == 2)) {
// System.out.println("X Diagonal Win");
return true;
}
for (int i = 0; i < 3; ++i) {
if ((board[i][0] == board[i][1] && board[i][0] == board[i][2] && board[i][0] == 2)
|| (board[0][i] == board[1][i] && board[0][i] == board[2][i] && board[0][i] == 2)) {
// System.out.println("X Row or Column win");
return true;
}
}
return false;
}
//check available states in the board
public List<Point> getAvailableStates() {
availablePoints = new ArrayList<>();
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
if (board[i][j] == 0) {
availablePoints.add(new Point(i, j));
}
}
}
return availablePoints;
}
//put player move in the board
public void placeAMove(Point point, int player) {
board[point.x][point.y] = player; //player = 1 for O, 2 for X..
}
//get best movement according to the board state
public Point returnBestMove() {
int MAX = -100000;
int best = -1;
for (int i = 0; i < rootsChildrenScores.size(); ++i) {
if (MAX < rootsChildrenScores.get(i).score) {
MAX = rootsChildrenScores.get(i).score;
best = i;
}
}
return rootsChildrenScores.get(best).point;
}
//accepts input from user
void takeHumanInput() {
System.out.println("Your move: ");
int x = scan.nextInt();
int y = scan.nextInt();
Point point = new Point(x, y);
placeAMove(point, 2);
}
//display current board
public void displayBoard() {
System.out.println();
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
System.out.print(board[i][j] + " ");
}
System.out.println();
}
}
//get min value
public int returnMin(List<Integer> list) {
int min = Integer.MAX_VALUE;
int index = -1;
for (int i = 0; i < list.size(); ++i) {
if (list.get(i) < min) {
min = list.get(i);
index = i;
}
}
return list.get(index);
}
//get max value
public int returnMax(List<Integer> list) {
int max = Integer.MIN_VALUE;
int index = -1;
for (int i = 0; i < list.size(); ++i) {
if (list.get(i) > max) {
max = list.get(i);
index = i;
}
}
return list.get(index);
}
//declares a list for scores
List<PointsAndScores> rootsChildrenScores;
//excutes minimax algorithm
public void callMinimax(int depth, int turn){
rootsChildrenScores = new ArrayList<>();
minimax(depth, turn);
}
//minimax algorithm
public int minimax(int depth, int turn) {
if (hasXWon()) return +1;
if (hasOWon()) return -1;
//get available states from the board
List<Point> pointsAvailable = getAvailableStates();
if (pointsAvailable.isEmpty()) return 0;
//stores scores
List<Integer> scores = new ArrayList<>();
for (int i = 0; i < pointsAvailable.size(); ++i) {
Point point = pointsAvailable.get(i);
if (turn == 1) { //O's turn select the highest from below minimax() call
placeAMove(point, 1);
int currentScore = minimax(depth + 1, 2);
scores.add(currentScore);//add scores to the list
if (depth == 0)
rootsChildrenScores.add(new PointsAndScores(currentScore, point));
} else if (turn == 2) {//X's turn select the lowest from below minimax() call
placeAMove(point, 2);
scores.add(minimax(depth + 1, 1));
}
board[point.x][point.y] = 0; //Reset this point
}
return turn == 1 ? returnMax(scores) : returnMin(scores);
}
}
//main class
public class TicTacToe {
public static void main(String[] args) {
Board b = new Board();//instantiate board
Random rand = new Random();//instantiate random value
b.displayBoard();//display board
System.out.println("Who's gonna move first? (1)Computer (2)User: ");
int choice = b.scan.nextInt();
if(choice == 1){
Point p = new Point(rand.nextInt(3), rand.nextInt(3));
b.placeAMove(p, 1);
b.displayBoard();
}
while (!b.isGameOver()) {
System.out.println("Your move: ");
Point userMove = new Point(b.scan.nextInt(), b.scan.nextInt());
b.placeAMove(userMove, 2); //2 for X and X is the user
b.displayBoard();
if (b.isGameOver()) {
break;
}
b.callMinimax(0, 1);
for (PointsAndScores pas : b.rootsChildrenScores) {
System.out.println("Point: " + pas.point + " Score: " + pas.score);
}
b.placeAMove(b.returnBestMove(), 1);
b.displayBoard();
}
if (b.hasXWon()) {
System.out.println("Unfortunately, you lost!");
} else if (b.hasOWon()) {
System.out.println("You win! This is not going to get printed.");
} else {
System.out.println("It's a draw!");
}
}
}
You need to introduce an integer variable, let's say n, which will contain the size of the board(i.e. # of cells = n*n). Before a game starts, the player will be asked for the preferred board size, 3 or 4, and the corresponding board will be created. In order for your program to work with 4x4 like it did with 3x3, we will need to place the variable n wherever we have a method or loop that needs to traverse through the board. In other words, instead of 3 we will place n. This will "generalize" our program. For example, within the display method we have 2 for loops that run as long as i and j are smaller than 3. To "generalize" our program to a semi-arbitrary board size(3 or 4), we place an n in place of the 3 so that the loop will run as long as i and j are smaller than n(3 or 4). This change from 3 to n will apply wherever we have a 3 that indicates the size of the board. Another thing we will need to change are the checking methods hasXWon() and hasOWon(). Here, we will need to add an extra section for when the board size is 4 and not 3. This will look more or less the same as it's counterpart with the only difference being that it will check the extra row, column and longer diagonals that exist in a 4x4 board. After inserting these changes, the program now looks like this:
import java.util.*;
//defines the point where to place 1 or 2
class Point {
int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
#Override
public String toString() {
return "[" + x + ", " + y + "]";
}
}
//defines the score per point -1,0,1
class PointsAndScores {
int score;
Point point;
PointsAndScores(int score, Point point) {
this.score = score;
this.point = point;
}
}
//defince the game board
class board {
List<Point> availablePoints;
Scanner scan = new Scanner(System.in);
public int n;
int[][] board;
public board(int n) {
this.n = n;
board = new int[n][n];
}
public boolean isGameOver() {
//Game is over is someone has won, or board is full (draw)
return (hasXWon() || hasOWon() || getAvailableStates().isEmpty());
}
//check if X have won represented by 1
public boolean hasXWon() {
if(n==3){
if ((board[0][0] == board[1][1] && board[0][0] == board[2][2] && board[0][0] == 1) || (board[0][2] == board[1][1] && board[0][2] == board[2][0] && board[0][2] == 1)) {
//System.out.println("O Diagonal Win");
return true;
}
for (int i = 0; i < n; ++i) {
if (((board[i][0] == board[i][1] && board[i][0] == board[i][2] && board[i][0] == 1)
|| (board[0][i] == board[1][i] && board[0][i] == board[2][i] && board[0][i] == 1))) {
// System.out.println("O Row or Column win");
return true;
}
}
return false;
}
else {
if ((board[0][0] == board[1][1] && board[0][0] == board[2][2] && board[0][0] == board[3][3]&& board[0][0] == 1) || (board[0][3] == board[1][2] && board[0][3] == board[2][1] && board[0][3] == board[3][0] && board[0][3] == 1)) {
//System.out.println("O Diagonal Win");
return true;
}
for (int i = 0; i < n; ++i) {
if (((board[i][0] == board[i][1] && board[i][0] == board[i][2] && board[i][0] == 1)
|| (board[0][i] == board[1][i] && board[0][i] == board[2][i] && board[0][i] == 1))) {
// System.out.println("O Row or Column win");
return true;
}
}
return false;
}
}
//check if O has won represented by 2
public boolean hasOWon() {
if(n==3){
if ((board[0][0] == board[1][1] && board[0][0] == board[2][2] && board[0][0] == 2) || (board[0][2] == board[1][1] && board[0][2] == board[2][0] && board[0][2] == 2)) {
//System.out.println("O Diagonal Win");
return true;
}
for (int i = 0; i < n; ++i) {
if (((board[i][0] == board[i][1] && board[i][0] == board[i][2] && board[i][0] == 2)
|| (board[0][i] == board[1][i] && board[0][i] == board[2][i] && board[0][i] == 2))) {
// System.out.println("O Row or Column win");
return true;
}
}
return false;
}
else {
if ((board[0][0] == board[1][1] && board[0][0] == board[2][2] && board[0][0] == board[3][3]&& board[0][0] == 2) || (board[0][3] == board[1][2] && board[0][3] == board[2][1] && board[0][3] == board[3][0] && board[0][3] == 2)) {
//System.out.println("O Diagonal Win");
return true;
}
for (int i = 0; i < n; ++i) {
if (((board[i][0] == board[i][1] && board[i][0] == board[i][2] && board[i][0] == 2)
|| (board[0][i] == board[1][i] && board[0][i] == board[2][i] && board[0][i] == 2))) {
// System.out.println("O Row or Column win");
return true;
}
}
return false;
}
}
//check available states in the board
public List<Point> getAvailableStates() {
availablePoints = new ArrayList<>();
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
if (board[i][j] == 0) {
availablePoints.add(new Point(i, j));
}
}
}
return availablePoints;
}
//put player move in the board
public void placeAMove(Point point, int player) {
board[point.x][point.y] = player; //player = 1 for O, 2 for X..
}
//get best movement according to the board state
public Point returnBestMove() {
int MAX = -100000;
int best = -1;
for (int i = 0; i < rootsChildrenScores.size(); ++i) {
if (MAX < rootsChildrenScores.get(i).score) {
MAX = rootsChildrenScores.get(i).score;
best = i;
}
}
return rootsChildrenScores.get(best).point;
}
//accepts input from user
void takeHumanInput() {
System.out.println("Your move: ");
int x = scan.nextInt();
int y = scan.nextInt();
Point point = new Point(x, y);
placeAMove(point, 2);
}
//display current board
public void displayboard() {
System.out.println();
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
System.out.print(board[i][j] + " ");
}
System.out.println();
}
}
//get min value
public int returnMin(List<Integer> list) {
int min = Integer.MAX_VALUE;
int index = -1;
for (int i = 0; i < list.size(); ++i) {
if (list.get(i) < min) {
min = list.get(i);
index = i;
}
}
return list.get(index);
}
//get max value
public int returnMax(List<Integer> list) {
int max = Integer.MIN_VALUE;
int index = -1;
for (int i = 0; i < list.size(); ++i) {
if (list.get(i) > max) {
max = list.get(i);
index = i;
}
}
return list.get(index);
}
//declares a list for scores
List<PointsAndScores> rootsChildrenScores;
//excutes minimax algorithm
public void callMinimax(int depth, int turn){
rootsChildrenScores = new ArrayList<>();
minimax(depth, turn);
}
//minimax algorithm
public int minimax(int depth, int turn) {
if (hasXWon()) return +1;
if (hasOWon()) return -1;
//get available states from the board
List<Point> pointsAvailable = getAvailableStates();
if (pointsAvailable.isEmpty()) return 0;
//stores scores
List<Integer> scores = new ArrayList<>();
for (int i = 0; i < pointsAvailable.size(); ++i) {
Point point = pointsAvailable.get(i);
if (turn == 1) { //O's turn select the highest from below minimax() call
placeAMove(point, 1);
int currentScore = minimax(depth + 1, 2);
scores.add(currentScore);//add scores to the list
if (depth == 0)
rootsChildrenScores.add(new PointsAndScores(currentScore, point));
} else if (turn == 2) {//X's turn select the lowest from below minimax() call
placeAMove(point, 2);
scores.add(minimax(depth + 1, 1));
}
board[point.x][point.y] = 0; //Reset this point
}
return turn == 1 ? returnMax(scores) : returnMin(scores);
}
}
//main class
public class TicTacToe {
public static void main(String[] args) {
//board b = new board();//instantiate board
Random rand = new Random();//instantiate random value
Point p;
Scanner s = new Scanner(System.in);
System.out.println("Choose board size: 3 or 4?");
int n=s.nextInt();
board b = new board(n); //Instantiating board after value of n has been read. This is important because the value of n is required for the instantiation to take place.
System.out.println(b.n);
b.displayboard();//display board
System.out.println("Who's gonna move first? (1)Computer (2)User: ");
int choice = b.scan.nextInt();
if(choice == 1){
if(b.n==3)
p = new Point(rand.nextInt(3), rand.nextInt(3));
else
p = new Point(rand.nextInt(4), rand.nextInt(4));
b.placeAMove(p, 1);
b.displayboard();
}
while (!b.isGameOver()) {
System.out.println("Your move: ");
Point userMove = new Point(b.scan.nextInt(), b.scan.nextInt());
b.placeAMove(userMove, 2); //2 for X and X is the user
b.displayboard();
if (b.isGameOver()) {
break;
}
b.callMinimax(0, 1);
for (PointsAndScores pas : b.rootsChildrenScores) {
System.out.println("Point: " + pas.point + " Score: " + pas.score);
}
b.placeAMove(b.returnBestMove(), 1);
b.displayboard();
}
if (b.hasXWon()) {
System.out.println("Unfortunately, you lost!");
} else if (b.hasOWon()) {
System.out.println("You win! This is not going to get printed.");
} else {
System.out.println("It's a draw!");
}
}
}
Your program is now able to create 4x4 games. There are however two things that you need to do. First, your placeAMove(...) method doesn't check if a cell is occupied before filling it. This may lead to cells being overwritten, so you must change that by checking if a cell is occupied before trying to fill it. The second and more important thing is that although the program is now able to create 4x4 games, it will not be able to carryout a proper game. The reason for this is that the number of nodes(states) created by minimax to find the next move, although manageable in 3x3 games, rises dramatically for 4x4 games. This means that it would take your computer A LOT of time, and by a lot I mean hours, to calculate the computer's second move. Even when I rigged the game(i.e. manually inserted random 1s and 2s in the cells before allowing minimax to be called to choose the computer's move) it still took the computer over 30 seconds to calculate it's move. This renders your game, of course, unplayable in 4x4 mode. There are, of course, ways, such as Memoization or Alpha-Beta Pruning or both together, to overcome this and speed up your algorithm. Here is a previously asked question to get you started on these topics. The chess programming wiki is also a good source of information on such topics, if a bit more complex in it's structure. Here's their entry on Memoization(Here called transposition tables).

check if array contains certain int BEFORE another int

I need to check if an array contains a 1 and then later in the array contains a 2.
What I have coded only checks if both are in there, not if one is before the other. How could I do this?
if(array[i] == 1)
count++;
else if(array[i] == 2)
count++;
}
if(count > 1)
System.out.print("true");
else
System.out.print("false");
Comparing the index of the values works!
if (nums[i] == 1)
value1 = i;
else if(nums[i] == 2)
value2 = i;
}
if (value2 > value1)
System.out.print("true");
else
System.out.print("false");
This oughta do it!
public void hasOneThenTwo(int[] a) {
bool hasOne = false;
for (int i = 0; i < a.length; ++i) {
if (!hasOne && a[i] == 1) {
hasOne = true;
} else if (hasOne && a[i] == 2) {
return true;
}
}
return false;
}

Categories