I'm new to Java and trying build a brick breaker game with Java. I've searched many instructions from online to build this. I have a problem here that I can't find the solution online anymore.
When I run my code, it works fine, but when the ball hit the top of the frame, it just go through it and never come back. I want let the ball to hit the top and reflect from it. Can anyone help me to solve this problem. I've wrote three classes. Please let me know anything could be helpful!
This is main class:
package brickBreaker;
import javax.swing.JFrame;
class Main {
public static void main(String[] args) {
JFrame obj = new JFrame();
Gameplay gamePlay = new Gameplay();
obj.setBounds(10, 10, 700, 600);
obj.setTitle("Breakout Ball");
obj.setResizable(false);
obj.setVisible(true);
obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
obj.add(gamePlay);
}
}
This is Gameplay class:
package brickBreaker;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.Timer;
import javax.swing.JPanel;
public class Gameplay extends JPanel implements KeyListener, ActionListener{
private boolean play = false;
private int score = 0;
private int totalBricks = 21;
private Timer timer;
private int delay = 8;
private int playerX = 310;
private int ballposX = 120;
private int ballposY = 350;
private int ballXdir = -1;
private int ballYdir = -2;
private MapGenerator map;
public Gameplay() {
map = new MapGenerator(3, 7);
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
timer = new Timer(delay, this);
timer.start();
}
public void paint(Graphics g) {
//background
g.setColor(Color.black);
g.fillRect(1, 1, 692, 592);
// drawing map
map.draw((Graphics2D) g);
// scores
g.setColor(Color.white);
g.setFont(new Font("serif", Font.BOLD, 25));
g.drawString(""+score, 590, 30);
// borders
g.setColor(Color.yellow);
g.fillRect(0, 0, 3, 592);
g.fillRect(0 , 0, 692, 3);
g.fillRect(692, 0, 3, 592);
// the paddle
g.setColor(Color.green);
g.fillRect(playerX, 550, 100, 8);
// the ball
g.setColor(Color.yellow);
g.fillOval(ballposX, ballposY, 20, 20);
if (ballposY > 570) {
play = false;
ballXdir = 0;
ballYdir = 0;
g.setColor(Color.red);
g.setFont(new Font("serif", Font.BOLD, 30));
g.drawString("Game Over, Scores: ", 190, 300);
g.setFont(new Font("serif", Font.BOLD, 20));
g.drawString("Press Enter to Restart ", 230, 350);
}
if (totalBricks <= 0) {
play = false;
ballXdir = 0;
ballYdir = 0;
g.setColor(Color.red);
g.setFont(new Font("serif", Font.BOLD, 30));
g.drawString("You Won, Scores: ", 190, 300);
g.setFont(new Font("serif", Font.BOLD, 20));
g.drawString("Press Enter to Restart ", 230, 350);
}
g.dispose();
}
#Override
public void actionPerformed (ActionEvent e) {
timer.start();
if (play) {
if (new Rectangle(ballposX, ballposY, 20, 20).intersects(new Rectangle(playerX, 550, 100, 8))) {
ballYdir = -ballYdir;
}
A: for (int i = 0; i <map.map.length; i++) {
for (int j = 0; j < map.map[0].length; j++) {
if (map.map[i][j] > 0) {
int brickX = j * map.brickWidth + 80;
int brickY = i * map.brickHeight + 50;
int brickWidth = map.brickWidth;
int brickHeight = map.brickHeight;
Rectangle rect = new Rectangle(brickX, brickY, brickWidth, brickHeight);
Rectangle ballRect = new Rectangle(ballposX, ballposY, 20, 20);
Rectangle brickRect = rect;
if (ballRect.intersects(brickRect)) {
map.setBrickValue(0, i, j);
totalBricks--;
score += 10;
if (ballposX + 19 <= brickRect.x || ballposX + 1 >= brickRect.x + brickRect.width) {
ballXdir = -ballXdir;
} else {
ballYdir = -ballYdir;
}
break A;
}
}
}
}
ballposX += ballXdir;
ballposY += ballYdir;
if (ballposX < 0) {
ballXdir = -ballXdir;
}
if (ballposY < 0) {
ballXdir = -ballYdir;
}
if (ballposX > 670) {
ballXdir = -ballXdir;
}
}
repaint();
}
#Override
public void keyReleased (KeyEvent e) {}
#Override
public void keyTyped (KeyEvent e) {}
#Override
public void keyPressed (KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_RIGHT) {
if (playerX >= 600) {
playerX = 600;
} else {
moveRight();
}
}
if(e.getKeyCode() == KeyEvent.VK_LEFT) {
if (playerX < 10) {
playerX = 10;
} else {
moveLeft();
}
}
if(e.getKeyCode() == KeyEvent.VK_ENTER) {
if (!play) {
play = true;
ballposX = 120;
ballposY = 350;
ballXdir = -1;
ballYdir = -2;
playerX = 310;
score = 0;
totalBricks = 21;
map = new MapGenerator (3, 7);
repaint();
}
}
}
public void moveRight() {
play = true;
playerX += 20;
}
public void moveLeft() {
play = true;
playerX -= 20;
}
}
This is MapGenerator class:
package brickBreaker;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
public class MapGenerator {
public int map[][];
public int brickWidth;
public int brickHeight;
public MapGenerator(int row, int col) {
map = new int [row][col];
for (int i = 0; i < map.length; i++) {
for (int j = 0; j < map[0].length; j++) {
map[i][j] = 1;
}
}
brickWidth = 540/col;
brickHeight = 150/row;
}
public void draw(Graphics2D g) {
for (int i = 0; i < map.length; i++) {
for (int j = 0; j < map[0].length; j++) {
if (map[i][j] > 0) {
g.setColor(Color.white);
g.fillRect(j * brickWidth + 80, i * brickHeight + 50, brickWidth,
brickHeight);
g.setStroke(new BasicStroke(3));
g.setColor(Color.black);
g.drawRect(j * brickWidth + 80, i * brickHeight + 50, brickWidth,
brickHeight);
}
}
}
}
public void setBrickValue(int value, int row, int col) {
map[row][col] = value;
}
}
At lines 140-142, you have
if (ballposY < 0) {
ballXdir = -ballYdir;
}
You are reversing the ballXdir rather than the ballYdir when the ball hits the top. Replace with
if (ballposY < 0) {
ballYdir = -ballYdir;
}
and it will bounce off the top correctly.
Related
I have a Robot method declared in the gameplay class, I have declared the variables but It will not excecated the loop properly, I assume I mis stepped somewhere in the calling of the variables or method. I have it set to pull the X position of the ball and move towards that by using the robot class to press a key, which works just fine on the keyboard (i.e. I can press the keys specified and the paddle moves)
I tried to re declare the variables in the method, the coordinates of both the paddle and ball works, the game functions, but the robot method is not executing at all. I tried to create a new instance of the method in the main method, but nothing changes, I tried to use the "this." function instead of declaring a new object in the method, but it just throws errors. Sorry about the code, I am fairly new to Java, and I am more experienced with C# and unity as opposed to the terminal and stuff like this. Here is the Gameplay Class.
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import javax.swing.Timer;
import java.awt.Robot;
public class TestGameplay extends JPanel implements KeyListener, ActionListener
{
private boolean play = false;
private int score = 0;
private int totalBricks = 48;
private Timer timer;
private int delay=8;
private int playerX = 310;
public int paddlePos;
private int ballposX = 120;
public int ballX;
private int ballposY = 350;
private int ballXdir = -1;
private int ballYdir = -2;
private MapGenerator map;
public TestGameplay()
{
map = new MapGenerator(4, 12);
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
timer=new Timer(delay,this);
timer.start();
paddlePos = playerX;
ballX = ballposX;
}
public void Robot() throws AWTException {
Robot breaker = new Robot();
int ballPos = ballposX;
if (ballPos > playerX) {
breaker.keyPress(KeyEvent.VK_2);
breaker.delay(100);
breaker.keyRelease(KeyEvent.VK_2);
} else {
breaker.keyPress(KeyEvent.VK_1);
breaker.delay(100);
breaker.keyRelease(KeyEvent.VK_1);
}
}
public void paint(Graphics g)
{
// background
g.setColor(Color.black);
g.fillRect(1, 1, 692, 592);
// drawing map
map.draw((Graphics2D) g);
// borders
g.setColor(Color.yellow);
g.fillRect(0, 0, 3, 592);
g.fillRect(0, 0, 692, 3);
g.fillRect(691, 0, 3, 592);
// the scores
g.setColor(Color.white);
g.setFont(new Font("serif",Font.BOLD, 25));
g.drawString(""+score, 590,30);
// the paddle
g.setColor(Color.green);
g.fillRect(playerX, 550, 100, 8);
// the ball
g.setColor(Color.yellow);
g.fillOval(ballposX, ballposY, 20, 20);
// when you won the game
if(totalBricks <= 0)
{
play = false;
ballXdir = 0;
ballYdir = 0;
g.setColor(Color.RED);
g.setFont(new Font("serif",Font.BOLD, 30));
g.drawString("You Won", 260,300);
g.setColor(Color.RED);
g.setFont(new Font("serif",Font.BOLD, 20));
g.drawString("Press (Enter) to Restart", 230,350);
}
// when you lose the game
if(ballposY > 570)
{
play = false;
ballXdir = 0;
ballYdir = 0;
g.setColor(Color.RED);
g.setFont(new Font("serif",Font.BOLD, 30));
g.drawString("Game Over, Scores: "+score, 190,300);
g.setColor(Color.RED);
g.setFont(new Font("serif",Font.BOLD, 20));
g.drawString("Press (Enter) to Restart", 230,350);
}
g.dispose();
}
public void keyPressed(KeyEvent e)
{
if (e.getKeyCode() == KeyEvent.VK_2)
{
if(playerX >= 600)
{
playerX = 600;
}
else
{
moveRight();
}
}
if (e.getKeyCode() == KeyEvent.VK_1)
{
if(playerX < 10)
{
playerX = 10;
}
else
{
moveLeft();
}
}
if (e.getKeyCode() == KeyEvent.VK_ENTER)
{
if(!play)
{
play = true;
ballposX = 120;
ballposY = 350;
ballXdir = -1;
ballYdir = -2;
playerX = 310;
score = 0;
totalBricks = 21;
map = new MapGenerator(3, 7);
repaint();
}
}
}
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e) {}
public void moveRight()
{
play = true;
playerX+=20;
}
public void moveLeft()
{
play = true;
playerX-=20;
}
public void actionPerformed(ActionEvent e)
{
timer.start();
if(play)
{
if(new Rectangle(ballposX, ballposY, 20, 20).intersects(new Rectangle(playerX, 550, 30, 8)))
{
ballYdir = -ballYdir;
ballXdir = -2;
}
else if(new Rectangle(ballposX, ballposY, 20, 20).intersects(new Rectangle(playerX + 70, 550, 30, 8)))
{
ballYdir = -ballYdir;
ballXdir = ballXdir + 1;
}
else if(new Rectangle(ballposX, ballposY, 20, 20).intersects(new Rectangle(playerX + 30, 550, 40, 8)))
{
ballYdir = -ballYdir;
}
// check map collision with the ball
A: for(int i = 0; i<map.map.length; i++)
{
for(int j =0; j<map.map[0].length; j++)
{
if(map.map[i][j] > 0)
{
//scores++;
int brickX = j * map.brickWidth + 80;
int brickY = i * map.brickHeight + 50;
int brickWidth = map.brickWidth;
int brickHeight = map.brickHeight;
Rectangle rect = new Rectangle(brickX, brickY, brickWidth, brickHeight);
Rectangle ballRect = new Rectangle(ballposX, ballposY, 20, 20);
Rectangle brickRect = rect;
if(ballRect.intersects(brickRect))
{
map.setBrickValue(0, i, j);
score+=5;
totalBricks--;
// when ball hit right or left of brick
if(ballposX + 19 <= brickRect.x || ballposX + 1 >= brickRect.x + brickRect.width)
{
ballXdir = -ballXdir;
}
// when ball hits top or bottom of brick
else
{
ballYdir = -ballYdir;
}
break A;
}
}
}
}
ballposX += ballXdir;
ballposY += ballYdir;
if(ballposX < 0)
{
ballXdir = -ballXdir;
}
if(ballposY < 0)
{
ballYdir = -ballYdir;
}
if(ballposX > 670)
{
ballXdir = -ballXdir;
}
repaint();
}
}
}
Here is the Main method
import java.awt.*;
import java.awt.event.KeyEvent;
import java.io.IOException;
import javax.swing.JFrame;
public class Main {
public static void main(String[] args) throws AWTException {
JFrame obj=new JFrame();
TestGameplay gamePlay = new TestGameplay();
Robot robot
obj.setBounds(10, 10, 700, 600);
obj.setTitle("Breakout Ball");
obj.setResizable(false);
obj.setVisible(true);
obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
obj.add(gamePlay);
obj.setVisible(true);
}
}
There is the map generator class as well, but It it not relevant to this I think
** I pulled the base game from Git but had to tweak some settings
I want to add a simple menu to my Java Snake game which will contain three buttons (New Game, Difficulty and Quit). I have created a class for the menu and a class for the mouse input. I have used an enum to store the states of the game (MAIN_MENU, DIFFICULTY_MENU and GAME) and a variable called STATE which stores the current state.
The main problem is that although the state of the game is changed when the "New Game" button is pressed the game doesn't start. I have tried to add game state checks inside the methods that are involved in setting the gameplay and I have also tried calling those methods from the mousePressed() method of the MouseInput class but none of these worked.
I would greatly appreciate if you could give me some tips on how to solve this issue.
Here's my code:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class SnakeGame extends JFrame{
public SnakeGame() {
initGUI();
}
public void initGUI() {
add(new GamePlay());
setResizable(false);
pack();
setTitle("The Snake");
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
JFrame frame = new SnakeGame();
frame.setVisible(true);
});
}
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class GamePlay extends JPanel implements ActionListener {
public static final int HEIGHT = 600;
public static final int WIDTH = 600;
private final int TOTAL_DOTS = 3600;
private final int DOT_SIZE = 10;
private final int RAND_POSITION = 29;
//private final int DELAY = 140;
private final int[] X = new int[TOTAL_DOTS];// the dots on X axis
private final int[] Y = new int[TOTAL_DOTS];//the dots on Y axis
private int dots;
private int apple_X;
private int apple_Y;
private int score = 0;
private int DELAY = 140;
private boolean leftDirection = false;
private boolean rightDirection = true;
private boolean upDirection = false;
private boolean downDirection = false;
private boolean inGame = true;
private Timer timer;
private Image bodyPart;
private Image snakeHead;
private Image apple;
private Menu menu;
public static GameState STATE = GameState.MAIN_MENU;//current game state(it changes when menu buttons are pressed)
public static enum GameState{
MAIN_MENU,
DIFFICULTY_MENU,
GAME
}
public GamePlay() {
setGamePlay();
}
public void setGamePlay() {
addKeyListener(new KeyboardEvent());
addMouseListener(new MouseInput());
setBackground(Color.BLACK);
setFocusable(true);
setPreferredSize(new Dimension(WIDTH, HEIGHT));
if(STATE == GameState.GAME) {
loadImages();
startGame();
}
}
private void loadImages() {
ImageIcon img2 = new ImageIcon("src/images/dot.png");
bodyPart = img2.getImage();
ImageIcon img1 = new ImageIcon("src/images/head.png");
snakeHead = img1.getImage();
ImageIcon img3 = new ImageIcon("src/images/apple.png");
apple = img3.getImage();
}
//setting the starting snake length and the apple position on the board
public void startGame() {
dots = 3;
for(int i = 0 ; i < dots; i++) {
X[i] = 50 - i * 10;
Y[i] = 50;
}
locateApple();
timer = new Timer(DELAY,this);
//timer.start();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if(STATE == GameState.GAME) {
draw(g);
}else if(STATE == GameState.MAIN_MENU) {
new Menu().displayMainMenu(g);
}else if(STATE == GameState.DIFFICULTY_MENU) {
new Menu().displayDifficultyMenu(g);
}
System.out.println("End of paint component method");
}
public void draw(Graphics g) {
scoreDisplay(g);
if(inGame) {
g.drawImage(apple, apple_X, apple_Y,this);
for(int i = 0 ; i < dots; i++) {
if(i == 0) {
g.drawImage(snakeHead,X[i], Y[i], this);
}else {
g.drawImage(bodyPart, X[i], Y[i], this);
}
}
Toolkit.getDefaultToolkit().sync();
}else {
gameOver(g);
}
}
public void gameOver(Graphics g) {
String msg = "Game Over!";
String msg2 = "Score: " + score + " " + "Length: " + dots;
Font small = new Font("Comic Sans",Font.BOLD,14 );
FontMetrics messageSize = getFontMetrics(small);
g.setColor(Color.WHITE);
g.setFont(small);
g.drawString(msg, (WIDTH - messageSize.stringWidth(msg)) / 2, HEIGHT / 2);
g.drawString(msg2, (WIDTH - messageSize.stringWidth(msg2)) / 2, (HEIGHT / 2) + 20);
restartMessageDisplay(g);
}
public void scoreDisplay(Graphics g) {
String gameScore = "Score: " + score;
String snakeLength = "Snake length: " + dots;
Font small = new Font("Arial", Font.BOLD, 14);
g.setColor(Color.WHITE);
g.setFont(small);
g.drawString(gameScore,480, 20);
g.drawString(snakeLength, 480, 40);
}
public void restartMessageDisplay(Graphics g) {
String restartMessage = " Press Enter to restart";
Font small = new Font("Arial", Font.BOLD, 14);
FontMetrics metrics = getFontMetrics(small);
g.drawString(restartMessage, (WIDTH - metrics.stringWidth(restartMessage)) / 2, (HEIGHT / 2) + 40);
}
private void checkApple() {
if((X[0] == apple_X) && (Y[0] == apple_Y)) {
dots++;
locateApple();
score += 5;//score update
DELAY -= 5;// speed increase when snake eats the apple
if(DELAY >= 40) {
timer.setDelay(DELAY);
}
}
}
//snake move logic
private void move() {
for(int i = dots; i > 0; i--) {
X[i] = X[(i-1)];
Y[i] = Y[(i-1)];
}
if(leftDirection) {
X[0] -= DOT_SIZE;
}
if(rightDirection) {
X[0] += DOT_SIZE;
}
if(upDirection) {
Y[0] -= DOT_SIZE;
}
if(downDirection) {
Y[0] += DOT_SIZE;
}
}
//checking for collision with the walls or the snake itself
private void checkCollision() {
for(int i = dots; i > 0; i--) {
if((i > 4) && (X[0] == X[i]) && (Y[0] == Y[i])) {
inGame = false;
}
}
if(X[0] < 0) {
inGame = false;
}
if(X[0] > WIDTH) {
inGame = false;
}
if(Y[0] < 0) {
inGame = false;
}
if(Y[0] > HEIGHT) {
inGame = false;
}
if(!inGame) {
timer.stop();
}
}
//setting apple position on the board
public void locateApple() {
int random = (int) (Math.random() * RAND_POSITION);
apple_X = random * DOT_SIZE;
random = (int) (Math.random()* RAND_POSITION);
apple_Y = random * DOT_SIZE;
}
#Override
public void actionPerformed(ActionEvent e) {
if(inGame) {
checkApple();
checkCollision();
move();
}
repaint();
}
private class KeyboardEvent extends KeyAdapter {
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if((keyCode == KeyEvent.VK_LEFT) && (!rightDirection)) {
leftDirection = true;
upDirection = false;
downDirection = false;
}
if((keyCode == KeyEvent.VK_RIGHT) && (!leftDirection)) {
rightDirection = true;
upDirection = false;
downDirection = false;
}
if((keyCode == KeyEvent.VK_UP) && (!downDirection)) {
upDirection = true;
leftDirection = false;
rightDirection = false;
}
if((keyCode == KeyEvent.VK_DOWN) && (!upDirection)) {
downDirection = true;
leftDirection = false;
rightDirection = false;
}
if(keyCode == KeyEvent.VK_PAUSE) {
timer.stop();
}
if(keyCode == KeyEvent.VK_SPACE) {
timer.start();
}
//game restart
if(keyCode == KeyEvent.VK_ENTER) {
if(!inGame) {
inGame = true;
leftDirection = false;
rightDirection = true;
upDirection = false;
downDirection = false;
score = 0;
DELAY = 140;
setGamePlay();
repaint();
}
}
}
}
}
import java.awt.*;
import javax.swing.*;
public class Menu {
public Rectangle newGameButton;
public Rectangle gameDifficultyButton;
public Rectangle quitButton;
public Rectangle easyDifficultyButton;
public Rectangle mediumDifficultyButton;
public Rectangle hardDifficultyButton;
public Button button1;
public Menu() {
int buttonWidth = 150;
int buttonHeight = 50;
newGameButton = new Rectangle((GamePlay.WIDTH - buttonWidth) / 2, (GamePlay.HEIGHT / 2) - 50, buttonWidth, buttonHeight);
gameDifficultyButton = new Rectangle((GamePlay.WIDTH - buttonWidth) / 2, (GamePlay.HEIGHT / 2) + 50, buttonWidth, buttonHeight);
quitButton = new Rectangle((GamePlay.WIDTH - buttonWidth) / 2, (GamePlay.HEIGHT / 2) + 150, buttonWidth, buttonHeight);
easyDifficultyButton = new Rectangle((GamePlay.WIDTH - buttonWidth) / 2, (GamePlay.HEIGHT / 2) - 50, buttonWidth, buttonHeight);
mediumDifficultyButton = new Rectangle((GamePlay.WIDTH - buttonWidth) / 2, (GamePlay.HEIGHT / 2) + 50, buttonWidth, buttonHeight);
hardDifficultyButton = new Rectangle((GamePlay.WIDTH - buttonWidth) / 2, (GamePlay.HEIGHT / 2) + 150, buttonWidth, buttonHeight);
}
public void displayMainMenu(Graphics g) {
Graphics2D buttonGraphics =(Graphics2D) g;
String title = "THE SNAKE GAME";
Font font = new Font("Arial", Font.BOLD, 50);
FontMetrics size = g.getFontMetrics(font);
g.setFont(font);
g.setColor(Color.WHITE);
g.drawString(title,(GamePlay.WIDTH-size.stringWidth(title)) / 2, (GamePlay.HEIGHT / 2) - 130);
Font buttonFont = new Font("Arial", Font.BOLD, 28);
g.setFont(buttonFont);
g.drawString("New Game",newGameButton.x + 2, newGameButton.y + 35);
buttonGraphics.draw(newGameButton);
g.drawString("Difficulty",gameDifficultyButton.x + 15,gameDifficultyButton.y + 35);
buttonGraphics.draw(gameDifficultyButton);
g.drawString("Quit", quitButton.x + 45, quitButton.y + 35);
buttonGraphics.draw(quitButton);
}
public void displayDifficultyMenu(Graphics g) {
Graphics2D difficultyMenuGraphics = (Graphics2D) g;
String title = "Difficulty level";
Font difficultyMenuTitleFont = new Font("Arial", Font.BOLD,40);
FontMetrics size = g.getFontMetrics(difficultyMenuTitleFont);
g.setFont(difficultyMenuTitleFont);
g.setColor(Color.WHITE);
g.drawString(title, (GamePlay.WIDTH - size.stringWidth(title)) / 2, (GamePlay.HEIGHT / 2) - 100);
Font difficultyButtonFont = new Font("Arial", Font.BOLD, 28);
g.setFont(difficultyButtonFont);
g.drawString("Easy", easyDifficultyButton.x + 40 , easyDifficultyButton.y + 35);
difficultyMenuGraphics.draw(easyDifficultyButton);
g.drawString("Medium",mediumDifficultyButton.x + 20, mediumDifficultyButton.y + 35);
difficultyMenuGraphics.draw(mediumDifficultyButton);
g.drawString("Hard", hardDifficultyButton.x + 40, hardDifficultyButton.y + 35);
difficultyMenuGraphics.draw(hardDifficultyButton);
}
}
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.lang.Thread.State;
public class MouseInput extends MouseAdapter {
public Rectangle newGameButton;
public Rectangle gameDifficultyButton;
public Rectangle quitButton;
public Rectangle easyDifficultyButton;
public Rectangle mediumDifficultyButton;
public Rectangle hardDifficultyButton;
Graphics g;
public void mousePressed(MouseEvent e) {
int mouseX = e.getX();
int mouseY = e.getY();
//NewGame button
if(mouseX >= (GamePlay.WIDTH - 150) / 2 && mouseX <= ((GamePlay.WIDTH - 150) / 2) + 150) {
if(mouseY >= (GamePlay.HEIGHT / 2) - 50 && mouseY <= (GamePlay.HEIGHT/ 2)) {
GamePlay.STATE = GamePlay.GameState.GAME;
System.out.println(GamePlay.STATE);
}
}
//Difficulty button
if(mouseX >= (GamePlay.WIDTH - 150) / 2 && mouseX <= ((GamePlay.WIDTH - 150)/ 2 ) + 150) {
if(mouseY >= (GamePlay.HEIGHT / 2) + 50 && mouseY <= (GamePlay.HEIGHT/ 2) + 100) {
GamePlay.STATE = GamePlay.STATE.DIFFICULTY_MENU;
System.out.println("Game state = " + GamePlay.STATE)
}
}
//Quit button
if(mouseX >= (GamePlay.WIDTH - 150) / 2 && mouseX <= ((GamePlay.WIDTH - 150)/ 2 ) + 150) {
if(mouseY >= (GamePlay.HEIGHT / 2) + 150 && mouseY <= (GamePlay.HEIGHT/ 2) + 200) {
System.exit(0);
}
}
}
}
Hi im new as a coder and i've been working on this very simple box breaker game that i made with tutorial from YT. Now i've started to try modify it and make it more appealing. Tutorial that i used was pretty good but it didn't tell me how to add current score to end where it says "You won, score: ".
Code:
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.Timer;
import javax.swing.JPanel;
public class Gameplay extends JPanel implements KeyListener,
ActionListener {
private boolean play = false;
private int score = 0;
private int totalBricks = 21;
private Timer timer;
private int delay = 8;
private int playerX = 310;
private int ballposX = 200;
private int ballposY = 350;
private int ballXdir = -1;
private int ballYdir = -2;
private MapGenerator map;
public Gameplay() {
map = new MapGenerator(3, 7);
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
timer = new Timer(delay, this);
timer.start();
}
public void paint(Graphics g) {
// background
g.setColor(Color.black);
g.fillRect(1, 1, 692, 592);
//drawing map
map.draw((Graphics2D)g);
//borders
g.setColor(Color.yellow);
g.fillRect(0, 0, 3, 592);
g.fillRect(0, 0, 692, 3);
g.fillRect(691, 0, 3, 592);
//scores
g.setColor(Color.white);
g.setFont(new Font("serif", Font.BOLD, 25));
g.drawString(""+score, 590, 30);
//the paddel
g.setColor(Color.green);
g.fillRect(playerX, 550, 100, 8);
//the ball
g.setColor(Color.yellow);
g.fillOval(ballposX, ballposY, 20, 20);
if(totalBricks <= 0) {
play = false;
ballXdir = 0;
ballYdir = 0;
g.setColor(Color.red);
g.setFont(new Font("serif", Font.BOLD, 30));
g.drawString("You Won, score: ", 260, 300);
g.setFont(new Font("serif", Font.BOLD, 20));
g.drawString("Press ENTER to restart.", 260, 350);
}
if(ballposY > 570) {
play = false;
ballXdir = 0;
ballYdir = 0;
g.setColor(Color.red);
g.setFont(new Font("serif", Font.BOLD, 30));
g.drawString("Game Over, Score: ", 200, 300);
g.setFont(new Font("serif", Font.BOLD, 20));
g.drawString("Press ENTER to restart.", 230, 350);
}
g.dispose();
}
#Override
public void actionPerformed(ActionEvent e) {
timer.start();
if(play) {
if(new Rectangle(ballposX, ballposY, 20, 20).intersects(new
Rectangle(playerX, 550, 100, 8))) {
ballYdir = -ballYdir;
}
A: for(int i = 0; i<map.map.length; i++) {
for(int j = 0; j<map.map[0].length; j++) {
if(map.map[i][j] > 0) {
int brickX = j* map.brickWidth + 80;
int brickY = i* map.brickHeight + 50;
int brickWidth = map.brickWidth;
int brickHeight = map.brickHeight;
Rectangle rect = new Rectangle(brickX, brickY,
brickWidth, brickHeight);
Rectangle ballRect = new Rectangle(ballposX,
ballposY, 19,19);
Rectangle brickRect = rect;
if(ballRect.intersects(brickRect)) {
map.setBrickValue(0, i, j);
totalBricks--;
score += 5;
if(ballposX + 19 <= brickRect.x && ballposX + 1 >=
brickRect.x + brickRect.width) {
ballXdir = -ballXdir;
} else {
ballYdir = -ballYdir;
}
break A;
}
}
}
}
ballposX += ballXdir;
ballposY += ballYdir;
if(ballposX < 0) {
ballXdir = -ballXdir;
}
if(ballposY < 0) {
ballYdir = -ballYdir;
}
if(ballposX > 670) {
ballXdir = -ballXdir;
}
}
repaint();
}
#Override
public void keyReleased(KeyEvent e) {}
#Override
public void keyTyped(KeyEvent e) {}
#Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_RIGHT) {
if(playerX >=600) {
playerX = 600;
} else {
moveRight();
}
}
if(e.getKeyCode() == KeyEvent.VK_LEFT) {
if(playerX < 10) {
playerX = 10;
} else {
moveLeft();
}
}
if(e.getKeyCode() == KeyEvent.VK_ENTER) {
if(!play) {
play = true;
ballposX = 200;
ballposY = 350;
ballXdir = -1;
ballYdir = -2;
playerX = 310;
score = 0;
totalBricks = 21;
map = new MapGenerator(3, 7);
repaint();
}
}
}
public void moveRight() {
play = true;
playerX+=20;
}
public void moveLeft() {
play = true;
playerX-=20;
}
}
"You Won, score: " + score
in java you can combine strings to make longer strings in this case "You Won, Score: " is a string and when you add the score to it score is converted to a string and is combined with the first part to give you what you want.
https://docs.oracle.com/javase/tutorial/java/data/strings.html
import java.awt.*;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.Timer;
public class Gameplay extends JPanel implements KeyListener, ActionListener {
boolean play = true;
private int score = 0, delay = 8, ballposX = 120, ballposY = 250, ballXdir = -10,
ballYdir = -10, playerX = 310, padXdir = -20, padYdir = -20;
private int padposX = 300, padposY = 50;
Timer timer;
public Gameplay() {
setSize(new Dimension(700, 600));
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
timer = new Timer(delay, this);
timer.start();
}
public void paint(Graphics g) {
// Gameboard size
g.setColor(Color.black);
g.fillRect(1, 1, 700, 600);
// Border of the game
g.setColor(Color.yellow);
g.fillRect(0, 0, 3, 592);
g.fillRect(0, 0, 692, 3);
g.fillRect(692, 0, 3, 592);
// Paddle
g.setColor(Color.green);
g.fillRect(playerX, 500, 100, 8);
// Second Paddle
g.setColor(Color.red);
g.fillRect(padposX, padposY, 100, 8);
// Ball
g.setColor(Color.yellow);
g.fillOval(ballposX, ballposY, 20, 20);
g.dispose();
}
public void actionPerformed(ActionEvent e) {
timer.start();
if (play) {
if (new Rectangle(ballposX, ballposY, 20, 20)
.intersects(new Rectangle(playerX, 500, 100, 8))) {
ballYdir = -ballYdir;
}
if (new Rectangle(ballposX, ballposY, 20, 20)
.intersects(new Rectangle(padposX, padposY, 100, 8))) {
ballYdir = -ballYdir;
}
ballposX += ballXdir;
ballposY += ballYdir;
if (ballposX < 0) {
ballXdir = -ballXdir;
}
if (ballposY < 0) {
ballYdir = -ballYdir;
}
if (ballposY > 560) {
ballYdir = -ballYdir;
}
if (ballposX > 665) {
ballXdir = -ballXdir;
}
repaint();
}
}
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
if (playerX >= 600) {
playerX = 600;
} else {
moveRight();
}
}
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
if (playerX < 10) {
playerX = 10;
} else {
moveLeft();
}
}
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}
public void moveRight() {
play = true;
playerX += 20;
}
public void moveLeft() {
play = true;
playerX -= 20;
}
public static void main(String[] args) {
JFrame obj = new JFrame();
Gameplay gamePlay = new Gameplay();
obj.setBounds(10, 10, 700, 600);
obj.setTitle("Air Hockey");
obj.setResizable(false);
obj.setVisible(true);
obj.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
obj.getContentPane().add(gamePlay);
}
}
In this program, i'm making an air hockey game where a player controls one of the paddles. But for some reason I can't move the paddle with my code. Is there something wrong with it? I used the if statements on the key event so the paddle can't go out of the game board. When you run this code, you will see a ball bouncing and two stationary paddles.
I am trying to make a brickBreaker game with the help of a video but when I compile I get an error in my public voids that involve KeyEvent towards the bottom of the code.
I get the error as follows:
cannot find symbol-class KeyEvent.
package brickBreaker;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent.*;
import java.awt.event.KeyListener;
import java.util.Timer;
import javax.swing.JPanel;
public class Gameplay extends JPanel implements KeyListener, ActionListener{
private boolean play = false;
private int score = 0;
private int totalBricks = 21;
private Timer time;
private int delay = 8;
private int playerX = 310;
private int ballposX = 120;
private int ballposY = 350;
private int balldirX = -1;
private int balldirY = -2;
private MapGenerator map;
public Gameplay(){
map = new MapGenerator(3, 7);
addKeyListener(this);
addActionListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
// timer = new Timer(delay, this);
// timer.start();
}
public void paint(Graphics g){
//background
g.setColor(Color.black);
g.fillRect(1,1, 692, 592);
//Drawing map
map.draw((Graphics2D)g);
//borders
g.setColor(Color.yellow);
g.fillRect(0,0,3,592);
g.fillRect(0,0,692,3);
g.fillRect(691, 0, 3, 592);
//the paddle
g.setColor(Color.green);
g.fillRect(playerX, 550, 100, 8);
//the ball
g.setColor(Color.yellow);
g.fillOval(ballposX, ballposY, 20, 20);
g.dispose();
}
#Override
public void actionPerformed(ActionEvent e){
timer.start();
if(play){
if(new Rectangle(ballposX, ballposY, 20, 20).intersects(new Rectangle(playerX, 550, 100, 8))){
balldirY = -balldirY;
}
A: for(int i = 0; i < map.map.length; i++){
for(int j = 0; j<map.map[0].length; j++){
if(map.map[i][j] > 0){
int brickX = j* map.brickwidth + 80;
int brickY = i * map.brickheight +50;
int brickwidth = map.brickwidth;
int brickheight = map.brickheight;
Rectangle rect = new Rectangle(brickX, brickY, brickwidth, brickheight);
Rectangle ballRect= new Rectangle(ballposX, ballposY, 20, 20);
Rectangle brickRect = rect;
if(ballRect.intersects(brickRect)){
map.setBrickValue(0, i, j);
totalBricks--;
score += 5;
if(ballposX + 1 <= brickRect.x || ballposX+1 >= brickRect.x+brickRect.width){
balldirX = -balldirX;
} else{
balldirY = -balldirY;
}
break A;
}
}
}
}
ballposX += balldirX;
ballposY+= balldirY;
if(ballposX < 0){
balldirX = -balldirX;
}
if(ballposY < 0){
balldirY = -balldirY;
}
if(ballposX > 670){
balldirX = -balldirX;
}
}
repaint();
}
#Override
public void keyPressed(KeyEvent e){
if(e.getKeyCode() == KeyEvent.VK_RIGHT){
if(playerX >= 600){
playerX = 600;
} else{
moveRight();
}
}
if(e.getKeyCode() == KeyEvent.VK_LEFT){
if(playerX >= 10){
playerX = 10;
} else{
moveLeft();
}
}
}
public void moveRight(){
play = true;
playerX+=20;
}
public void moveLeft(){
play = true;
playerX-=20;
}
}
Change this line import java.awt.event.KeyEvent.*; to this import java.awt.event.KeyEvent;.
EDIT
You need to implement these two methods as well, as they are part of the KeyListener interface.
#Override
public void keyReleased(KeyEvent arg0) {
// TODO
}
#Override
public void keyTyped(KeyEvent arg0) {
// TODO
}