How To Set Background For A 2d Game On Java
By Gaming
Learn how to program
by playing video games.
How to make a Video Game in Java (second Basics)
February 4, 2021
This project will get you making your get-go game in Java! Accept my starter code (I explicate how it works) and build your own game! Whether your a beginner or intermediate developer, I layout some ideas for you on what to build adjacent to progress your skills. This is a bully projection for all Java students, and might fifty-fifty expect good on that portfolio for your resume. Take fun developing your commencement video game!
Links
Take hold of this starter code on GitHub: https://github.com/learncodebygaming/java_2d_game
Need help getting setup for Java evolution? https://world wide web.youtube.com/sentry?v=U3UV8c8TFG4
Missed the Joy of Coding second Graphics projection? https://world wide web.youtube.com/watch?five=IyBsWymfqms
Recommended Java second Game resource: https://zetcode.com/javagames/
What'south upwardly guys? Today I wanna testify you how to make a video game in Java. If you lot're in that beginner-to-intermediate range of learning how to program, and you lot're looking for a projection that isn't super boring, you're in the right place. Or even if you need a project to add to your resume: this is something that'southward really visual, that tin be actually impressive looking.
This is an active tutorial. I've designed this project specifically for you to write your own code, and to make a video game that'southward all your own.
We'll be making a 2nd game, using the Java Swing library, and this projection builds off of the work we did in the Bob Ross "Joy of Coding" video. And then if you become really confused every bit I start to go through this, or if you need some more practice with second graphics, then yous should go back and do that project outset. And that should give y'all everything yous need to exist ready for this ane.
My idea for this project was: at that place'southward certain things in developing a game that are just kinda hard, only they're unavoidable. And I don't desire to overwhelm you with things yous might not be ready for nevertheless, that perhaps are interim as a barrier to you having fun with code. So I idea I'd start you off with like a template projection. But a real simple game that gets you passed some of those initial hurdles, and so yous can get to the fun parts.
Now I'grand not going to do a full code-along this fourth dimension, but I want to get y'all familiar with the codebase y'all'll be working with. So what I call back we'll do is: in the first half of this video I want to testify you how I built up this code, So that you can feel comfortable with it even if you don't understand what every line does.
Then in the 2nd half I want to give you a agglomeration of ideas and direction for unlike ways you tin build out your game. Sort of similar trivial homework projects that can all add together up to a game that's uniquely yours. And I'one thousand going to exist breaking downwardly those ideas from easiest to hardest, then you can properly progress your skills equally y'all work on your game.
So if you're ready, the offset matter you'll desire to practise is: download this projection off of Github, run information technology once to brand sure it'due south working, and then come back hither and we'll talk through the code. Yous can either clone it, if yous're familiar with Git, or you tin just download the .Goose egg file.
App.coffee
import javax.swing.*; course App { private static void initWindow() { // create a window frame and set the title in the toolbar JFrame window = new JFrame("Tin't Stop, Won't End, GameStop"); // when we shut the window, stop the app window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // create the jpanel to draw on. // this also initializes the game loop Board board = new Lath(); // add the jpanel to the window window.add(board); // laissez passer keyboard inputs to the jpanel window.addKeyListener(board); // don't allow the user to resize the window window.setResizable(false); // fit the window size around the components (just our jpanel). // pack() should be called subsequently setResizable() to avoid problems on some platforms window.pack(); // open up window in the center of the screen window.setLocationRelativeTo(aught); // display the window window.setVisible(true); } public static void main(String[] args) { // invokeLater() is used here to prevent our graphics processing from // blocking the GUI. https://stackoverflow.com/a/22534931/4655368 // this is a lot of boilerplate code that you shouldn't be too concerned well-nigh. // just know that when primary runs it will phone call initWindow() once. SwingUtilities.invokeLater(new Runnable() { public void run() { initWindow(); } }); } }
Board.java
import java.awt.*; import java.awt.issue.*; import java.util.ArrayList; import coffee.util.Random; import javax.swing.*; public grade Board extends JPanel implements ActionListener, KeyListener { // controls the filibuster between each tick in ms individual final int DELAY = 25; // controls the size of the board public static final int TILE_SIZE = 50; public static final int ROWS = 12; public static final int COLUMNS = 18; // controls how many coins appear on the board public static final int NUM_COINS = v; // suppress serialization warning individual static concluding long serialVersionUID = 490905409104883233L; // go on a reference to the timer object that triggers actionPerformed() in // case we need access to it in some other method private Timer timer; // objects that announced on the game board private Thespian thespian; private ArrayList coins; public Board() { // set the game board size setPreferredSize(new Dimension(TILE_SIZE * COLUMNS, TILE_SIZE * ROWS)); // set the game lath background color setBackground(new Colour(232, 232, 232)); // initialize the game country actor = new Player(); coins = populateCoins(); // this timer will call the actionPerformed() method every DELAY ms timer = new Timer(Delay, this); timer.start(); } @Override public void actionPerformed(ActionEvent e) { // this method is called by the timer every DELAY ms. // use this space to update the land of your game or animation // before the graphics are redrawn. // preclude the role player from disappearing off the lath player.tick(); // give the player points for collecting coins collectCoins(); // calling repaint() will trigger paintComponent() to run once again, // which will refresh/redraw the graphics. repaint(); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); // when calling g.drawImage() nosotros can employ "this" for the ImageObserver // because Component implements the ImageObserver interface, and JPanel // extends from Component. So "this" Lath instance, every bit a Component, tin // react to imageUpdate() events triggered by g.drawImage() // draw our graphics. drawBackground(g); drawScore(g); for (Coin coin : coins) { coin.draw(g, this); } player.depict(1000, this); // this smooths out animations on some systems Toolkit.getDefaultToolkit().sync(); } @Override public void keyTyped(KeyEvent e) { // this is not used but must be defined as part of the KeyListener interface } @Override public void keyPressed(KeyEvent e) { // react to key down events player.keyPressed(e); } @Override public void keyReleased(KeyEvent due east) { // react to key up events } private void drawBackground(Graphics g) { // draw a checky background g.setColor(new Color(214, 214, 214)); for (int row = 0; row < ROWS; row++) { for (int col = 0; col < COLUMNS; col++) { // only color every other tile if ((row + col) % 2 == 1) { // draw a square tile at the electric current row/column position g.fillRect( col * TILE_SIZE, row * TILE_SIZE, TILE_SIZE, TILE_SIZE ); } } } } individual void drawScore(Graphics chiliad) { // set the text to be displayed String text = "$" + player.getScore(); // we need to cast the Graphics to Graphics2D to draw nicer text Graphics2D g2d = (Graphics2D) yard; g2d.setRenderingHint( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); g2d.setRenderingHint( RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); g2d.setRenderingHint( RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); // set the text color and font g2d.setColor(new Color(30, 201, 139)); g2d.setFont(new Font("Lato", Font.Assuming, 25)); // draw the score in the bottom center of the screen // https://stackoverflow.com/a/27740330/4655368 FontMetrics metrics = g2d.getFontMetrics(g2d.getFont()); // the text will be contained within this rectangle. // here I've sized it to be the entire lesser row of board tiles Rectangle rect = new Rectangle(0, TILE_SIZE * (ROWS - 1), TILE_SIZE * COLUMNS, TILE_SIZE); // determine the x coordinate for the text int x = rect.x + (rect.width - metrics.stringWidth(text)) / 2; // determine the y coordinate for the text // (note we add together the rise, as in java 2nd 0 is peak of the screen) int y = rect.y + ((rect.height - metrics.getHeight()) / 2) + metrics.getAscent(); // draw the string g2d.drawString(text, x, y); } private ArrayList populateCoins() { ArrayList coinList = new ArrayList<>(); Random rand = new Random(); // create the given number of coins in random positions on the board. // note that at that place is not check here to preclude two coins from occupying the aforementioned // spot, nor to prevent coins from spawning in the same spot equally the player for (int i = 0; i < NUM_COINS; i++) { int coinX = rand.nextInt(COLUMNS); int coinY = rand.nextInt(ROWS); coinList.add(new Coin(coinX, coinY)); } render coinList; } private void collectCoins() { // let player to pickup coins ArrayList collectedCoins = new ArrayList<>(); for (Coin money : coins) { // if the role player is on the same tile equally a coin, collect it if (player.getPos().equals(coin.getPos())) { // give the histrion some points for picking this up player.addScore(100); collectedCoins.add(coin); } } // remove collected coins from the board coins.removeAll(collectedCoins); } }
Role player.coffee
import java.awt.result.KeyEvent; import java.awt.Graphics; import coffee.awt.image.BufferedImage; import coffee.awt.paradigm.ImageObserver; import java.awt.Point; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; public class Actor { // image that represents the actor's position on the board individual BufferedImage image; // electric current position of the player on the board grid private Point pos; // keep track of the player's score private int score; public Player() { // load the assets loadImage(); // initialize the state pos = new Point(0, 0); score = 0; } private void loadImage() { try { // you lot can use simply the filename if the image file is in your // project folder, otherwise you demand to provide the file path. image = ImageIO.read(new File("images/role player.png")); } take hold of (IOException exc) { System.out.println("Error opening epitome file: " + exc.getMessage()); } } public void depict(Graphics thousand, ImageObserver observer) { // with the Point course, note that pos.getX() returns a double, but // pos.x reliably returns an int. https://stackoverflow.com/a/30220114/4655368 // this is too where we translate lath grid position into a sheet pixel // position by multiplying past the tile size. thousand.drawImage( prototype, pos.ten * Lath.TILE_SIZE, pos.y * Board.TILE_SIZE, observer ); } public void keyPressed(KeyEvent east) { // every keyboard get has a certain lawmaking. get the value of that lawmaking from the // keyboard event so that we can compare information technology to KeyEvent constants int key = e.getKeyCode(); // depending on which arrow key was pressed, we're going to movement the player past // ane whole tile for this input if (primal == KeyEvent.VK_UP) { pos.translate(0, -ane); } if (cardinal == KeyEvent.VK_RIGHT) { pos.translate(i, 0); } if (primal == KeyEvent.VK_DOWN) { pos.interpret(0, i); } if (fundamental == KeyEvent.VK_LEFT) { pos.interpret(-1, 0); } } public void tick() { // this gets called once every tick, before the repainting process happens. // so we tin do anything needed in here to update the state of the player. // prevent the player from moving off the border of the board sideways if (pos.x < 0) { pos.10 = 0; } else if (pos.x >= Lath.COLUMNS) { pos.x = Board.COLUMNS - i; } // prevent the player from moving off the border of the board vertically if (pos.y < 0) { pos.y = 0; } else if (pos.y >= Board.ROWS) { pos.y = Board.ROWS - 1; } } public String getScore() { render String.valueOf(score); } public void addScore(int amount) { score += amount; } public Bespeak getPos() { render pos; } }
Coin.java
import java.awt.Graphics; import java.awt.image.BufferedImage; import coffee.awt.epitome.ImageObserver; import java.awt.Point; import coffee.io.File; import java.io.IOException; import javax.imageio.ImageIO; public course Coin { // epitome that represents the coin's position on the board private BufferedImage image; // current position of the coin on the lath grid private Point pos; public Coin(int 10, int y) { // load the avails loadImage(); // initialize the country pos = new Point(10, y); } private void loadImage() { endeavor { // you can use just the filename if the paradigm file is in your // projection binder, otherwise you need to provide the file path. image = ImageIO.read(new File("images/coin.png")); } catch (IOException exc) { System.out.println("Error opening image file: " + exc.getMessage()); } } public void draw(Graphics g, ImageObserver observer) { // with the Point class, note that pos.getX() returns a double, only // pos.ten reliably returns an int. https://stackoverflow.com/a/30220114/4655368 // this is likewise where we translate lath grid position into a canvas pixel // position by multiplying by the tile size. thousand.drawImage( image, pos.ten * Board.TILE_SIZE, pos.y * Board.TILE_SIZE, observer ); } public Point getPos() { return pos; } }
Now allow's talk virtually some of the things you tin can exercise with this starter code, to build out your own game. You're not meant to do all of these. Just pick and choose things you like or want to endeavor. And if you have whatsoever ideas that aren't on these lists, definitely just go for it.
Beginner
- Change the colors that are being used.
- Change the image files that are being used.
- Change how many points you get per coin.
- Make instance or course variables to control hardcoded values similar the ones just mentioned.
- Utilise WASD instead of arrows for movement.
- Change the dimensions of the game board.
- Brand a new coin appear whenever the player picks one upwards.
- Change the tile size.
- Remember to update your epitome files, or scale the images.
Intermediate
- Make coins disappear afterwards some time.
- Past ticks, or using a divide timer, or later on the player has moved and so many squares.
- Make more than coins appear at random intervals.
- Replace the checkered groundwork with an image.
- Role player and Coin share a lot of commonalities. Create a parent course that both of these classes extend from to reduce code duplication.
- Make a special coin that looks dissimilar and is worth more than points.
- End or restart the game when all coins are collected, or when a certain score is reached.
- Decide what winning means, then redraw the whole canvas with a celebration graphic when you win the game.
- Add together a game clock.
- Could count up or down.
- Could supercede the score or be in add-on to the score.
- Brandish it like the score.
- Keep track of high scores.
- In a single play session.
- Or across all sessions by reading/writing to a file.
- Permit the role player to wrap around the edges of the board.
Advanced
- Add together obstacles to cake player motion.
- Add an object type that reduces your score when touched. Or maybe it ends the game.
- Brand an object blazon that moves around on its ain. Could be similar the ghosts from pacman.
- Add sounds.
- When a player moves, or picks up coins.
- A constant sound track.
- A sound that plays when yous offset open up the game.
- Implement delta movements to merely permit players to move one tile per tick.
- Can play around with the tick rate when developing this.
- React to both pressed and released.
- Tin enable diagonal movements.
- Fixes the result caused by belongings down a key, and makes for a more responsive experience.
- Make the total game area larger than the portion of that grid we see in the game window.
- So maybe the viewport moves as the player approaches an edge.
- Or possibly the player stays in the middle and the whole viewport moves with the histrion whenever the player moves.
- Think about other keyboard keys that might perform some other activity.
- Tin can be every bit simple equally changing some colors in the game.
- Or possibly you've got health potions to restore histrion health.
- Add more scoreboard/HUD elements.
- Maybe move this off of the game board itself, to some designated area on the canvas. I recommend still using just the single JPanel if y'all want to practice this.
- Eliminate the grid concept altogether and use pixel positions instead.
Good
To dive even deeper into developing your Coffee 2d game, I recommend checking out this series of tutorials for guidance and inspiration: https://zetcode.com/javagames/
Alright so proficient luck on edifice what's probably your first computer game! Hopefully you lot've got a lot of ideas, and some sense of how you might accomplish them. I actually tried to strip this projection downwardly, and arrive equally like shooting fish in a barrel for you lot to build off of as possible.
Once you've finished your projection, and y'all're wondering what'due south next? Offset of all I'm super proud of you: you've achieved something most people volition only ever dream of. And the next pace would exist to just brand some other game, only push yourself to be a fiddling more ambitious this 2nd time around.
And so later on that y'all're ready to graduate to a proper game development library. I've never used any Coffee game development libraries, so I tin can't really give you whatsoever recommendations there. But permit me know if you finish up finding ane you like, and possibly I can bank check that out in a future video.
My proper name is Ben and I assistance people learn how to lawmaking by gaming. I believe in the ability of project-based learning to foster a deep understanding and joy in the craft of software evolution. On this site I share programming tutorials, coding-game reviews, and project ideas for you to explore.
How To Set Background For A 2d Game On Java,
Source: https://learncodebygaming.com/blog/how-to-make-a-video-game-in-java-2d-basics
Posted by: mclarenquity1983.blogspot.com
0 Response to "How To Set Background For A 2d Game On Java"
Post a Comment