git clone : https://github.com/consumerfed/game.git
Showing posts with label java games. Show all posts
Showing posts with label java games. Show all posts
July 28, 2020
Tic Tac Toe game in java with source code | explained | Java implementation
A Simple tic tac toe game : github url
April 21, 2020
Making Tic Tac Toe using abstract and interface in Java Full source code
What we did here is, using the OOPs concepts abstract and interface we change the face of the project
Help us to do simple modification in future so as to add new games using the same matrix.
You have to go through the previous tutorials to fully understand the concepts.
Change in Tic Tac Toe class
public class TicTacToe implements IGameChanges in Main class
import com.cfed.matrix.tictactoe.IGame;
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
* Copyright (c) 1997-2017 Javabelazy and/or its affiliates. All rights reserved.
*
*/
/**
* @author konzernites
* @since 1.0
*
*/
public class Main extends AbstractGame {
private static final long serialVersionUID = 8683452581122892182L;
/**
* @param args
* @throws IllegalAccessException
*/
public static void main(String[] args) throws IllegalAccessException {
Main mainClass = new Main();
mainClass.execute();
}
private void execute() throws IllegalAccessException {
Matrix<Character> matrix = new Matrix<>(3, 3);
System.out.println(" **** INSTRUCTIONS **** ");
System.out.println(" User has to enter row and column ");
System.out.println(" Postion starts from (0,0) to (2,2) ");
IGame game = new TicTacToe(matrix);
TicTacToe.isTwoPlayer = true;
playGame(game);
System.out.println(" ***** GAME OVER ***** ");
System.out.println(" Developed by consumerfed I T Section ");
}
}
AbstractGame.java
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
* Copyright (c) 1997-2017 Javabelazy and/or its affiliates. All rights reserved.
*
*/
import com.cfed.matrix.tictactoe.IGame;
/**
*
*/
/**
* @author Konzernites
*
*/
public abstract class AbstractGame {
public void playGame(IGame game) throws IllegalAccessException {
game.startGame();
}
}
IGame Interface in java
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
* Copyright (c) 1997-2017 Javabelazy and/or its affiliates. All rights reserved.
*
*/
/**
*
*/
package com.cfed.matrix.tictactoe;
/**
* @author jwalian walla bag
*
*/
public interface IGame {
public void startGame() throws IllegalAccessException;
}
Labels:
abstract class java,
algorithm,
java,
java games,
java interface
Location:
Amritsar, Punjab, India
April 14, 2020
How to make the Tic Tac Toe Game a two player | Java source code
We have already developed a code for Tic Tac Toe Game. For making the code to a two player game, we need to make one simple modification in TicTacToe.Java file
Scanner scanner = null;
scanner = new Scanner(System.in);
System.out.println(" *** THE USER : " + currentMove + " MOVE *** ");
System.out.println(" Enter the row (values from 0 to 2): ");
int row = scanner.nextInt();
validate(row);
System.out.println(" Enter the col (values from 0 to 2): ");
int col = scanner.nextInt();
validate(col);
matrix.add(row, col, currentMove);
rowMoved = row;
colMoved = col;
}
@SuppressWarnings("resource")
public void startGame() throws IllegalAccessException {
int rowMoved = 0;
int colMoved = 0;
while (moveCount < MAX_MOVE) {
if (moveCount % 2 == 0) {
if (isTwoPlayer) {
getUserMove(rowMoved, colMoved, COMP_MOVE);
} else {
matrix = computerMove.computerMove(rowMoved, colMoved);
System.out.println("** COMPUTER MOVE **");
try {
Thread.sleep(3121);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} else {
getUserMove(rowMoved, colMoved, USER_MOVE);
}
matrix.print();
boolean isWon = checkWinner();
if (isWon) {
String name = winner.equals(TikTocToe.USER_MOVE) ? " USER " : " COMPUTER ";
System.out.println("*** Congratulation *** ");
System.out.println(name + " is the winner ");
break;
}
moveCount++;
}
}
public static boolean isTwoPlayer = false;
In MainClass, the user has to choose whether you prefer a two player game or you like to play with computer...
To see the full source code, check our previous posts.
Create a new method
private void getUserMove(int rowMoved, int colMoved, char currentMove) throws IllegalAccessException {Scanner scanner = null;
scanner = new Scanner(System.in);
System.out.println(" *** THE USER : " + currentMove + " MOVE *** ");
System.out.println(" Enter the row (values from 0 to 2): ");
int row = scanner.nextInt();
validate(row);
System.out.println(" Enter the col (values from 0 to 2): ");
int col = scanner.nextInt();
validate(col);
matrix.add(row, col, currentMove);
rowMoved = row;
colMoved = col;
}
Change the following method
@SuppressWarnings("resource")
public void startGame() throws IllegalAccessException {
int rowMoved = 0;
int colMoved = 0;
while (moveCount < MAX_MOVE) {
if (moveCount % 2 == 0) {
if (isTwoPlayer) {
getUserMove(rowMoved, colMoved, COMP_MOVE);
} else {
matrix = computerMove.computerMove(rowMoved, colMoved);
System.out.println("** COMPUTER MOVE **");
try {
Thread.sleep(3121);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} else {
getUserMove(rowMoved, colMoved, USER_MOVE);
}
matrix.print();
boolean isWon = checkWinner();
if (isWon) {
String name = winner.equals(TikTocToe.USER_MOVE) ? " USER " : " COMPUTER ";
System.out.println("*** Congratulation *** ");
System.out.println(name + " is the winner ");
break;
}
moveCount++;
}
}
Create a member variable - isTwoPlayer (boolean)
public static boolean isTwoPlayer = false;
In MainClass, the user has to choose whether you prefer a two player game or you like to play with computer...
To see the full source code, check our previous posts.
Labels:
java,
java games
Location:
Thazhekad, Kerala, India
April 07, 2020
Tic Tac Toe - Play with computer | Full Java source code
ComputerMove.java
You will get a null pointer exception in tic tac toe game, for the java code which we posted earlier.So these changes has to be made in the code.
While the user chose the first move other than the centre position, the Nullpointer Exception comes.
private Matrix<Character> generateFirstCompMove() throws IllegalAccessException {
int row = 1;
int col = 1;
if(matrix.isElementExist(row, col)) {
Random r = new Random();
row = r.nextInt(3);
col = r.nextInt(3);
col = (row == 1 && col == 1) ? col + 1 : col;
matrix.add(row, col, TikTocToe.COMP_MOVE);
}else {
matrix.add(1, 1, TikTocToe.COMP_MOVE);
}
return matrix;
}
Labels:
abstract class java,
java,
java games
Location:
Japan
March 28, 2020
Tic Tac Toe Game developed in java full code play with computer
Main,java
/**
*
*/
package com.cfed.tiktactoe;
/**
* @author konzernites
* @since 1.0
*
*/
public class Main {
/**
* @param args
* @throws IllegalAccessException
*/
public static void main(String[] args) throws IllegalAccessException {
Matrix<Character> matrix = new Matrix<>(3, 3);
System.out.println(" **** INSTRUCTIONS **** ");
System.out.println(" User has to enter row and column ");
System.out.println(" Postion starts from (0,0) to (2,2) ");
TikTocToe tikTokToe = new TikTocToe(matrix);
tikTokToe.startGame();
System.out.println(" ***** GAME OVER ***** ");
System.out.println(" Developed by consumerfed I T Section ");
}
}
TicTacToe.java
/**
* Tic Tac Toe
* The main class
*
*/
package com.cfed.tiktactoe;
import java.util.Scanner;
/**
* @author konzernites
* @param <E>
* @since 1.0
*
*/
public class TikTocToe {
public static final int MATRIX_SIZE = 3;
public static final int MAX_MOVE = 9;
protected static int moveCount = 1;
public static final char USER_MOVE = 'X';
public static final char COMP_MOVE = 'O';
private ComputerMove computerMove = null;
private Matrix<Character> matrix = null;
public Character winner = null;
public TikTocToe() {
intialize();
}
public TikTocToe(Matrix matrix) {
this.matrix = matrix;
intialize();
}
private void intialize() {
computerMove = new ComputerMove(matrix);
}
private boolean checkWinner() {
if (findWinner() == USER_MOVE) {
return true;
} else if (findWinner() == COMP_MOVE) {
return true;
}
return false;
}
@SuppressWarnings("unused")
private char findWinner() {
Object[][] newMatrix = matrix.getMatrix();
if (moveCount < 5 || moveCount > MAX_MOVE) {
return Matrix.EMPTY_DATA;
} else if (null!= matrix.getValue(0, 0) && (TikTocToe.USER_MOVE == matrix.getValue(0, 0) || TikTocToe.COMP_MOVE == matrix.getValue(0, 0))) {
winner = (Character)matrix.getValue(0, 0);
if ((null!= matrix.getValue(0, 1) && winner.equals(newMatrix[0][1])) && (null!= matrix.getValue(0, 2) && winner.equals(newMatrix[0][2]))) {
return winner;
} else if ((null!= matrix.getValue(0, 1) && winner.equals(newMatrix[1][0])) && (null!= matrix.getValue(2, 0) && winner.equals(newMatrix[2][0]))) {
return winner;
} else if ((null!= matrix.getValue(1, 1) && winner.equals(newMatrix[1][1])) && ( null!= matrix.getValue(2, 2) && winner.equals(newMatrix[2][2]))) {
return winner;
}
} else if (null!= matrix.getValue(1, 1) && (TikTocToe.USER_MOVE == matrix.getValue(1, 1) || TikTocToe.COMP_MOVE == matrix.getValue(1, 1))) {
winner = (Character)newMatrix[1][1];
if ((null!= matrix.getValue(1, 0) && winner.equals(newMatrix[1][0])) && (null!= matrix.getValue(1, 2) && winner.equals(newMatrix[1][2]))) {
return winner;
} else if ((null!= matrix.getValue(0, 0) && winner.equals(newMatrix[0][0])) && (null!= matrix.getValue(1, 2) && winner.equals(newMatrix[1][2]))) {
return winner;
} else if ((null!= matrix.getValue(0, 2) && winner.equals(newMatrix[0][2])) && (null!= matrix.getValue(2, 0) && winner.equals(newMatrix[2][0]))) {
return winner;
}
} else if (null!= matrix.getValue(2, 2) && (TikTocToe.USER_MOVE == matrix.getValue(2, 2) || TikTocToe.COMP_MOVE == matrix.getValue(2, 2))) {
winner = (Character)newMatrix[2][2];
if ((null!= matrix.getValue(2, 0) && winner.equals(newMatrix[2][0])) && (null!= matrix.getValue(2, 1) && winner.equals(newMatrix[2][1]))) {
return winner;
} else if ((null!= matrix.getValue(0, 2) && winner.equals(newMatrix[0][2])) && (null!= matrix.getValue(1, 2) && winner.equals(newMatrix[1][2]))) {
return winner;
}
}
return Matrix.EMPTY_DATA;
}
/**
* @param args
* @throws IllegalAccessException
*/
public static void main(String[] args) throws IllegalAccessException {
System.out.println(" **** INSTRUCTION **** ");
System.out.println(" User has to enter row and column ");
System.out.println(" Postion starts from (0,0) to (2,2) ");
TikTocToe t = new TikTocToe();
t.startGame();
System.out.println(" **** GAME OVER ***** ");
System.out.println(" Developed by consumerfed I T section kozhikode ");
}
public void startGame() throws IllegalAccessException {
int rowMoved = 0;
int colMoved = 0;
Scanner scanner = new Scanner(System.in);
while (moveCount < MAX_MOVE) {
if (moveCount % 2 == 0) {
matrix = computerMove.computerMove(rowMoved, colMoved);
System.out.println("** COMPUTER MOVE **");
try {
Thread.sleep(3121);
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
System.out.println("** YOUR MOVE **");
System.out.println(" Enter the row (values from 0 to 2): ");
int row = scanner.nextInt();
validate(row);
System.out.println(" Enter the col (values from 0 to 2): ");
int col = scanner.nextInt();
validate(col);
matrix.add(row, col, USER_MOVE);
rowMoved = row;
colMoved = col;
}
matrix.print();
boolean isWon = checkWinner();
if (isWon) {
System.out.println("*** Congratulation *** ");
System.out.println(winner + " is the winner ");
break;
}
moveCount++;
}
}
Dimensions.java
/**
*
*/
package com.cfed.tiktactoe;
/**
* @author konzernites
* @since 1.0
*
*/
public class Dimensions {
private static final long serialVersionUID = 8683452581122892188L;
private int row = 0;
private int column = 0;
public int getRow() {
return row;
}
public void setRow(int row) {
this.row = row;
}
public int getColumn() {
return column;
}
public void setColumn(int column) {
this.column = column;
}
}
private void validate(int value) {
if (value < 0 || value > 2) {
throw new IllegalArgumentException(" This value is not permitted");
}
}
}
Matrix.java
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
* Copyright (c) 1997-2017 Javabelazy and/or its affiliates. All rights reserved.
*
*/
package com.cfed.tiktactoe;
import java.util.NoSuchElementException;
/**
* @author konzernites
* @since 1.0
*
*/
public class Matrix<E> extends AbstractMatrix<E> {
@SuppressWarnings("unused")
private static final long serialVersionUID = 8683452581122892189L;
private final int MAX_COLUMN;
private final int MAX_ROW;
private final int MAX_CAPACITY;
protected static final char EMPTY_DATA = '\0';
private static boolean isEditable = false;
private E elementData[][];
private int capacity = 0;
public Matrix(int row, int column) {
this.MAX_COLUMN = column;
this.MAX_ROW = row;
this.MAX_CAPACITY = MAX_ROW * MAX_COLUMN;
intialize();
}
@SuppressWarnings("unchecked")
private void intialize() {
this.elementData = (E[][]) new Object[MAX_ROW][MAX_COLUMN];
}
public Matrix() {
this(2, 2);
}
public void add(int row, int column, E value) throws IllegalAccessException {
if (row > MAX_ROW || column > MAX_COLUMN)
throw new IllegalAccessException("Illegal capacity");
else if (isFull() || isElementExist(row, column))
throw new IllegalAccessException("Value already exist");
else {
capacity++;
this.elementData[row][column] = value;
}
}
public E[][] getMatrix() {
if (isEmpty())
throw new NoSuchElementException("Matrix is empty");
else
return this.elementData;
}
public E getValue(int row, int column) {
if (isEmpty())
return null;
else if(isElementExist(row, column))
return this.elementData[row][column];
else
return null;
}
public void remove(int row, int column) {
if (isEmpty())
throw new NoSuchElementException("Cannot remove value from an empty matrix");
else {
this.elementData[row][column] = null;
capacity--;
}
}
public void removeAll() {
if (isEmpty())
throw new NoSuchElementException("Cannot remove value from an empty matrix");
else {
// TODO remove all elements from matrix
}
}
public void print() {
if (isEmpty())
throw new NoSuchElementException("Cannot display an empty matrix");
else {
for (int r = 0; r < MAX_ROW; r++) {
for (int c = 0; c < MAX_COLUMN; c++) {
if (null == elementData[r][c])
System.out.print(" | ");
else
System.out.print(elementData[r][c] + " | ");
}
System.out.println("");
}
}
}
public Dimensions dimension() {
Dimensions dimensions = new Dimensions();
dimensions.setRow(MAX_ROW);
dimensions.setColumn(MAX_COLUMN);
return dimensions;
}
private boolean isEmpty() {
if (capacity == 0)
return true;
else
return false;
}
public boolean isElementExist(int row, int column) {
if (isEmpty())
return false;
else if (null != elementData[row][column])
return true;
else
return false;
}
private boolean isFull() {
if (capacity >= MAX_CAPACITY)
return true;
else
return false;
}
public int size() {
return capacity;
}
}
ComputerMove.java
/**
* Computer Moves for user move in tik toc toe
* Developed by consumerfed kozhikode I T section
* Version 1.0
* consfedkozhikode@gmail.com
*
*/
package com.cfed.tiktactoe;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
/**
* @author konzernites
* @since 1.0
*
*/
public class ComputerMove {
private int MATRIX_SIZE = 3;
private static final char EMPTY_DATA = ' ';
private Map<String, Integer> priorityPosition = null;
private static final String techIssue = "EXPERIENCING SOME TECHNICAL ISSUE";
private Matrix<Character> matrix = null;
public ComputerMove(Matrix<Character> matrix) {
this.matrix = matrix;
}
public Matrix<Character> computerMove(int rowMoved, int colMoved) throws IllegalAccessException {
if (TikTocToe.moveCount <= 2) {
matrix = generateFirstCompMove();
} else {
matrix = generateCompMove(rowMoved, colMoved);
}
return matrix;
}
private Matrix<Character> generateCompMove(int rowMoved, int colMoved) throws IllegalAccessException {
priorityPosition = new HashMap<>();
boolean isInserted = false;
for (int row = 0; row < MATRIX_SIZE; row++) {
for (int col = 0; col < MATRIX_SIZE; col++) {
if (!matrix.isElementExist(row, col)) {
isInserted = findPriority(row, col);
if (isInserted)
return matrix;
}
}
}
if (!isInserted) {
String key = maxUsingCollectionsMaxAndLambda(priorityPosition);
int r = Integer.parseInt(key.substring(0, 1));
int c = Integer.parseInt(key.substring(1, 2));
if (!matrix.isElementExist(r, c))
matrix.add(r, c, TikTocToe.COMP_MOVE);
}
return matrix;
}
private Matrix<Character> generateFirstCompMove() throws IllegalAccessException {
int row = 0;
int col = 0;
if (matrix.getValue(1, 1).equals(EMPTY_DATA)) {
matrix.add(1, 1, TikTocToe.COMP_MOVE);
} else {
Random r = new Random();
row = r.nextInt(3);
col = r.nextInt(3);
col = (row == 1 && col == 1) ? col + 1 : col;
matrix.add(row, col, TikTocToe.COMP_MOVE);
}
return matrix;
}
private boolean findPriority(int row, int col) throws IllegalAccessException {
boolean isInserted = true;
if (diagonalOne(0, 0)) {
isInserted = true;
} else if (diagonalTwo(0, MATRIX_SIZE - 1)) {
isInserted = true;
} else if (rowCheck(row, col)) {
matrix.add(row, col, TikTocToe.COMP_MOVE);
} else if (colCheck(row, col)) {
matrix.add(row, col, TikTocToe.COMP_MOVE);
} else {
isInserted = false;
}
return isInserted;
}
private boolean colCheck(int row, int col) {
boolean isPrior = false;
boolean isSafe = false;
int loopCount = 1;
int value = 0;
int r = row;
int c = col;
while (loopCount < MATRIX_SIZE) {
if (r + 1 == MATRIX_SIZE) {
r = 0;
} else {
r++;
}
if (null != matrix.getValue(r, c) && TikTocToe.COMP_MOVE == matrix.getValue(r, c)) {
isSafe = true;
break;
} else if (null != matrix.getValue(r, c) && TikTocToe.USER_MOVE == matrix.getValue(r, c)) {
value++;
}
loopCount++;
}
if (!isSafe) {
String key = String.valueOf(row + "" + col);
priorityPosition.put(key, value);
}
if (value == 2 && !isSafe) {
isPrior = true;
}
return isPrior;
}
private boolean rowCheck(int row, int col) {
boolean isPrior = false;
boolean isSafe = false;
int loopCount = 1;
int value = 0;
int r = row;
int c = col;
while (loopCount < MATRIX_SIZE) {
c = (c + 1 == MATRIX_SIZE) ? 0 : c + 1;
if (null != matrix.getValue(r, c) && TikTocToe.COMP_MOVE == matrix.getValue(r, c)) {
isSafe = true;
break;
} else if (null != matrix.getValue(r, c) && TikTocToe.USER_MOVE == matrix.getValue(r, c)) {
value++;
}
loopCount++;
}
if (!isSafe) {
String key = String.valueOf(row + "" + col);
priorityPosition.put(key, value);
}
if (value == 2 && !isSafe) {
isPrior = true;
}
return isPrior;
}
private boolean diagonalTwo(int row, int col) throws IllegalAccessException {
boolean isPrior = false;
boolean isSafe = false;
int loopCount = 1;
int value = 0;
int r = 0;
int c = 0;
while (loopCount <= MATRIX_SIZE) {
if (null != matrix.getValue(row, col) && TikTocToe.COMP_MOVE == matrix.getValue(row, col)) {
isSafe = true;
break;
} else if (null != matrix.getValue(row, col) && TikTocToe.USER_MOVE == matrix.getValue(row, col)) {
value++;
}
if (!matrix.isElementExist(row, col)) {
r = row;
c = col;
}
row++;
col--;
loopCount++;
}
if (!isSafe) {
String key = String.valueOf(r + "" + c);
priorityPosition.put(key, value);
}
if (value == 2 && !isSafe) {
matrix.add(r, c, TikTocToe.COMP_MOVE);
isPrior = true;
}
return isPrior;
}
private boolean diagonalOne(int row, int col) throws IllegalAccessException {
boolean isPrior = false;
boolean isSafe = false;
int loopCount = 1;
int value = 0;
int r = 0;
int c = 0;
while (loopCount <= MATRIX_SIZE) {
if (null != matrix.getValue(row, col) && TikTocToe.COMP_MOVE == matrix.getValue(row, col)) {
isSafe = true;
break;
} else if (null != matrix.getValue(row, col) && TikTocToe.USER_MOVE == matrix.getValue(row, col)) {
value++;
}
if (!matrix.isElementExist(row, col)) {
r = row;
c = col;
}
row++;
col++;
loopCount++;
}
if (!isSafe) {
String key = String.valueOf(r + "" + c);
priorityPosition.put(key, value);
}
if (value == 2 && !isSafe) {
matrix.add(r, c, TikTocToe.COMP_MOVE);
isPrior = true;
}
return isPrior;
}
private <K, V extends Comparable<V>> K maxUsingCollectionsMaxAndLambda(Map<K, V> map) {
Entry<K, V> maxEntry = Collections.max(map.entrySet(),
(Entry<K, V> e1, Entry<K, V> e2) -> e1.getValue().compareTo(e2.getValue()));
return maxEntry.getKey();
}
}
Output
**** INSTRUCTIONS ****
User has to enter row and column
Postion starts from (0,0) to (2,2)
** YOUR MOVE **
Enter the row (values from 0 to 2):
1
Enter the col (values from 0 to 2):
1
| | |
| X | |
| | |
** COMPUTER MOVE **
| | O |
| X | |
| | |
** YOUR MOVE **
Enter the row (values from 0 to 2):
2
Enter the col (values from 0 to 2):
2
| | O |
| X | |
| | X |
** COMPUTER MOVE **
O | | O |
| X | |
| | X |
** YOUR MOVE **
Enter the row (values from 0 to 2):
1
Enter the col (values from 0 to 2):
2
O | | O |
| X | X |
| | X |
** COMPUTER MOVE **
O | | O |
O | X | X |
| | X |
** YOUR MOVE **
Enter the row (values from 0 to 2):
2
Enter the col (values from 0 to 2):
1
O | | O |
O | X | X |
| X | X |
** COMPUTER MOVE **
O | O | O |
O | X | X |
| X | X |
*** Congratulation ***
O is the winner
***** GAME OVER *****
Developed by consumerfed I T section kozhikode
O | O | O |
O | X | X |
| X | X |
User has to enter row and column
Postion starts from (0,0) to (2,2)
** YOUR MOVE **
Enter the row (values from 0 to 2):
1
Enter the col (values from 0 to 2):
1
| | |
| X | |
| | |
** COMPUTER MOVE **
| | O |
| X | |
| | |
** YOUR MOVE **
Enter the row (values from 0 to 2):
2
Enter the col (values from 0 to 2):
2
| | O |
| X | |
| | X |
** COMPUTER MOVE **
O | | O |
| X | |
| | X |
** YOUR MOVE **
Enter the row (values from 0 to 2):
1
Enter the col (values from 0 to 2):
2
O | | O |
| X | X |
| | X |
** COMPUTER MOVE **
O | | O |
O | X | X |
| | X |
** YOUR MOVE **
Enter the row (values from 0 to 2):
2
Enter the col (values from 0 to 2):
1
O | | O |
O | X | X |
| X | X |
** COMPUTER MOVE **
O | O | O |
O | X | X |
| X | X |
*** Congratulation ***
O is the winner
***** GAME OVER *****
Developed by consumerfed I T section kozhikode
O | O | O |
O | X | X |
| X | X |
Labels:
algorithm,
client project,
java,
java games,
Student Project in java
Location:
Belgium
March 21, 2020
Tic Tac Toe Two player game with computer moves
The Tic Tac Toe Game output- Log file
**** INSTRUCTIONS ****User has to enter row and column
Postion starts from (0,0) to (2,2)
** YOUR MOVE **
Enter the row (values from 0 to 2):
1
Enter the col (values from 0 to 2):
1
| | |
| X | |
| | |
** COMPUTER MOVE **
| | O |
| X | |
| | |
** YOUR MOVE **
Enter the row (values from 0 to 2):
2
Enter the col (values from 0 to 2):
2
| | O |
| X | |
| | X |
** COMPUTER MOVE **
O | | O |
| X | |
| | X |
** YOUR MOVE **
Enter the row (values from 0 to 2):
1
Enter the col (values from 0 to 2):
2
O | | O |
| X | X |
| | X |
** COMPUTER MOVE **
O | | O |
O | X | X |
| | X |
** YOUR MOVE **
Enter the row (values from 0 to 2):
2
Enter the col (values from 0 to 2):
1
O | | O |
O | X | X |
| X | X |
** COMPUTER MOVE **
O | O | O |
O | X | X |
| X | X |
*** Congratulation ***
true is the winner
***** GAME OVER *****
Developed by consumerfed I T section kozhikode
O | O | O |
O | X | X |
| X | X |
Next post : Tic Tac Toe Game developed in java full code play with computer
March 07, 2020
Tik tok toe computer game code explained
Tik tok toe code explanation ( game developed in java )
isSpaceEmpty : is a method used to check whether the value of matrix is the specified rows and col is empty or not, If it is not an empty one then it will through an Illegal argument exception.
private boolean isSpaceEmpty(char[][] matrix, int row, int col) {
if (userMove == matrix[row][col] || compMove == matrix[row][col]) {
throw new IllegalArgumentException(techIssue);
}
return true;
}
generateFirstCompMove : The following function will calculate the first move. Computer will chose the centre of the matrix if not empty in other case random position generated.
private char[][] generateFirstCompMove(char[][] matrix) {
int row = 0;
int col = 0;
if (EMPTY == matrix[1][1]) {
matrix[1][1] = compMove;
} else {
Random r = new Random();
row = r.nextInt(3);
col = r.nextInt(3);
col = (row == 1 && col == 1) ? col + 1 : col;
matrix[row][col] = compMove;
}
return matrix;
}
Happy Birthday Madhav my best friend... I miss you a lot
I was greatly inspired by madhav who has developed a paranoid game using C language when he was in higher secondary. It was year 2001 if i remember correctly, in that days computer in home where rare, study materials was not much abundantly available as now. So i dedicate this code for him.
Tic Tac Toe Game developed in java full code play with computer , coming soon...
Labels:
algorithm,
java,
java games,
Student Project in java
Location:
Mumbai, Maharashtra, India
March 02, 2020
Tik Toc Toe Game single player with computer Java code
Tik Tok Toe a computer game developed in java by I T Section Kozhikode
/*** Happy Birthday bestie !!!
*
*/
package com.konzern.games;
import java.util.Scanner;
/**
* @author konzernites
*
*/
public class TikTocToe {
private int MATRIX_SIZE = 3;
private char[][] matrix = { { ' ', ' ', ' ' }, { ' ', ' ', ' ' }, { ' ', ' ', ' ' } };
private int moveCount = 1;
private char USER_MOVE = 'X';
private char COMP_MOVE = 'O';
private ComputerMove computerMove = null;
public TikTocToe() {
intialize();
}
private void intialize() {
computerMove = new ComputerMove(USER_MOVE,COMP_MOVE);
}
/**
* @param args
*/
public static void main(String[] args) {
System.out.println(" **** INSTRUCTION **** ");
System.out.println(" User has to enter row and column ");
System.out.println(" Postion starts from (0,0) to (2,2) ");
TikTocToe t = new TikTocToe();
t.startGame();
System.out.println(" **** GAME OVER ***** ");
System.out.println(" Developed by consumerfed I T section kozhikode ");
}
private void startGame() {
// TODO Auto-generated method stub
char move = 'x';
Scanner scanner = new Scanner(System.in);
int rowMoved = 0;
int colMoved = 0;
while (moveCount < 9) {
if (moveCount % 2 == 0) {
matrix = computerMove.computeMove(matrix, moveCount, rowMoved, colMoved);
System.out.println("** COMPUTER MOVE **");
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
System.out.println("** YOUR MOVE **");
System.out.println(" Enter the row (values from 0 to 2): ");
int row = scanner.nextInt();
System.out.println(" Enter the col (values from 0 to 2): ");
int col = scanner.nextInt();
matrix[row][col] = USER_MOVE;
rowMoved =row;
colMoved= col;
}
printMatrix();
boolean winner = checkWinner(matrix, move);
if (winner) {
System.out.println("*** Congratulation *** ");
System.out.println(move + " is the winner ");
break;
}
moveCount++;
}
}
private void printMatrix() {
// TODO Auto-generated method stub
for (int row = 0; row < MATRIX_SIZE; row++) {
for (int col = 0; col < MATRIX_SIZE; col++) {
System.out.print(matrix[row][col] + " | ");
}
System.out.println("");
}
}
private boolean checkWinner(char[][] matrix, char move) {
if (move == matrix[0][0] && move == matrix[0][1] && move == matrix[0][2]) {
return true;
} else if (move == matrix[1][0] && move == matrix[1][1] && move == matrix[1][2]) {
return true;
} else if (move == matrix[2][0] && move == matrix[2][1] && move == matrix[2][2]) {
return true;
} else if (move == matrix[0][0] && move == matrix[1][0] && move == matrix[2][0]) {
return true;
} else if (move == matrix[0][1] && move == matrix[1][1] && move == matrix[2][1]) {
return true;
} else if (move == matrix[0][2] && move == matrix[1][2] && move == matrix[2][2]) {
return true;
} else if (move == matrix[0][0] && move == matrix[1][1] && move == matrix[2][2]) {
return true;
} else if (move == matrix[0][2] && move == matrix[1][1] && move == matrix[2][0]) {
return true;
} else {
return false;
}
}
}
/**
* Computer Moves for user move in tik toc toe
* Developed by consumerfed kozhikode I T section
* Version 1.0
* consfedkozhikode@gmail.com
*
*/
package com.konzern.games;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
/**
* @author konzernites
*
*/
public class ComputerMove {
private char userMove = '\0';
private char compMove = '\0';
private int MATRIX_SIZE = 3;
private char EMPTY = ' ';
private Map<String, Integer> priorityPosition = null;
public ComputerMove(char userMove, char compMove) {
this.compMove = compMove;
this.userMove = userMove;
}
public char[][] computeMove(char[][] matrix, int moveCount, int rowMoved, int colMoved) {
if (moveCount <= 2) {
matrix = generateFirstCompMove(matrix);
} else {
matrix = generateCompMove(matrix, moveCount, rowMoved, colMoved);
}
return matrix;
}
private char[][] generateCompMove(char[][] matrix, int moveCount, int rowMoved, int colMoved) {
priorityPosition = new HashMap<>();
boolean isInserted = false;
for (int row = 0; row < MATRIX_SIZE; row++) {
for (int col = 0; col < MATRIX_SIZE; col++) {
if (EMPTY == matrix[row][col]) {
isInserted = findPriority(matrix, row, col);
if (isInserted)
return matrix;
}
}
}
if (!isInserted) {
// set max value of map to matrix
String key = maxUsingCollectionsMaxAndLambda(priorityPosition);
int r = Integer.parseInt(key.substring(0, 1));
int c = Integer.parseInt(key.substring(1, 2));
matrix[r][c] = compMove;
}
return matrix;
}
private boolean findPriority(char[][] matrix, int row, int col) {
boolean isInserted = true;
if (diagonalOne(matrix, 0, 0)) {
isInserted = true;
} else if (diagonalTwo(matrix, 0, MATRIX_SIZE - 1)) {
isInserted = true;
} else if (rowCheck(matrix, row, col)) {
matrix[row][col] = compMove;
} else if (colCheck(matrix, row, col)) {
matrix[row][col] = compMove;
} else {
isInserted = false;
}
return isInserted;
}
private boolean diagonalTwo(char[][] matrix, int row, int col) {
boolean isPrior = false;
boolean isSafe = false;
int loopCount = 1;
int value = 0;
int r = 0;
int c = 0;
while (loopCount <= MATRIX_SIZE) {
if (compMove == matrix[row][col]) {
isSafe = true;
break;
} else if (userMove == matrix[row][col]) {
value++;
}
if (EMPTY == matrix[row][col]) {
r = row;
c = col;
}
row++;
col--;
loopCount++;
}
if (!isSafe) {
String key = String.valueOf(r + "" + c);
priorityPosition.put(key, value);
}
if (value == 2) {
matrix[r][c] = compMove;
isPrior = true;
}
return isPrior;
}
private boolean diagonalOne(char[][] matrix, int row, int col) {
boolean isPrior = false;
boolean isSafe = false;
int loopCount = 1;
int value = 0;
int r = 0;
int c = 0;
while (loopCount <= MATRIX_SIZE) {
if (compMove == matrix[row][col]) {
isSafe = true;
break;
} else if (userMove == matrix[row][col]) {
value++;
}
if (EMPTY == matrix[row][col]) {
r = row;
c = col;
}
row++;
col++;
loopCount++;
}
if (!isSafe) {
String key = String.valueOf(r + "" + c);
priorityPosition.put(key, value);
}
if (value == 2) {
matrix[r][c] = compMove;
isPrior = true;
}
return isPrior;
}
private boolean colCheck(char[][] matrix, int row, int col) {
boolean isPrior = false;
boolean isSafe = false;
int loopCount = 1;
int value = 0;
int r = row;
int c = col;
while (loopCount < MATRIX_SIZE) {
if (r + 1 == MATRIX_SIZE) {
r = 0;
} else {
r++;
}
if (compMove == matrix[r][c]) {
isSafe = true;
break;
} else if (userMove == matrix[r][c]) {
value++;
}
loopCount++;
}
if (!isSafe) {
String key = String.valueOf(row +""+ col);
priorityPosition.put(key, value);
}
if (value == 2) {
isPrior = true;
}
return isPrior;
}
private boolean rowCheck(char[][] matrix, int row, int col) {
boolean isPrior = false;
boolean isSafe = false;
int loopCount = 1;
int value = 0;
int r = row;
int c = col;
while (loopCount < MATRIX_SIZE) {
c = (c + 1 == MATRIX_SIZE) ? 0 : c + 1;
if (compMove == matrix[r][c]) {
isSafe = true;
break;
} else if (userMove == matrix[r][c]) {
value++;
}
loopCount++;
}
if (!isSafe) {
String key = String.valueOf(row + "" + col);
priorityPosition.put(key, value);
}
if (value == 2) {
isPrior = true;
}
return isPrior;
}
private char[][] generateFirstCompMove(char[][] matrix) {
int row = 0;
int col = 0;
if (EMPTY == matrix[1][1]) {
matrix[1][1] = compMove;
} else {
Random r = new Random();
row = r.nextInt(3);
col = r.nextInt(3);
col = (row == 1 && col == 1) ? col + 1 : col;
matrix[row][col] = compMove;
}
return matrix;
}
private <K, V extends Comparable<V>> K maxUsingCollectionsMaxAndLambda(Map<K, V> map) {
Entry<K, V> maxEntry = Collections.max(map.entrySet(),
(Entry<K, V> e1, Entry<K, V> e2) -> e1.getValue().compareTo(e2.getValue()));
return maxEntry.getKey();
}
private void printMatrix(char[][] matrix) {
for (int row = 0; row < MATRIX_SIZE; row++) {
for (int col = 0; col < MATRIX_SIZE; col++) {
System.out.print(matrix[row][col] + " | ");
}
System.out.println("");
}
}
}
Explanation on this code will be posted on the next post, also some update on the code is made and will be posted soon...
Please provide your feedback....
February 07, 2020
TicTacToe playing with computer full java source code | algorithm
watch this video
Developed a two player tic tac toe game in java. The user can also play with the computer, we developed a new algorithm that makes computers to investigate user moves and to choose the best moves to win the game. So we request the readers to watch the video showing how it works. Our developers are working on the ui parts. We will update the source code in this website soon. You can post your comments & queries. Please follow the blog for our update. Your feedback are valuable.
Full source code will be available in this blog soon..
Tic Tac Toe Game |
Labels:
algorithm,
java,
java games
Location:
Hyderabad, Telangana, India
January 21, 2020
Tic Tac Toe in Java - The Matrix code
Tic Tac Toe algorithm and source code in Java
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
* Copyright (c) 1997-2017 Javabelazy and/or its affiliates. All rights reserved.
*
*/
package com.cfed.tiktactoe;
import java.util.NoSuchElementException;
/**
* @author konzernites
* @since 1.0
* id : 6523895
*/
public class Matrix<E> extends AbstractMatrix<E> {
@SuppressWarnings("unused")
private static final long serialVersionUID = 8683452581122892189L;
private final int MAX_COLUMN;
private final int MAX_ROW;
private final int MAX_CAPACITY;
protected static final char EMPTY_DATA = '\0';
private static boolean isEditable = false;
private E elementData[][];
private int capacity = 0;
public Matrix(int row, int column) {
this.MAX_COLUMN = column;
this.MAX_ROW = row;
this.MAX_CAPACITY = MAX_ROW * MAX_COLUMN;
intialize();
}
@SuppressWarnings("unchecked")
private void intialize() {
this.elementData = (E[][]) new Object[MAX_ROW][MAX_COLUMN];
}
public Matrix() {
this(2, 2);
}
public void add(int row, int column, E value) throws IllegalAccessException {
if (row > MAX_ROW || column > MAX_COLUMN)
throw new IllegalAccessException("Illegal capacity");
else if (isFull() || isElementExist(row, column))
throw new IllegalAccessException("Value already exist");
else {
capacity++;
this.elementData[row][column] = value;
}
}
public E[][] getMatrix() {
if (isEmpty())
throw new NoSuchElementException("Matrix is empty");
else
return this.elementData;
}
public E getValue(int row, int column) {
if (isEmpty())
return null;
else if(isElementExist(row, column))
return this.elementData[row][column];
else
return null;
}
public void remove(int row, int column) {
if (isEmpty())
throw new NoSuchElementException("Cannot remove value from an empty matrix");
else {
this.elementData[row][column] = null;
capacity--;
}
}
public void removeAll() {
if (isEmpty())
throw new NoSuchElementException("Cannot remove value from an empty matrix");
else {
// TODO remove all elements from matrix
}
}
public void print() {
if (isEmpty())
throw new NoSuchElementException("Cannot display an empty matrix");
else {
for (int r = 0; r < MAX_ROW; r++) {
for (int c = 0; c < MAX_COLUMN; c++) {
if (null == elementData[r][c])
System.out.print(" | ");
else
System.out.print(elementData[r][c] + " | ");
}
System.out.println("");
}
}
}
public Dimensions dimension() {
Dimensions dimensions = new Dimensions();
dimensions.setRow(MAX_ROW);
dimensions.setColumn(MAX_COLUMN);
return dimensions;
}
private boolean isEmpty() {
if (capacity == 0)
return true;
else
return false;
}
public boolean isElementExist(int row, int column) {
if (isEmpty())
return false;
else if (null != elementData[row][column])
return true;
else
return false;
}
private boolean isFull() {
if (capacity >= MAX_CAPACITY)
return true;
else
return false;
}
public int size() {
return capacity;
}
}
An abstract Matrix for Tic Tac Toe.
Tic Tac Toe complete code will be available soon, stay update
Labels:
algorithm,
datastructure,
java,
java games
Location:
Thazhekad, Kerala, India
Subscribe to:
Posts (Atom)