0% found this document useful (0 votes)
55 views

Board - Java Import Java - Awt. Import Java - Awt.Event. Import Java - Util.Arraylist

The document contains the source code for a 2D Java game. It includes classes for the game board, coins the player can collect, and the player character. The board class initializes the game window, player, coins and timer. It handles input, updating the player position, coin collection, and repainting the screen. The coin and player classes represent the in-game objects and handle drawing to the screen.

Uploaded by

Solomon Mariel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
55 views

Board - Java Import Java - Awt. Import Java - Awt.Event. Import Java - Util.Arraylist

The document contains the source code for a 2D Java game. It includes classes for the game board, coins the player can collect, and the player character. The board class initializes the game window, player, coins and timer. It handles input, updating the player position, coin collection, and repainting the screen. The coin and player classes represent the in-game objects and handle drawing to the screen.

Uploaded by

Solomon Mariel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

SOURCE/S: COMES FROM 1 SOURCE ONLY

https://github.com/learncodebygaming/java_2d_game/blob/master/Player.java

APP.JAVA

import javax.swing.*;

class App {

private static void initWindow() {


JFrame window = new JFrame("Askies");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Board board = new Board();
window.add(board);
window.addKeyListener(board);
window.setResizable(false);
window.pack();
window.setLocationRelativeTo(null);
window.setVisible(true);
}

public static void main(String[] args) {


SwingUtilities.invokeLater(new Runnable() {
public void run() {
initWindow();
}
});
}
}

—------------------------------------------------------------------------------------------------------------------------------

BOARD.JAVA

import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.*;

public class Board extends JPanel implements ActionListener, KeyListener {

private final int DELAY = 25;


public static final int TILE_SIZE = 50;
public static final int ROWS = 12;
public static final int COLUMNS = 18;
public static final int NUM_COINS = 5;
private static final long serialVersionUID = 490905409104883233L;

private Timer timer;


private Player player;
private ArrayList<Coin> coins;

public Board() {
setPreferredSize(new Dimension(TILE_SIZE * COLUMNS, TILE_SIZE * ROWS));
setBackground(new Color(232, 232, 232));

player = new Player();


coins = populateCoins();

timer = new Timer(DELAY, this);


timer.start();
}

@Override
public void actionPerformed(ActionEvent e) {
player.tick();

collectCoins();

repaint();
}

@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
drawBackground(g);
drawScore(g);
for (Coin coin : coins) {
coin.draw(g, this);
}
player.draw(g, this);

Toolkit.getDefaultToolkit().sync();
}

@Override
public void keyTyped(KeyEvent e) {
}

@Override
public void keyPressed(KeyEvent e) {
player.keyPressed(e);
}

@Override
public void keyReleased(KeyEvent e) {
}

private void drawBackground(Graphics g) {


g.setColor(new Color(214, 214, 214));
for (int row = 0; row < ROWS; row++) {
for (int col = 0; col < COLUMNS; col++) {
if ((row + col) % 2 == 1) {
g.fillRect(
col * TILE_SIZE,
row * TILE_SIZE,
TILE_SIZE,
TILE_SIZE
);
}
}
}
}
private void drawScore(Graphics g) {
String text = "$" + player.getScore();
Graphics2D g2d = (Graphics2D) g;
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);
g2d.setColor(new Color(30, 201, 139));
g2d.setFont(new Font("Lato", Font.BOLD, 25));
FontMetrics metrics = g2d.getFontMetrics(g2d.getFont());
Rectangle rect = new Rectangle(0, TILE_SIZE * (ROWS - 1), TILE_SIZE * COLUMNS,
TILE_SIZE);
int x = rect.x + (rect.width - metrics.stringWidth(text)) / 2;
int y = rect.y + ((rect.height - metrics.getHeight()) / 2) + metrics.getAscent();
g2d.drawString(text, x, y);
}

private ArrayList<Coin> populateCoins() {


ArrayList<Coin> coinList = new ArrayList<>();
Random rand = new Random();

for (int i = 0; i < NUM_COINS; i++) {


int coinX = rand.nextInt(COLUMNS);
int coinY = rand.nextInt(ROWS);
coinList.add(new Coin(coinX, coinY));
}

return coinList;
}

private void collectCoins() {


ArrayList<Coin> collectedCoins = new ArrayList<>();
for (Coin coin : coins) {
if (player.getPos().equals(coin.getPos())) {
player.addScore(100);
collectedCoins.add(coin);
}
}
coins.removeAll(collectedCoins);
}

—------------------------------------------------------------------------------------------------------------------------------------------

COIN.JAVA

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import java.awt.Point;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class Coin {

private BufferedImage image;


private Point pos;

public Coin(int x, int y) {


loadImage();

pos = new Point(x, y);


}

private void loadImage() {


try {
.
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) {


g.drawImage(
image,
pos.x * Board.TILE_SIZE,
pos.y * Board.TILE_SIZE,
observer
);
}

public Point getPos() {


return pos;
}

---------------------------------------------------------------------------------------------------------------------------------------------

PLAYER.JAVA

import java.awt.event.KeyEvent;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.awt.image.ImageObserver;
import java.awt.Point;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class Player {

private BufferedImage image;


private Point pos;
private int score;

public Player() {
loadImage();
pos = new Point(0, 0);
score = 0;
}

private void loadImage() {


try {
image = ImageIO.read(new File("images/player.png"));
} catch (IOException exc) {
System.out.println("Error opening image file: " + exc.getMessage());
}
}

public void draw(Graphics g, ImageObserver observer) {


g.drawImage(
image,
pos.x * Board.TILE_SIZE,
pos.y * Board.TILE_SIZE,
observer
);
}

public void keyPressed(KeyEvent e) {


int key = e.getKeyCode();

if (key == KeyEvent.VK_UP) {
pos.translate(0, -1);
}
if (key == KeyEvent.VK_RIGHT) {
pos.translate(1, 0);
}
if (key == KeyEvent.VK_DOWN) {
pos.translate(0, 1);
}
if (key == KeyEvent.VK_LEFT) {
pos.translate(-1, 0);
}
}

public void tick() {


if (pos.x < 0) {
pos.x = 0;
} else if (pos.x >= Board.COLUMNS) {
pos.x = Board.COLUMNS - 1;
}
if (pos.y < 0) {
pos.y = 0;
} else if (pos.y >= Board.ROWS) {
pos.y = Board.ROWS - 1;
}
}

public String getScore() {


return String.valueOf(score);
}

public void addScore(int amount) {


score += amount;
}

public Point getPos() {


return pos;
}

You might also like