Coding pacman in java

Source Code : Pacman Game with Java

pacman is the game to gather all the points in the labyrinth and avoid the spirits. The pacman is cartoon in two ways. His position in the labyrinth and his whole body. We animate his whole body with four pictures, based on the direction. The movement is used to create the impression of pacman buying and selling his mouth. The labyrinth includes 15 x 15 pieces. The framework of the labyrinth is based on a simple array of integers. Pacman has three lives. We also depend the score.

SOURCE CODE JAVA PACMAN GAME :

This code is for the boards:

package pacman; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Dimension; import java.awt.Event; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import javax.swing.ImageIcon; import javax.swing.JPanel; import javax.swing.Timer; public class Board extends JPanel implements ActionListener < Dimension d; Font smallfont = new Font("Helvetica", Font.BOLD, 14); FontMetrics fmsmall, fmlarge; Image ii; Color dotcolor = new Color(192, 192, 0); Color mazecolor; boolean ingame = false; boolean dying = false; final int blocksize = 24; final int nrofblocks = 15; final int scrsize = nrofblocks * blocksize; final int pacanimdelay = 2; final int pacmananimcount = 4; final int maxghosts = 12; final int pacmanspeed = 6; int pacanimcount = pacanimdelay; int pacanimdir = 1; int pacmananimpos = 0; int nrofghosts = 6; int pacsleft, score; int deathcounter; int[] dx, dy; int[] ghostx, ghosty, ghostdx, ghostdy, ghostspeed; Image ghost; Image pacman1, pacman2up, pacman2left, pacman2right, pacman2down; Image pacman3up, pacman3down, pacman3left, pacman3right; Image pacman4up, pacman4down, pacman4left, pacman4right; int pacmanx, pacmany, pacmandx, pacmandy; int reqdx, reqdy, viewdx, viewdy; final short leveldata[] = < 19, 26, 26, 26, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 22, 21, 0, 0, 0, 17, 16, 16, 16, 16, 16, 16, 16, 16, 16, 20, 21, 0, 0, 0, 17, 16, 16, 16, 16, 16, 16, 16, 16, 16, 20, 21, 0, 0, 0, 17, 16, 16, 24, 16, 16, 16, 16, 16, 16, 20, 17, 18, 18, 18, 16, 16, 20, 0, 17, 16, 16, 16, 16, 16, 20, 17, 16, 16, 16, 16, 16, 20, 0, 17, 16, 16, 16, 16, 24, 20, 25, 16, 16, 16, 24, 24, 28, 0, 25, 24, 24, 16, 20, 0, 21, 1, 17, 16, 20, 0, 0, 0, 0, 0, 0, 0, 17, 20, 0, 21, 1, 17, 16, 16, 18, 18, 22, 0, 19, 18, 18, 16, 20, 0, 21, 1, 17, 16, 16, 16, 16, 20, 0, 17, 16, 16, 16, 20, 0, 21, 1, 17, 16, 16, 16, 16, 20, 0, 17, 16, 16, 16, 20, 0, 21, 1, 17, 16, 16, 16, 16, 16, 18, 16, 16, 16, 16, 20, 0, 21, 1, 17, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 20, 0, 21, 1, 25, 24, 24, 24, 24, 24, 24, 24, 24, 16, 16, 16, 18, 20, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 25, 24, 24, 24, 28 >; final int validspeeds[] = < 1, 2, 3, 4, 6, 8 >; final int maxspeed = 6; int currentspeed = 3; short[] screendata; Timer timer; public Board() < GetImages(); addKeyListener(new TAdapter()); screendata = new short[nrofblocks * nrofblocks]; mazecolor = new Color(5, 100, 5); setFocusable(true); d = new Dimension(400, 400); setBackground(Color.black); setDoubleBuffered(true); ghostx = new int[maxghosts]; ghostdx = new int[maxghosts]; ghosty = new int[maxghosts]; ghostdy = new int[maxghosts]; ghostspeed = new int[maxghosts]; dx = new int[4]; dy = new int[4]; timer = new Timer(40, this); timer.start(); >public void addNotify() < super.addNotify(); GameInit(); >public void DoAnim() < pacanimcount--; if (pacanimcount > public void PlayGame(Graphics2D g2d) < if (dying) < Death(); >else < MovePacMan(); DrawPacMan(g2d); moveGhosts(g2d); CheckMaze(); >> public void ShowIntroScreen(Graphics2D g2d) < g2d.setColor(new Color(0, 32, 48)); g2d.fillRect(50, scrsize / 2 - 30, scrsize - 100, 50); g2d.setColor(Color.white); g2d.drawRect(50, scrsize / 2 - 30, scrsize - 100, 50); String s = "Press s to start."; Font small = new Font("Helvetica", Font.BOLD, 14); FontMetrics metr = this.getFontMetrics(small); g2d.setColor(Color.white); g2d.setFont(small); g2d.drawString(s, (scrsize - metr.stringWidth(s)) / 2, scrsize / 2); >public void DrawScore(Graphics2D g) < int i; String s; g.setFont(smallfont); g.setColor(new Color(96, 128, 255)); s = "Score: " + score; g.drawString(s, scrsize / 2 + 96, scrsize + 16); for (i = 0; i < pacsleft; i++) < g.drawImage(pacman3left, i * 28 + 8, scrsize + 1, this); >> public void CheckMaze() < short i = 0; boolean finished = true; while (i < nrofblocks * nrofblocks && finished) < if ((screendata[i] & 48) != 0) finished = false; i++; >if (finished) < score += 50; if (nrofghosts < maxghosts) nrofghosts++; if (currentspeed < maxspeed) currentspeed++; LevelInit(); >> public void Death() < pacsleft--; if (pacsleft == 0) ingame = false; LevelContinue(); >public void moveGhosts(Graphics2D g2d) < short i; int pos; int count; for (i = 0; i < nrofghosts; i++) < if (ghostx[i] % blocksize == 0 && ghosty[i] % blocksize == 0) < pos = ghostx[i] / blocksize + nrofblocks * (int)(ghosty[i] / blocksize); count = 0; if ((screendata[pos] & 1) == 0 && ghostdx[i] != 1) < dx[count] = -1; dy[count] = 0; count++; >if ((screendata[pos] & 2) == 0 && ghostdy[i] != 1) < dx[count] = 0; dy[count] = -1; count++; >if ((screendata[pos] & 4) == 0 && ghostdx[i] != -1) < dx[count] = 1; dy[count] = 0; count++; >if ((screendata[pos] & 8) == 0 && ghostdy[i] != -1) < dx[count] = 0; dy[count] = 1; count++; >if (count == 0) < if ((screendata[pos] & 15) == 15) < ghostdx[i] = 0; ghostdy[i] = 0; >else < ghostdx[i] = -ghostdx[i]; ghostdy[i] = -ghostdy[i]; >> else < count = (int)(Math.random() * count); if (count >3) count = 3; ghostdx[i] = dx[count]; ghostdy[i] = dy[count]; > > ghostx[i] = ghostx[i] + (ghostdx[i] * ghostspeed[i]); ghosty[i] = ghosty[i] + (ghostdy[i] * ghostspeed[i]); DrawGhost(g2d, ghostx[i] + 1, ghosty[i] + 1); if (pacmanx > (ghostx[i] - 12) && pacmanx < (ghostx[i] + 12) && pacmany >(ghosty[i] - 12) && pacmany < (ghosty[i] + 12) && ingame) < dying = true; deathcounter = 64; >> > public void DrawGhost(Graphics2D g2d, int x, int y) < g2d.drawImage(ghost, x, y, this); >public void MovePacMan() < int pos; short ch; if (reqdx == -pacmandx && reqdy == -pacmandy) < pacmandx = reqdx; pacmandy = reqdy; viewdx = pacmandx; viewdy = pacmandy; >if (pacmanx % blocksize == 0 && pacmany % blocksize == 0) < pos = pacmanx / blocksize + nrofblocks * (int)(pacmany / blocksize); ch = screendata[pos]; if ((ch & 16) != 0) < screendata[pos] = (short)(ch & 15); score++; >if (reqdx != 0 || reqdy != 0) < if (!((reqdx == -1 && reqdy == 0 && (ch & 1) != 0) || (reqdx == 1 && reqdy == 0 && (ch & 4) != 0) || (reqdx == 0 && reqdy == -1 && (ch & 2) != 0) || (reqdx == 0 && reqdy == 1 && (ch & 8) != 0))) < pacmandx = reqdx; pacmandy = reqdy; viewdx = pacmandx; viewdy = pacmandy; >> // Check for standstill if ((pacmandx == -1 && pacmandy == 0 && (ch & 1) != 0) || (pacmandx == 1 && pacmandy == 0 && (ch & 4) != 0) || (pacmandx == 0 && pacmandy == -1 && (ch & 2) != 0) || (pacmandx == 0 && pacmandy == 1 && (ch & 8) != 0)) < pacmandx = 0; pacmandy = 0; >> pacmanx = pacmanx + pacmanspeed * pacmandx; pacmany = pacmany + pacmanspeed * pacmandy; > public void DrawPacMan(Graphics2D g2d) < if (viewdx == -1) DrawPacManLeft(g2d); else if (viewdx == 1) DrawPacManRight(g2d); else if (viewdy == -1) DrawPacManUp(g2d); else DrawPacManDown(g2d); >public void DrawPacManUp(Graphics2D g2d) < switch (pacmananimpos) < case 1: g2d.drawImage(pacman2up, pacmanx + 1, pacmany + 1, this); break; case 2: g2d.drawImage(pacman3up, pacmanx + 1, pacmany + 1, this); break; case 3: g2d.drawImage(pacman4up, pacmanx + 1, pacmany + 1, this); break; default: g2d.drawImage(pacman1, pacmanx + 1, pacmany + 1, this); break; >> public void DrawPacManDown(Graphics2D g2d) < switch (pacmananimpos) < case 1: g2d.drawImage(pacman2down, pacmanx + 1, pacmany + 1, this); break; case 2: g2d.drawImage(pacman3down, pacmanx + 1, pacmany + 1, this); break; case 3: g2d.drawImage(pacman4down, pacmanx + 1, pacmany + 1, this); break; default: g2d.drawImage(pacman1, pacmanx + 1, pacmany + 1, this); break; >> public void DrawPacManLeft(Graphics2D g2d) < switch (pacmananimpos) < case 1: g2d.drawImage(pacman2left, pacmanx + 1, pacmany + 1, this); break; case 2: g2d.drawImage(pacman3left, pacmanx + 1, pacmany + 1, this); break; case 3: g2d.drawImage(pacman4left, pacmanx + 1, pacmany + 1, this); break; default: g2d.drawImage(pacman1, pacmanx + 1, pacmany + 1, this); break; >> public void DrawPacManRight(Graphics2D g2d) < switch (pacmananimpos) < case 1: g2d.drawImage(pacman2right, pacmanx + 1, pacmany + 1, this); break; case 2: g2d.drawImage(pacman3right, pacmanx + 1, pacmany + 1, this); break; case 3: g2d.drawImage(pacman4right, pacmanx + 1, pacmany + 1, this); break; default: g2d.drawImage(pacman1, pacmanx + 1, pacmany + 1, this); break; >> public void DrawMaze(Graphics2D g2d) < short i = 0; int x, y; for (y = 0; y < scrsize; y += blocksize) < for (x = 0; x < scrsize; x += blocksize) < g2d.setColor(mazecolor); g2d.setStroke(new BasicStroke(2)); if ((screendata[i] & 1) != 0) // draws left < g2d.drawLine(x, y, x, y + blocksize - 1); >if ((screendata[i] & 2) != 0) // draws top < g2d.drawLine(x, y, x + blocksize - 1, y); >if ((screendata[i] & 4) != 0) // draws right < g2d.drawLine(x + blocksize - 1, y, x + blocksize - 1, y + blocksize - 1); >if ((screendata[i] & 8) != 0) // draws bottom < g2d.drawLine(x, y + blocksize - 1, x + blocksize - 1, y + blocksize - 1); >if ((screendata[i] & 16) != 0) // draws point < g2d.setColor(dotcolor); g2d.fillRect(x + 11, y + 11, 2, 2); >i++; > > > public void GameInit() < pacsleft = 3; score = 0; LevelInit(); nrofghosts = 6; currentspeed = 3; >public void LevelInit() < int i; for (i = 0; i < nrofblocks * nrofblocks; i++) screendata[i] = leveldata[i]; LevelContinue(); >public void LevelContinue() < short i; int dx = 1; int random; for (i = 0; i < nrofghosts; i++) < ghosty[i] = 4 * blocksize; ghostx[i] = 4 * blocksize; ghostdy[i] = 0; ghostdx[i] = dx; dx = -dx; random = (int)(Math.random() * (currentspeed + 1)); if (random >currentspeed) random = currentspeed; ghostspeed[i] = validspeeds[random]; > pacmanx = 7 * blocksize; pacmany = 11 * blocksize; pacmandx = 0; pacmandy = 0; reqdx = 0; reqdy = 0; viewdx = -1; viewdy = 0; dying = false; > public void GetImages() < ghost = new ImageIcon(Board.class.getResource("../pacpix/ghost.png")).getImage(); pacman1 = new ImageIcon(Board.class.getResource("../pacpix/pacman.png")).getImage(); pacman2up = new ImageIcon(Board.class.getResource("../pacpix/up1.png")).getImage(); pacman3up = new ImageIcon(Board.class.getResource("../pacpix/up2.png")).getImage(); pacman4up = new ImageIcon(Board.class.getResource("../pacpix/up3.png")).getImage(); pacman2down = new ImageIcon(Board.class.getResource("../pacpix/down1.png")).getImage(); pacman3down = new ImageIcon(Board.class.getResource("../pacpix/down2.png")).getImage(); pacman4down = new ImageIcon(Board.class.getResource("../pacpix/down3.png")).getImage(); pacman2left = new ImageIcon(Board.class.getResource("../pacpix/left1.png")).getImage(); pacman3left = new ImageIcon(Board.class.getResource("../pacpix/left2.png")).getImage(); pacman4left = new ImageIcon(Board.class.getResource("../pacpix/left3.png")).getImage(); pacman2right = new ImageIcon(Board.class.getResource("../pacpix/right1.png")).getImage(); pacman3right = new ImageIcon(Board.class.getResource("../pacpix/right2.png")).getImage(); pacman4right = new ImageIcon(Board.class.getResource("../pacpix/right3.png")).getImage(); >public void paint(Graphics g) < super.paint(g); Graphics2D g2d = (Graphics2D) g; g2d.setColor(Color.black); g2d.fillRect(0, 0, d.width, d.height); DrawMaze(g2d); DrawScore(g2d); DoAnim(); if (ingame) PlayGame(g2d); else ShowIntroScreen(g2d); g.drawImage(ii, 5, 5, this); Toolkit.getDefaultToolkit().sync(); g.dispose(); >class TAdapter extends KeyAdapter < public void keyPressed(KeyEvent e) < int key = e.getKeyCode(); if (ingame) < if (key == KeyEvent.VK_LEFT) < reqdx=-1; reqdy=0; >else if (key == KeyEvent.VK_RIGHT) < reqdx=1; reqdy=0; >else if (key == KeyEvent.VK_UP) < reqdx=0; reqdy=-1; >else if (key == KeyEvent.VK_DOWN) < reqdx=0; reqdy=1; >else if (key == KeyEvent.VK_ESCAPE && timer.isRunning()) < ingame=false; >else if (key == KeyEvent.VK_PAUSE) < if (timer.isRunning()) timer.stop(); else timer.start(); >> else < if (key == 's' || key == 'S') < ingame=true; GameInit(); >> > public void keyReleased(KeyEvent e) < int key = e.getKeyCode(); if (key == Event.LEFT || key == Event.RIGHT || key == Event.UP || key == Event.DOWN) < reqdx=0; reqdy=0; >> > public void actionPerformed(ActionEvent e) < repaint(); >>

The Commons.java file has some common constants.

Читайте также:  METANIT.COM

These numbers make up the maze. They provide information out of which we create the corners and the points. For example number 19 in the upper left corner means, that the square will have top and left borders and a point. (16 + 2 + 1)

The doAnim() counts the pacmananimpos variable, which determines what pacman image is drawn. There are four pacman images. There is also a pacanimdelay variable, which makes the animation a bit slower. Otherwise the pacman would open his mouth too fast.

boolean finished = true; while (i

This code is part of the checkMaze() method. It checks, if there are any points left for the Pacman to eat. Number 16 stands for a point. If all points are consumed, we move to the next level.

Next we will examine the moveGhosts() method. The ghosts move one square and then decide, if they change the direction.

if (ghostx[i] % blocksize == 0 && ghosty[i] % blocksize == 0) 

Continue only if you have finished moving one square.

pos = ghostx[i] / blocksize + nrofblocks * (int)(ghosty[i] / blocksize);

This line determines, where the ghost is situated. In which position/square. There are 225 theoretical positions. (A ghost cannot move over walls. )

if ((screendata[pos] & 1) == 0 && ghostdx[i] != 1)

If there is no obstacle on the left and the ghost is not already moving to the right, the ghost will move to the left. What does this code really mean? If the ghost enters a tunnel, he will continue in the same direction until he is out of the tunnel. Moving of ghosts is partly random. We do not apply this randomness inside long tunnels. The ghost might get stuck there.

if (pacmanx > (ghostx[i] - 12) && pacmanx < (ghostx[i] + 12) && pacmany >(ghosty[i] - 12) && pacmany

If there is a collision between ghosts and a pacman, the pacman dies.

Next we are going to examine the movePacman() method. The reqdx and reqdy variables are determined in the TAdapter inner class. These variables are controlled with cursor keys.

If the pacman moves to a position, where there is a point, we remove it from the maze and increase the score value.

if ((pacmandx == -1 && pacmandy == 0 && (ch & 1) != 0) || (pacmandx == 1 && pacmandy == 0 && (ch & 4) != 0) || (pacmandx == 0 && pacmandy == -1 && (ch & 2) != 0) || (pacmandx == 0 && pacmandy == 1 && (ch & 8) != 0))

If the pacman cannot move further it his current direction, there is a standstill.

public void drawPacMan(Graphics2D g2d)

There are four possible recommendations for a pacman. There are four images to all recommendations. The images are used to turn the pacman begin his mouth area shut.

The drawMaze () strategy draw a network out of numbers in the wide range screendata. Variety 1 is the staying boundary, 2 is the greater boundary, 4 is the real boundary, 8 and 16 is the decreased limit is the aspect. We just went through all 225 int box network. For example we have 9 in the wide range screendata. We had a bit first (1) and 4th items (8) locations. So we draw down and staying limitations in this particular rectangular shape.

if ((screendata[i] & 1) != 0) // draws left

Draw a left border if the first bit of a number is set this source code is for the pacman : 
package packman; import javax.swing.JFrame; import pacman.Board; public class PacMan extends JFrame < public PacMan() < add(new Board()); setTitle("Pacman"); setDefaultCloseOperation(EXIT_ON_CLOSE); setSize(380, 420); setLocationRelativeTo(null); setVisible(true); >public static void main(String[] args) < new PacMan(); >>

Источник

Pacman Game In Java With Source Code

Pacman Game in Java

Pacman Game In Java With Source Code

The Pacman Game In Java was developed using Java Programming Language, In This Article is a simple Pacman shooting game in java, The Pacman In Java gameplay is simple and easy for the users. All you have to do is just to use your mouse for shooting and ASWD key for directional movement and use the right click mouse button to fire the shot. You can use your mouse to decrease the speed of the shot.

A Pacman Java Game Download You can play this game in two formats, one versus the human player and the other as a multi-player. The Pacman For Java gameplay with the computer comes with various difficulties.

This game also includes a Pacman Java Source Code Download for free, just find the downloadable source code below and click to start downloading.

To start playing a Pacman Game In Java make sure that you have NetBeans IDE or any platform of Java installed on your computer.

Pacman Game In Java With Source Code steps on how to run the project

These are the steps on how to run Pacman Game In Java With Source Code

download source code

First, download the source code given below.

Step 2: Extract file.

pacman zip file

Second, after you finished download the source code, extract the zip file.

pacman open netbeans

Third, open “Netbeans IDE”.

Step 4: Click open project.

pacman open project

Fourth, click open project and choose your download source code.

Step 5: Add jar file.

pacman add jar files

Fifth, add all jar file into the project folder libraries.

pacman run project

Sixth, right click the project folder and click run.

Step 7: Enjoy playing!

The Code Given Below Is For The Main Module of The Game

package Game; import static Game.GameFont.optionBlue; import org.newdawn.slick.AppGameContainer; import org.newdawn.slick.BasicGame; import org.newdawn.slick.Color; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; import org.newdawn.slick.Image; import org.newdawn.slick.Input; import org.newdawn.slick.SlickException; import org.newdawn.slick.gui.TextField; import java.io.FileInputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.net.InetSocketAddress; import java.net.SocketException; import java.util.ArrayList; import java.util.Random; import java.awt.Point; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.UnknownHostException; import java.util.Enumeration; import java.util.LinkedList; import org.newdawn.slick.Sound; public class Game extends BasicGame < public static GameContainer container; static Input input; public static int mouseX, mouseY; static final int MENUSTATE = 0, GAMEPLAYSTATE = 1, MULTIPLAYERMENUSTATE = 2, MULTIPLAYERGAMEPLAYSTATE = 3, MULTIPLAYERGAMEOVERSTATE = 4, LEADERBOARDSTATE = 5, PAUSESTATE = 6, GAMEOVERSTATE = 7; static int state = MENUSTATE; static boolean canCreateConnection = true; static boolean paused = false; public static Button leaderboardButton; public static Button quitButton; public static Button playButton; public static Button multiplayerButton; public static Button menuButton; public static Button resumeButton; public static Button retryButton; public static Button serverButton; public static Button showMultiplayerScoresButton; static GameFont bigFont; static GameFont playFont; static GameFont replayFont; static GameFont leaderboardFont; static GameFont escFont; static GameFont multiplayerFont; static GameFont smallFont; static Image titleImage; static Image youLostImage; static Image[] ghosts = new Image[4]; static ScoreManager Score; static LinkedListbulletList = new LinkedList<>(); static ArrayList enemyList = new ArrayList<>(); static Ammo[] ammos = new Ammo[10]; static Player player; static int bulletCount = 0, enemyCount = 0, ammosCount = 0; static final int START_DELAY = 500, AMMOS_DELAY = 10000, NEW_DIFFICULTY_DELAY = 15000, BULLET_DELAY = 200; static int ENEMY_DELAY = 500; static int startDelay = START_DELAY; static int canSpawnEnemy = ENEMY_DELAY; static int canSpawnAmmo = AMMOS_DELAY; static int increaseDifficulty = NEW_DIFFICULTY_DELAY; static int canFire = 0; static Random enemyPositionX = new Random(); static Random enemyPositionY = new Random(); static GameFont IPFont; static GameFont DestinationPortFont; static GameFont SourcePortFont; static TextField IPTextField, DestinationPortTextField, SourcePortTextField; static String IP; static int SourcePort, DestinationPort; static boolean opponentFired = false; static Opponent opponent; static ArrayList opponentBulletList = new ArrayList<>(); static int oppBulletCount = 0; static Point opponentCoordinates = new Point(Window.HALF_WIDTH, Window.HALF_HEIGHT); static Point opponentMouseCoordinates = new Point(); static int opponentScreenHeight = 0, opponentScreenWidth = 0; public static Sound openingSound; public static Sound shootSound; static Connection connection; static InetSocketAddress address; static String infoString = ""; static String winnerString = ""; public static int players = 0; public static int multiplayerGameID = 0; static UDPServerThread server; static boolean isServer = false; static UDPSenderThread sender; static UDPReceiverThread receiver; public static String localIP = null; public static void main(String[] args) throws SlickException < try < Enumerationinterfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) < NetworkInterface iface = interfaces.nextElement(); if (iface.isLoopback() || !iface.isUp()) < continue; >Enumeration addresses = iface.getInetAddresses(); while (addresses.hasMoreElements()) < InetAddress address = addresses.nextElement(); localIP = address.getHostAddress(); >> > catch (SocketException e) < throw new RuntimeException(e); >AppGameContainer app = new AppGameContainer(new Game("Pac Man: The Top Down Shooter")); app.setDisplayMode(Window.WIDTH, Window.HEIGHT, true); app.start(); > public Game(String title) < super(title); >/** * Inizializza tutte le variabili del gioco. * @param gc del gioco * @throws SlickException */ @Override public void init(GameContainer gc) throws SlickException < gc.setMaximumLogicUpdateInterval(60); gc.setTargetFrameRate(60); gc.setVSync(true); gc.setAlwaysRender(true); gc.setShowFPS(false); gc.setClearEachFrame(true); gc.setSmoothDeltas(false); gc.setVerbose(true); gc.setMouseCursor("Images/Aim.png", 16, 16); playFont = new GameFont(64); replayFont = new GameFont(64f); leaderboardFont = new GameFont(44f); escFont = new GameFont(44f); multiplayerFont = new GameFont(44f); smallFont = new GameFont(24f); IPFont = new GameFont(54f); DestinationPortFont = new GameFont(44f); SourcePortFont = new GameFont(44f); Score = new ScoreManager(); Score.resetScore(); IPTextField = new TextField(gc, IPFont.getFont(), Window.HALF_WIDTH - 180, Window.HALF_HEIGHT - 200, IPFont.getStringWidth("555555555555555"), 54); IPTextField.setBorderColor(Color.transparent); IPTextField.setMaxLength(15); IPTextField.setCursorVisible(false); SourcePortTextField = new TextField(gc, DestinationPortFont.getFont(), Window.HALF_WIDTH, Window.HALF_HEIGHT - 120, DestinationPortFont.getStringWidth("55555"), 44); SourcePortTextField.setBorderColor(Color.transparent); SourcePortTextField.setMaxLength(5); SourcePortTextField.setCursorVisible(false); DestinationPortTextField = new TextField(gc, SourcePortFont.getFont(), Window.HALF_WIDTH - 40, Window.HALF_HEIGHT - 48, SourcePortFont.getStringWidth("55555"), 44); DestinationPortTextField.setBorderColor(Color.blue); DestinationPortTextField.setMaxLength(5); DestinationPortTextField.setCursorVisible(false); playButton = new Button("PLAY (ENTER)", Window.HALF_WIDTH, Window.HALF_HEIGHT, 64, Color.green); multiplayerButton = new Button("MULTIPLAYER (M)", Window.HALF_WIDTH, Window.HALF_HEIGHT + 64, 44, Color.green); leaderboardButton = new Button("LEADERBOARD (L)", Window.HALF_WIDTH, Window.HALF_HEIGHT + 128, 44, Color.green); quitButton = new Button("QUIT (ESC)", Window.HALF_WIDTH, Window.HEIGHT - Window.HEIGHT/20, 44, Color.red); menuButton = new Button("MENU (ESC)", Window.HALF_WIDTH, Window.HEIGHT - Window.HEIGHT/20, 44, Color.red); resumeButton = new Button("RESUME (R)", Window.HALF_WIDTH, Window.HALF_HEIGHT, 64, optionBlue); retryButton = new Button("RETRY (R)", Window.HALF_WIDTH, Window.HALF_HEIGHT, 64, optionBlue); serverButton = new Button("SERVER", Window.HALF_WIDTH, Window.HALF_HEIGHT + 40, 32, Color.red); showMultiplayerScoresButton = new Button("SHOW MULTIPLAYER HIGHSCORES", Window.HALF_WIDTH, quitButton.getY() - Window.HEIGHT/16, 24, Color.white); player = new Player(); opponent = new Opponent(); for (int i = 0; i < 10; i++) ammos[i] = new Ammo(); try < titleImage = new Image("Images/Title.png"); youLostImage = new Image("Images/GameLost.png"); ghosts[0] = new Image("Images/Clyde.png"); ghosts[1] = new Image("Images/Blinky.png"); ghosts[2] = new Image("Images/Inky.png"); ghosts[3] = new Image("Images/Pinky.png"); openingSound = new Sound("Sounds/openingSound.wav"); shootSound = new Sound("Sounds/pacmanShoot.wav"); ObjectInputStream inStream = new ObjectInputStream(new FileInputStream("pmmtds.scores")); Score = (ScoreManager) inStream.readObject(); >catch (IOException e) < System.out.println("SCORES FILE NOT FOUND"); >catch (ClassNotFoundException e) < System.out.println("SCORES FILE EMPTY"); >catch (SlickException e) < System.out.println("ONE OR MORE IMAGES NOT FOUND"); >Score.resetScore(); > /** * Metodo generico per aggiornare la logica degli oggetti di tutto il gioco * @param gc del gioco * @param delta del gioco * @throws SlickException */ @Override public void update(GameContainer gc, int delta) throws SlickException < input = gc.getInput(); mouseX = input.getMouseX(); mouseY = input.getMouseY(); switch (state) < case MENUSTATE: MenuState.update(gc, input, delta, mouseX, mouseY); break; case GAMEPLAYSTATE: GamePlayState.update(gc, input, delta, mouseX, mouseY); break; case MULTIPLAYERMENUSTATE: MultiplayerMenuState.update(gc, input, delta, mouseX, mouseY); break; case MULTIPLAYERGAMEPLAYSTATE: createConnection(); MultiplayerGamePlayState.update(gc, input, delta, mouseX, mouseY); break; case MULTIPLAYERGAMEOVERSTATE: MultiplayerGameOverState.update(gc, input, delta, mouseX, mouseY); break; case LEADERBOARDSTATE: LeaderBoardState.update(gc, input, delta, mouseX, mouseY); break; case PAUSESTATE: PauseState.update(gc, input, delta, mouseX, mouseY); break; case GAMEOVERSTATE: GameOverState.update(gc, input, delta, mouseX, mouseY); break; >> /** * Metodo generico per aggiornare la logica degli oggetti di tutto il gioco * @param gc del gioco * @param g L'oggetto che si occupa di disergnare su schermo * @throws SlickException */ @Override public void render(GameContainer gc, Graphics g) throws SlickException < switch (state) < case MENUSTATE: MenuState.render(gc, g); break; case GAMEPLAYSTATE: GamePlayState.render(gc, g); break; case MULTIPLAYERMENUSTATE: MultiplayerMenuState.render(gc, g); break; case MULTIPLAYERGAMEPLAYSTATE: MultiplayerGamePlayState.render(gc, g); break; case MULTIPLAYERGAMEOVERSTATE: MultiplayerGameOverState.render(gc, g); break; case LEADERBOARDSTATE: LeaderBoardState.render(gc, g); break; case PAUSESTATE: PauseState.render(gc, g); break; case GAMEOVERSTATE: GameOverState.render(gc, g); break; >> /** * Apre la connessione tra i due giocatori e apre il server che serve ad inviare le posizioni dei nemici. */ private void createConnection() < if (canCreateConnection) < address = new InetSocketAddress(IP, DestinationPort); try < connection = new Connection(); connection.connect(SourcePort, address); connection.start(); >catch (SocketException e) < System.out.println("ERROR: IP, SOURCE PORT or DESTINATION PORT NOT VALID " + e); >int serverPort = 7777; if (isServer) < server = new UDPServerThread(serverPort, 2); server.isRunning(true); server.start(); >try < InetAddress serverAddress; if (isServer) serverAddress = InetAddress.getByName("localhost"); else serverAddress = InetAddress.getByName(IP); sender = new UDPSenderThread(serverAddress, serverPort); sender.start(); receiver = new UDPReceiverThread(sender.getSocket()); receiver.start(); >catch (SocketException e) < System.out.println("Socket Exception"); >catch (UnknownHostException e) < System.out.println("Unknown Host"); >canCreateConnection = false; > > > 

Источник

Оцените статью