//JAVA -- BRAINVITA -- A MARBLE GAME
//CHAINANI MIKHAIL

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.util.*;

//<applet code="BrainVita" width=300 height=300>
//</applet>

public class HelloWorld extends Applet implements ActionListener,Runnable
{
	int pickX=-1,pickY=-1,pointX=-1,pointY=-1,dragX=-1,dragY=-1;
	public int board[];
	public int i,j,k,deadBalls;
	public Button restart=new Button("RESTART");
	public Button bsol=new Button("DEMO");
	public Button inst=new Button("INSTRUCTIONS");
	public Button back=new Button("BACK");
	public Button undo=new Button("UNDO");
	boolean instructions;
	public boolean gameend;
	final int UP=1,RIGHT=2,DOWN=3,LEFT=4;
	public int solution[][]={
		{3,5,1},{1,4,2},{3,3,3},{3,6,1},{2,6,1},{3,4,4},{5,4,4},{4,6,1},
		{3,4,2},{0,4,2},{2,3,3},{0,3,2},{2,2,3},{2,5,1},{0,2,2},{6,4,4},
        {4,3,3},{6,3,4},{4,2,3},{4,5,1},{6,2,4},{3,2,2},{4,0,3},{4,3,1},
        {2,0,2},{4,0,3},{5,2,4},{3,1,3},{3,3,4},{2,1,3},{1,3,2}};
	Thread t=null;
	int count;
	Stack u=new Stack();
	Integer o=new Integer(0);

	//INITIALISATION OF THE APPLET
	public void init()
	{
		setLayout(null);
		resize(465,300);
		board=new int[49];
		t=new Thread(this);
		fillBoard();
		addComp(restart,280,136,100,50,true);
		addComp(bsol,280,73,100,50,true);
		addComp(inst,280,10,100,50,true);
		addComp(back,280,199,100,50,false);
		addComp(undo,280,199,100,50,true);
		repaint();
	}

	//ADD A BUTTON
	public void addComp(Button b,int x,int y,int w,int h,boolean vis)
	{
		b.setBounds(x,y,w,h);
		b.setVisible(vis);
		add(b);
		b.addActionListener(this);
	}

	//INITIALISE THE BOARD
	public void fillBoard()
	{
		for(i=0;i<49;i++)
			board[i]=1;
		for(i=0;i<2;i++)
			for(j=0;j<2;j++)
			{
				board[i*7+j]=-1;
				board[i*7+j+5]=-1;
				board[i*7+j+35]=-1;
				board[i*7+j+40]=-1;
			}
		board[24]=0;
		undo.setEnabled(false);
		bsol.setEnabled(true);
		gameend=false;
		instructions=false;
		deadBalls=0;
	}

		public void actionPerformed(ActionEvent ae)
	{
		if(ae.getSource()==restart)
		{
			u=new Stack();
			if(t.isAlive())
				t.stop();
			fillBoard();
			repaint();
		}

		if(ae.getSource()==bsol)
		{
			bsol.setEnabled(false);
			undo.setEnabled(false);
			displaysol();
		}

		if(ae.getSource()==inst)
		{
			restart.setVisible(false);
			bsol.setVisible(false);
			inst.setVisible(false);
			back.setVisible(true);
			undo.setVisible(false);
			instructions=true;
			repaint();
		}

		if(ae.getSource()==back)
		{
			restart.setVisible(true);
			bsol.setVisible(true);
			inst.setVisible(true);
			back.setVisible(false);
			undo.setVisible(true);
			instructions=false;
			repaint();
		}

		if(ae.getSource()==undo)
		{
			gameend=false;
			undoMove();
			repaint();
		}
	}

	//POP THE VALUES OF THE PREVIOUS MOVE FROM THE STACK AND UNDO THIS MOVE
	public void undoMove()
	{
		o=(Integer)u.pop();
		pickY=o.intValue();
		o=(Integer)u.pop();
		pickX=o.intValue();
		o=(Integer)u.pop();
		dragY=o.intValue();
		o=(Integer)u.pop();
		dragX=o.intValue();
		board[pickY*7+pickX]=0;
		board[dragY*7+dragX]=1;
		board[((pickY+dragY)/2)*7+(pickX+dragX)/2]=1;
		deadBalls--;
		if(u.empty())
		{
			undo.setEnabled(false);
			bsol.setEnabled(true);
		}
	}

	public void fixBox(Graphics g,int x,int y,int w,int h,Color c)
	{
		g.setColor(c);
		g.fillRect(x,y,w,h);
	}

	public void fixDisc(Graphics g,int x,int y,int r,Color c)
	{
		g.setColor(c);
		g.fillOval(x,y,r,r);
	}

	public void fixCircle(Graphics g,int x,int y,int r,Color c)
	{
		g.setColor(c);
		g.drawOval(x,y,r,r);
	}

	//DRAW A BALL ON THE BOARD AT THE SPECIFIED LOCATION
	public void boardBall(Graphics g,int x, int y)
	{
		g.setColor(Color.white);
		g.fillRect(x,y,16,16);
		fixDisc(g,x+1,y+1,15,Color.black);
		fixDisc(g,x,y,14,Color.green);
	}

	//DRAW AN EMPTY SPACE AT THE SPECIFIED LOCATION
	public void boardHole(Graphics g,int x,int y)
	{
		g.setColor(Color.white);
		g.fillRect(x,y,16,16);
		fixDisc(g,x,y,14,Color.black);
	}

	//DRAW A BALL THAT HAS BEEN REMOVED
	public void deadBall(Graphics g,int x,int y)
	{
		fixDisc(g,x+1,y+1,15,Color.black);
		fixDisc(g,x,y,14,Color.cyan);
	}

	//PERFORN THE ACTION WHEN THE MOUSE IS PRESSED DOWN
	public boolean mouseDown(Event e,int x,int y)
	{
		pointX=-1;
		pointY=-1;
		pickX=-1;
		pickY=-1;
		dragX=-1;
		dragY=-1;

		//CALCULATE THE X AND Y INDEX OF THE POSITION ON THE BOARD
		i=(y-34)/17;
		j=(x-34)/17;

		//IF IT IS A VALID POSITION
		if((i>-1) && (i<7) && (j>-1) && (j<7))
		{
			pointX=x;
			pointY=y;
			pickX=j;
			pickY=i;
		}
		return false;
	}

	//PERFORM THE ACTION WHEN THE MOUSE IS DRAGGED
	public boolean mouseDrag(Event e,int x,int y)
	{
		//IF MOUSE IS DRAGGED ALONG THE Y-AXIS
		if((x<pointX+8) && (x>pointX-8))
		{
			//IF MOUSE IS DRAGGED UP
			if((pickY>1) && (y<pointY-14))
			{
				//IF BALL JUMP IS VALID
				if((board[pickY*7+pickX-7]==1) && (board[pickY*7+pickX-14]==0))
				{
					dragX=pickX;
					dragY=pickY-2;
				}
			}

			//IF MOUSE IS DRAGGED DOWN
			else if((pickY<5) && (y>pointY+14))

			{
				//IF BALL JUMP IS VALID
				if((board[pickY*7+pickX+7]==1) && (board[pickY*7+pickX+14]==0))
				{
					dragX=pickX;
					dragY=pickY+2;
				}
			}
		}

		//IF MOUSE IS DRAGGED ALONG THE X AXIS
		else if((y<pointY+8) && (y>pointY-8))
		{
			//IF MOUSE IS DRAGGED TO THE LEFT
			if((pickX>1) && (x<pointX-14))
			{
				//IF BALL JUMP IS VALID
				if((board[pickY*7+pickX-1]==1) && (board[pickY*7+pickX-2]==0))
				{
					dragX=pickX-2;
					dragY=pickY;
				}
			}

			//IF MOUSE IS DRAGGED TO THE RIGHT
			else if((pickX<5) && (x>pointX+14))
			{
				//IF BALL JUMP IS VALID
				if((board[pickY*7+pickX+1]==1) && (board[pickY*7+pickX+2]==0))
				{
					dragX=pickX+2;
					dragY=pickY;
				}
			}
		}
		return false;
	}

	//PERFORM THE ACTION WHEN THE MOUSE IS RELEASED
	public boolean mouseUp(Event e,int x,int y)
	{
		//IF MOUSE WAS DRAGGED TO A VALID POSITION
		if(dragX>-1)
		{
			//PERFORM THE BALL JUMP OPERATION
			undo.setEnabled(true);
			board[pickY*7+pickX]=0;
			board[dragY*7+dragX]=1;
			board[7*(pickY+dragY)/2+(pickX+dragX)/2]=0;
			deadBalls++;
			bsol.setEnabled(false);
			if(gameover())
				gameend=true;

			//PUSH THE VALUES OF pickX,pickY,dragX,
			//dragY ONTO THE STACK TO IMPLEMENT UNDO
			Integer pX=new Integer(pickX);
			u.push(pX);
			Integer pY=new Integer(pickY);
			u.push(pY);
			Integer dX=new Integer(dragX);
			u.push(dX);
			Integer dY=new Integer(dragY);
			u.push(dY);
			repaint();
		}
		return false;
	}

	public void update(Graphics g)
	{
		paint(g);
	}

	//CHECKS IF THE GAME IS OVER
	public boolean gameover()
	{
		for(i=2;i<5;i++)
			for(j=2;j<5;j++)
			{
				if(board[i*7+j]==1)
				{
					if((board[i*7+j-7]==1) && (board[i*7+j-14]==0))
						return false;
					if((board[i*7+j-1]==1) && (board[i*7+j-2]==0))
						return false;
					if((board[i*7+j+7]==1) && (board[i*7+j+14]==0))
						return false;
					if((board[i*7+j+1]==1) && (board[i*7+j+2]==0))
						return false;
				}
				else
				{
					if((board[i*7+j-7]==1) && (board[i*7+j-14]==1))
						return false;
					if((board[i*7+j-1]==1) && (board[i*7+j-2]==1))
						return false;
					if((board[i*7+j+7]==1) && (board[i*7+j+14]==1))
						return false;
					if((board[i*7+j+1]==1) && (board[i*7+j+2]==1))
						return false;
				}

			}

		for(i=0;i<2;i++)
		{
			if((board[i*7+2]==1) && (board[i*7+3]==1) && (board[i*7+4]==0))
				return false;
			if((board[i*7+2]==0) && (board[i*7+3]==1) && (board[i*7+4]==1))
				return false;
			if((board[i*7+2+35]==1) && (board[i*7+3+35]==1) && (board[i*7+4+35]==0))
				return false;
			if((board[i*7+2+35]==0) && (board[i*7+3+35]==1) && (board[i*7+4+35]==1))
				return false;
			if((board[2*7+i]==1) && (board[3*7+i]==1) && (board[4*7+i]==0))
				return false;
			if((board[2*7+i]==0) && (board[3*7+i]==1) && (board[4*7+i]==1))
				return false;
			if((board[2*7+i+5]==1) && (board[3*7+i+5]==1) && (board[4*7+i+5]==0))
				return false;
			if((board[2*7+i+5]==0) && (board[3*7+i+5]==1) && (board[4*7+i+5]==1))
				return false;
		}

		return true;
	}

	//PAINT FUNCTION DISPLAYS THE GAME
	public void paint(Graphics g)
	{
		showStatus("Welcome to BrainVita--A marble game By Mikhail Chainani");
		g.setColor(Color.lightGray);
		g.fillRect(0,0,size().width,size().height);

		//IF USER DOES NOT WANT TO VIEW THE INSTRUCTIONS
		if(instructions==false)
		{
			//DISPLAY THE BOARD
			fixDisc(g,2,2,187,Color.gray);
			fixDisc(g,0,0,185,Color.white);
			fixCircle(g,10,10,165,Color.black);

			//IF GAME IS OVER DISPLAY THE SCORE
			if(gameend)
			{
				g.drawString("Game Over!",55,75);
				g.drawString("Your Score is--"+(32-deadBalls),45,90);
				if(32-deadBalls==1)
					g.drawString("CONGRATULATIONS",30,105);
			}

			else
			{
				//DISPLAY THE BALLS IN THE APPROPRIATE POSITION
				for (i=0;i<7;i++)
					for (j=0;j<7;j++)
						if (board[i*7+j]>-1)
							if (board[i*7+j]==0)
								boardHole(g,34+j*17,34+i*17);
							else
								boardBall(g,34+j*17,34+i*17);

				//THE ELIMINATED BALLS OUTSIDE THE BOARD
				for (i=0;i<deadBalls;i++)
				{
					if(i<16)
						deadBall(g,5+i*17,195);
					else
						deadBall(g,5+(i-16)*17,212);
				}
			}
		}

		//DISPLAY THE INSTRUCTION
		else
		{
			displayinst(g);
		}
	}

	//CRAETE A NEW THREAD TO FIND OPTIMAL SOLUTION
	public void displaysol()
	{
		t=new Thread(this);
		t.start();
	}

	//THREAD RUN FUNCTION TO CALCULATE THE OPTIMAL SOLUTION
	public void run()
	{
		for(count=0;count<solution.length;count++)
		{
			int X=-1,Y=-1;
			board[solution[count][1]*7+solution[count][0]]=0;
			switch(solution[count][2])
			{
				case UP:
					Y=solution[count][1]-2;
					X=solution[count][0];
					break;
				case DOWN:
					Y=solution[count][1]+2;
					X=solution[count][0];
					break;
				case RIGHT:
					Y=solution[count][1];
					X=solution[count][0]+2;
					break;
				case LEFT:
					Y=solution[count][1];
					X=solution[count][0]-2;
					break;
			}
			deadBalls+=1;
			board[Y*7+X]=1;
			board[((solution[count][1]+Y)/2)*7+(solution[count][0]+X)/2]=0;
			repaint();

			//INSERT A 1.5 SEC DELAY
			try
			{
				Thread.sleep(1500);
			}
			catch(InterruptedException e)	{System.out.println("Interrupted");}
		}
		gameend=true;
		t.stop();
	}

	//DISPLAY THE INSTRUCTIONS
	public void displayinst(Graphics g)
	{
		g.setColor(Color.blue);
		g.drawString("Welome to Brainvita--A marble game",75,15);
		g.drawString("**********OBJECTIVE**********",100,45);
		g.drawString("You have to eliminate as many marbles as possible. Select a marble",15,60);
		g.drawString("and jump it over an adjecent marble to remove it. (the middle marble)",15,75);
		g.drawString("*********INSTRUCTIONS********",100,105);
		g.drawString("Drag a marble using the mouse to jump it over another marble",15,120);
		g.drawString("************SCORE************",100,150);
		g.drawString("Your score is the number of marbles remaining after the game is over.",15,165);
		g.drawString("above 6--This game isn't for monkeys",15,195);
		g.drawString("6--Better luck next time",15,210);
		g.drawString("5--Average",15,225);
		g.drawString("4--Just above average",15,240);
		g.drawString("3--Good work",15,255);
		g.drawString("2--Almost there",15,270);
		g.drawString("1--Pure Genius",15,285);
	}
} 
by

Java online compiler

Write, Run & Share Java code online using OneCompiler's Java online compiler for free. It's one of the robust, feature-rich online compilers for Java language, running the Java LTS version 17. Getting started with the OneCompiler's Java editor is easy and fast. The editor shows sample boilerplate code when you choose language as Java and start coding.

Taking inputs (stdin)

OneCompiler's Java online editor supports stdin and users can give inputs to the programs using the STDIN textbox under the I/O tab. Using Scanner class in Java program, you can read the inputs. Following is a sample program that shows reading STDIN ( A string in this case ).

import java.util.Scanner;
class Input {
    public static void main(String[] args) {
    	Scanner input = new Scanner(System.in);
    	System.out.println("Enter your name: ");
    	String inp = input.next();
    	System.out.println("Hello, " + inp);
    }
}

Adding dependencies

OneCompiler supports Gradle for dependency management. Users can add dependencies in the build.gradle file and use them in their programs. When you add the dependencies for the first time, the first run might be a little slow as we download the dependencies, but the subsequent runs will be faster. Following sample Gradle configuration shows how to add dependencies

apply plugin:'application'
mainClassName = 'HelloWorld'

run { standardInput = System.in }
sourceSets { main { java { srcDir './' } } }

repositories {
    jcenter()
}

dependencies {
    // add dependencies here as below
    implementation group: 'org.apache.commons', name: 'commons-lang3', version: '3.9'
}

About Java

Java is a very popular general-purpose programming language, it is class-based and object-oriented. Java was developed by James Gosling at Sun Microsystems ( later acquired by Oracle) the initial release of Java was in 1995. Java 17 is the latest long-term supported version (LTS). As of today, Java is the world's number one server programming language with a 12 million developer community, 5 million students studying worldwide and it's #1 choice for the cloud development.

Syntax help

Variables

short x = 999; 			// -32768 to 32767
int   x = 99999; 		// -2147483648 to 2147483647
long  x = 99999999999L; // -9223372036854775808 to 9223372036854775807

float x = 1.2;
double x = 99.99d;

byte x = 99; // -128 to 127
char x = 'A';
boolean x = true;

Loops

1. If Else:

When ever you want to perform a set of operations based on a condition If-Else is used.

if(conditional-expression) {
  // code
} else {
  // code
}

Example:

int i = 10;
if(i % 2 == 0) {
  System.out.println("i is even number");
} else {
  System.out.println("i is odd number");
}

2. Switch:

Switch is an alternative to If-Else-If ladder and to select one among many blocks of code.

switch(<conditional-expression>) {    
case value1:    
 // code    
 break;  // optional  
case value2:    
 // code    
 break;  // optional  
...    
    
default:     
 //code to be executed when all the above cases are not matched;    
} 

3. For:

For loop is used to iterate a set of statements based on a condition. Usually for loop is preferred when number of iterations is known in advance.

for(Initialization; Condition; Increment/decrement){  
    //code  
} 

4. While:

While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.

while(<condition>){  
 // code 
}  

5. Do-While:

Do-while is also used to iterate a set of statements based on a condition. It is mostly used when you need to execute the statements atleast once.

do {
  // code 
} while (<condition>); 

Classes and Objects

Class is the blueprint of an object, which is also referred as user-defined data type with variables and functions. Object is a basic unit in OOP, and is an instance of the class.

How to create a Class:

class keyword is required to create a class.

Example:

class Mobile {
    public:    // access specifier which specifies that accessibility of class members 
    string name; // string variable (attribute)
    int price; // int variable (attribute)
};

How to create a Object:

Mobile m1 = new Mobile();

How to define methods in a class:

public class Greeting {
    static void hello() {
        System.out.println("Hello.. Happy learning!");
    }

    public static void main(String[] args) {
        hello();
    }
}

Collections

Collection is a group of objects which can be represented as a single unit. Collections are introduced to bring a unified common interface to all the objects.

Collection Framework was introduced since JDK 1.2 which is used to represent and manage Collections and it contains:

  1. Interfaces
  2. Classes
  3. Algorithms

This framework also defines map interfaces and several classes in addition to Collections.

Advantages:

  • High performance
  • Reduces developer's effort
  • Unified architecture which has common methods for all objects.
CollectionDescription
SetSet is a collection of elements which can not contain duplicate values. Set is implemented in HashSets, LinkedHashSets, TreeSet etc
ListList is a ordered collection of elements which can have duplicates. Lists are classified into ArrayList, LinkedList, Vectors
QueueFIFO approach, while instantiating Queue interface you can either choose LinkedList or PriorityQueue.
DequeDeque(Double Ended Queue) is used to add or remove elements from both the ends of the Queue(both head and tail)
MapMap contains key-values pairs which don't have any duplicates. Map is implemented in HashMap, TreeMap etc.