Simple Game Without GUI (java)

 This is a very simple game made with java.

This Game can be run in the command line.

This game is a good practice for the intermediate level
and it helps beginners to understand the concept of object oriented programming languages

Please, note that I am the one who invented and came up with the idea behind this game,
so it is not a real, famous game. Rather it is just a very good practice to understand
the concept of object oriented programming languages, inheritance and packages.


Video from the game:



📢RecommendedPlease watch the video first of all. Try to understand the game and the idea behind it and then try to implement  the game on your own first, before looking at the code down below.


📥Download the Code📥

package structure:














To compile and run the game:









______________________________________________________________
________________________________________

🎁Code:



Main.java:


/**
 * @author Khaled Badran
 */

package game;

import game.simulation.Simulation;

class Main {
    
    public static void main(String[] args) {
        Simulation game = new Simulation();                     
        game.run();        
    }
}


___________________________________________________

Util.java:



/**
 * @author Khaled Badran
 */

 
package game.util;
import java.io.IOException;

public class Util {

    public static void clearScreen() {
        try {
            new ProcessBuilder("cmd""/c""cls").inheritIO().start().waitFor();
        } catch (Exception e) {
            // handle exception
            System.err.println(e);
        }
    }
    
    public static void sleep(long milliseconds) {
        try{
            Thread.sleep(milliseconds); //converting from mili seconds to seconds.
        } catch(Exception e) {
            System.err.println("Thread inturrupted");
        }    
    }
    
}


___________________________________________________

PlayingFieldTile.java:



/**
 * @author Khaled Badran
 */

package game.model;

public enum PlayingFieldTile {
    PLAYER(" I "), MINE(" * "), GROUND("   "), DESTINATION(" # "), MONEY(" $ "), DEATH(" X ");
    
    private final String output; //important for printing the playing field

    private PlayingFieldTile(String str) {
        this.output = str;
    }

    public String toString() {
        return output;
    }
}


___________________________________________________

PlayingField.java:



/**
 * @author Khaled Badran
 */

package game.model;

import java.util.Random;

public class PlayingField {
    private PlayingFieldTile[][] field = new PlayingFieldTile[10][10];
    private final int SIZE = 10;
    
    public PlayingField() {
        for(int i = 0; i < SIZE; i++)//rows
            for(int j = 0; j < SIZE; j++//tiles/squares
                field[i][j] = PlayingFieldTile.GROUND;
        
        field[0][0= PlayingFieldTile.PLAYER;
        field[9][9= PlayingFieldTile.DESTINATION;
        
        int randRow, randCol;
    
        for(int money = 10; money > 0;){
            randRow = new Random().nextInt(10);
            randCol = new Random().nextInt(10);
            if(field[randRow][randCol] == PlayingFieldTile.GROUND){
                field[randRow][randCol] = PlayingFieldTile.MONEY;
                money--;
            }    
        }
        
        for(int mine = 20; mine > 0;){
            randRow = new Random().nextInt(10);
            randCol = new Random().nextInt(10);
            if(field[randRow][randCol] == PlayingFieldTile.GROUND){
                field[randRow][randCol] = PlayingFieldTile.MINE;
                mine--;
            }    
        }
        
    }
    
    public PlayingField(PlayingFieldTile[][] field) {
        setField(field);
    }
    
    public PlayingFieldTile[][] getField() {
        return field;
    }
    
    public void setField(PlayingFieldTile[][] field) {
        //make sure that the Playing Field Size is correct.
        //The correct Playing Field Size is 10 X 10
        if (field.length != SIZE){//number of (rows/ 1 dimensional arrays)
            System.err.println("Playing Field Size is incorrect.");
            System.exit(1);
        }
        // number of cols/Tiles in every single (row/1 dimensional array)
        for(PlayingFieldTile[] i: field)
            if (i.length != SIZE){ 
                System.err.println("Playing Field Size is incorrect.");
                System.exit(1);
            }
        //if the Playing Field Size is correct, initialize the field member.      
        for(int i = 0; i < SIZE; i++)
            for(int j = 0; j < SIZE; j++)
                this.field[i][j] = field[i][j];
    }
    
    public PlayingFieldTile getTile(int x/*row*/int y/*col*/) {
        return field[x][y];
    } 
    
    public void setTile(int x/*row*/int y/*col*/,PlayingFieldTile t) {
        field[x][y= t;
    }
    
    public int getSize() {
        return this.SIZE;
    }
    
    
    @Override
    public String toString() {
        String playingFieldStructure = " _______________________________________\n";
        for(int i = 0; i < SIZE; i++){//rows
            for(int j = 0; j < SIZE; j++){ //tiles/squares
                    playingFieldStructure += "|" + field[i][j];
            }
            playingFieldStructure += "|\n";    
            for(int j = 0; j < SIZE; j++)
                playingFieldStructure += "|___";
                
            playingFieldStructure += "|\n";
        }
        return playingFieldStructure;
    }
}

___________________________________________________

PlayingField.java:



/**
 * @author Khaled Badran
 */

package game.simulation;

class Player {

    private int playerXPosition;
    private int playerYPosition;
    private int score;
    private boolean gameOver;
    private boolean dead;
    
    public Player() {
        playerXPosition = 0;
        playerYPosition = 0;
        score = 0;
        gameOver = false;
        dead = false;
    }
    
    public int getPlayerXPosition() {
        return playerXPosition;
    }
    
    public int getPlayerYPosition() {
        return playerYPosition;
    }
    
    public int getScore() {
        return score;
    }
    
    public boolean isGameOver() {
        return gameOver;
    }
    
    public boolean isDead() {
        return dead;
    }
    
    public void setPlayerXPosition(int x) {
        playerXPosition = x;
    }
    
    public void setPlayerYPosition(int y) {
        playerYPosition = y;
    }
    
    public void increaseScore() {
        score++;
    }
    
    public void setGameOver(boolean status) {
        gameOver = status;
    }
    
    public void setDead(boolean status) {
        dead = status;
    }
    
}


___________________________________________________

Simulation.java:


/**
 * @author Khaled Badran
 */

package game.simulation;

import java.util.Scanner;
import game.model.*;
import game.util.Util

public class Simulation extends PlayingField{
    
    private Player player = new Player();
    
    
    private String getPlayerMove() {
        String move = "";
        Scanner input = new Scanner(System.in);

        while(true) {
            System.out.println("Please enter one of the following directions (w, a, s, d)");
            System.out.println("w = up, s = down, d = right, a = left");
            move = input.next().toLowerCase();
            if(move.equals("w")||move.equals("s")||move.equals("d")||move.equals("a"))
                break;
        }
        return move;
    }
    
    private boolean isInsideField(String move) {
        int tmpXPosition = 0;
        int tmpYPosition = 0;
        if(move.equals("w"))
            tmpXPosition = player.getPlayerXPosition()-1;
        else if(move.equals("s")) 
            tmpXPosition = player.getPlayerXPosition()+1;
        else if(move.equals("a"))
            tmpYPosition = player.getPlayerYPosition()-1;
        else if(move.equals("d")) 
            tmpYPosition = player.getPlayerYPosition()+1;

        if (tmpXPosition < getSize() && tmpYPosition < getSize() && tmpXPosition >= 0 && tmpYPosition >= 0)
            return true;
        return false;
    }
    
    private void updateGame(int previousXint previousYint newXint newY) {
        setTile(previousXpreviousYPlayingFieldTile.GROUND);
        if (getTile(newXnewY== PlayingFieldTile.GROUND)
            setTile(newXnewYPlayingFieldTile.PLAYER);
        else if(getTile(newXnewY== PlayingFieldTile.MINE){
            setTile(newXnewYPlayingFieldTile.DEATH);
            player.setDead(true);
            player.setGameOver(true);
        }else if(getTile(newXnewY== PlayingFieldTile.MONEY){
            setTile(newXnewYPlayingFieldTile.PLAYER);
            player.increaseScore();
        }else if(getTile(newXnewY== PlayingFieldTile.DESTINATION){
            setTile(newXnewYPlayingFieldTile.PLAYER);
            player.setGameOver(true);
        }
    }
    
    public void movePlayer() {
        String movement = getPlayerMove();
        int previousX = player.getPlayerXPosition();
        int previousY = player.getPlayerYPosition();
        
        if (isInsideField(movement)){
            if(movement.equals("w"))
                player.setPlayerXPosition(player.getPlayerXPosition()-1);
            else if(movement.equals("s")) 
                player.setPlayerXPosition(player.getPlayerXPosition()+1);
            else if(movement.equals("a"))
                player.setPlayerYPosition(player.getPlayerYPosition()-1);
            else if(movement.equals("d")) 
                player.setPlayerYPosition(player.getPlayerYPosition()+1);
                
            updateGame(previousX, previousY, player.getPlayerXPosition(), player.getPlayerYPosition());    
        } else {
            System.out.println("sorry, you can't get out of the playing field!");
            movePlayer();
        }
    } 
    
    
    public void run() {
        if (player.isGameOver()){
            if (player.isDead()) System.out.println("sorry, you lost -_-");
            else {
                System.out.println("   VICTORY");
                System.out.println("  YOU WON :)");
                System.out.println("  your score is: " + String.valueOf(player.getScore()));
            }
            return;
        }
        
        Util.clearScreen();
        System.out.println(this);
        movePlayer();
        Util.sleep(500);
        Util.clearScreen();
        System.out.println(this);
        run();
    }
    
    @Override
    public String toString() {
        return super.toString();
    }
    
}

____________________________________________________

Output:

please watch the video.

____________________________________________________





Comments