UrbanPro
true

Learn Java Training from the Best Tutors

  • Affordable fees
  • 1-1 or Group class
  • Flexible Timings
  • Verified Tutors

Search in

Puzzle Game coding

Venkatesh Kammampati
08/07/2019 0 0

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Random;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

import java.util.Random;
public class GameOfFifteen extends JPanel
{
private int size;
private int nbTiles;
private int dimension;
private static final Color FOREGROUND_COLOR=new Color(239,83,80);
private static final Random RANDOM=new Random();
private int[] tiles;
private int tileSize;
private int blankPos;
private int margin;
private int gridSize;
private boolean gameOver;
public GameOfFifteen(int size, int dimension, int margin)
{
super();
this.size = size;
this.dimension = dimension;
this.margin = margin;
nbTiles=size*size-1;
tiles=new int[size*size];
gridSize=(dimension-2*margin);
tileSize=gridSize/size;
setPreferredSize(new Dimension(dimension,dimension+margin));
setBackground(Color.WHITE);
setForeground(FOREGROUND_COLOR);
setFont(new Font("SansSerif",Font.BOLD,60));
gameOver=true;
addMouseListener(new MouseAdapter(){

public void mousePressed(MouseEvent e)
{

if(gameOver)
{
newGame();
}
else
{
int dir=0;
int ex=e.getX()-margin;
int ey=e.getY()-margin;
if(ex<0||ex>gridSize||ey<0||ey>gridSize)
return;
int c1=ex/tileSize;
int r1=ey/tileSize;
int c2=blankPos%size;
int r2=blankPos/size;
int clickPos=r1*size+c1;
if(c1==c2 && Math.abs(r1-r2)>0)

dir=(r1-r2)>0 ? size:-size;

else if(r1==r2 && Math.abs(c1-c2)>0)
dir=(c1-c2)>0? 1:-1;

if(dir!=0)
{
do {
int newBlankPos=blankPos+dir;
tiles[blankPos]=tiles[newBlankPos];
blankPos=newBlankPos;
}while(blankPos!=clickPos);
tiles[blankPos]=0;
}
gameOver=isSolved();
}
repaint();
}
});
newGame();

}
private void newGame() {
do {
reset();
shuffle();
}while(!isSolvable());
gameOver=false;
}
private void reset() {
for(int i=0;i<tiles.length;i++) {
tiles[i]=(i+1)%tiles.length;
}
blankPos=tiles.length-1;
}
private void shuffle()
{
int n=nbTiles;
while(n>1)
{
int r=RANDOM.nextInt(n--);
int tmp=tiles[r];
tiles[r]=tiles[n];
tiles[n]=tmp;
}
}
private boolean isSolvable()
{
int countInversions=0;
for(int i=0;i<nbTiles;i++)
{
for(int j=0;j<i;j++)
{
if(tiles[j]>tiles[i])
countInversions++;
}
}
return countInversions%2==0;
}
private boolean isSolved()
{
if(tiles[tiles.length-1]!=0)
return false;
for(int i=nbTiles-1;i>=0;i--)
{
if(tiles[i]!=i+1)
return false;
}
return true;
}
private void drawGrid(Graphics2D g)
{
for(int i=0;i<tiles.length;i++)
{
int r=i/size;
int c=i%size;
int x=margin+c*tileSize;
int y=margin+r*tileSize;
if(tiles[i]==0) {
if(gameOver) {
g.setColor(FOREGROUND_COLOR);
drawCenteredString(g,"|///",x,y);
}
continue;
}
g.setColor(getForeground());
g.fillRoundRect(x, y, tileSize, tileSize, 25, 25);
g.setColor(Color.BLACK);
g.drawRoundRect(x,y,tileSize,tileSize,25,25);
g.setColor(Color.WHITE);
drawCenteredString(g,String.valueOf(tiles[i]),x,y);
}
}
private void drawStartMessage(Graphics2D g) {
if(gameOver) {
g.setFont(getFont().deriveFont(Font.BOLD,18));
g.setColor(FOREGROUND_COLOR);
String s="Click to start new game";
g.drawString(s, (getWidth()-g.getFontMetrics().stringWidth(s))/2, getHeight()-margin);
}
}
private void drawCenteredString(Graphics2D g,String s,int x,int y)
{
FontMetrics fm=g.getFontMetrics();
int asc=fm.getAscent();
int desc=fm.getDescent();
g.drawString(s,x+(tileSize-fm.stringWidth(s))/2,y+(asc+(tileSize-(asc+desc))/2));
}
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2D=(Graphics2D)g;
g2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
drawGrid(g2D);
drawStartMessage(g2D);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(() ->
{
JFrame frame=new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Game of Fifteen");
frame.setResizable(false);
frame.add(new GameOfFifteen(4,550,30),BorderLayout.CENTER);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
}

0 Dislike
Follow 2

Please Enter a comment

Submit

Other Lessons for You

Spring - Dependency Injection (DI)
Spring - Dependency Injection (DI) DI is a framework which provides loose coupling in code. Here loose coupling means no hard coding of the object. Instead of hard coding, we will be injecting these object...

Java Advantages
In this video, learn about Java and its advantages. Also, check out the difference between Java and C++, Java development kit, Java Run Time Environment (JRE) with a proper demonstration program for better clarity.

Java : Compile-time Versus Runtime optimization
While designing and development, one should think in terms of compile-time and run-time.It helps in understanding language basics in a better way.Let's understand this with a question below : What...
S

CONDITIONAL STATEMENT - IF ELSE
1. IF condition only if is true conditon is required. if(condition){//statements} 2. IF-ELSE condition 1. to check whether the condition will be true or false.syntax of if-else2. only 1 conditionif(condition){//statements}else{//statements} 3....

Why Should We Learn Java Language?
Most of starters has confusion today that which of the programming language should be chosen to work on. It totally depends upon your need. As per my opinion, if you want to grow your career in IT industry...
X

Looking for Java Training Classes?

The best tutors for Java Training Classes are on UrbanPro

  • Select the best Tutor
  • Book & Attend a Free Demo
  • Pay and start Learning

Learn Java Training with the Best Tutors

The best Tutors for Java Training Classes are on UrbanPro

This website uses cookies

We use cookies to improve user experience. Choose what cookies you allow us to use. You can read more about our Cookie Policy in our Privacy Policy

Accept All
Decline All

UrbanPro.com is India's largest network of most trusted tutors and institutes. Over 55 lakh students rely on UrbanPro.com, to fulfill their learning requirements across 1,000+ categories. Using UrbanPro.com, parents, and students can compare multiple Tutors and Institutes and choose the one that best suits their requirements. More than 7.5 lakh verified Tutors and Institutes are helping millions of students every day and growing their tutoring business on UrbanPro.com. Whether you are looking for a tutor to learn mathematics, a German language trainer to brush up your German language skills or an institute to upgrade your IT skills, we have got the best selection of Tutors and Training Institutes for you. Read more