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

Interview Tip : Q1) Why Strings are immutable in java ? What happen if it was mutable in java?
As we all know that Strings in java are immutabe in nature, now the question comes why the creator made it immutable in nature, although this field used maximum in any java program. The answer to this...

ClassNotFoundException vs NoClassDefFoundError
ClassNotFoundException NoClassDefFoundError It is an exception and happens due to programmer’s mistake and can be recovered by updating the code. Thrown when an application tries...

Class and Objects in Java
Class is a template or a blueprint which is used to describe an object. On other hand Object is a reference of a class which follows all the stuff written inside the class. How about taking the whole tour in the following video

TestNG Annotations and its sequence
public class TestNGAnnotations { @BeforeMethod public void beforeM() { System.out.println("Before Method"); } @AfterMethod public void afterMethod() { System.out.println("After Method"); } @BeforeClass...
S

Sarthak C.

0 0
0

Crux Of The Basic Interview Question Asked Around It Professionals
Question: Explain PSVM() in Java. Answer: This question is asked from a differnet persctive. Person asking this question is looking for deep java concepts. If answer in your mind is something like...
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