I'm programming a Game called "Kulami". It is a board game for two players.The board is build with rectangular plates different by size. I can sign all plates I need, but I can't move them, the MouseMotionListener doesn't work. A rectangular plate is signed, but there is no contact to press the mouse. I can't find the mistake. Can anyone show on my code and help me?
Thanks!
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import Model.EFieldStateMarble;
import Model.EFieldStatePlate;
public class Plate extends JPanel {
// Eigenschaften
public String plate[][];
// Konstruktor
public Plate(int r, int c, EFieldStatePlate fieldStatePlate, EFieldStateMarble fieldStateMarble) {
plate = new String[r][c];
for (r = 0; r < plate.length; r++) { // waagerecht
for (c = 0; c < plate[r].length; c++) { // senkrecht
plate[r][c] = fieldStatePlate.toString() + fieldStateMarble.toString(); // Codierung Feld
}
}
}
// Methoden
public void showPlate() { // Konsolenausgabe Spielfeldplatte
for (int r = 0; r < plate.length; r++) {
for (int c = 0; c < plate[r].length; c++) {
System.out.print(plate[r][c]);
}
System.out.println();
}
}
// Ändert Eintrage in r-ter Reihe und c-ter Spalte
public void setEntryAt(int r, int c, EFieldStatePlate fieldStatePlate, EFieldStateMarble fieldStateMarble) {
plate[r][c] = fieldStatePlate.toString() + fieldStateMarble.toString();
}
public String[][] getPlate() {
return plate;
}
// dreht das Array um 90°
public void turnPlate() {
int m = plate.length;
int n = plate[0].length;
String[][] returnPlate = new String[n][m];
for (int r = 0; r < plate.length; r++) {
for (int c = 0; c < plate[0].length; c++) {
returnPlate[c][m - 1 - r] = plate[r][c];
}
}plate = returnPlate;
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
drawPlate(g2d, 60, 60);
}
private void drawPlateField(Graphics2D g2d, int x, int y) {
int posX = x;
int posY = y;
g2d.setColor(Color.BLACK);
g2d.drawRect(posX, posY, 60, 60);
g2d.setColor(new Color(242, 203, 130));
g2d.fillRect(posX + 1, posY + 1, 59, 59);
g2d.setColor(Color.BLACK);
g2d.drawOval(x + 15, y + 15, 30, 30);
g2d.setColor(new Color(242, 203, 130));
g2d.fillOval(x + 16, y + 16, 29, 29);
}
private void drawPlate(Graphics g2d, int plateX, int plateY ) {
try {
for (int r = 0; r < plate.length; r++) {
for (int c = 0; c < plate[0].length; c++) {
drawPlateField((Graphics2D) g2d, plateX + c * 60, plateY + r * 60);
}
}
} catch (Exception e) {
System.out.print(e);
}
}
private class PlateDragged implements MouseListener, MouseMotionListener {
//Plattengröße
int platesizeX = plate.length;
int platesizeY = plate[0].length;
//Plattenkoordinaten
int plateX = 60;
int plateY = 60;
//Position, von der die Maus die Platte zieht
int dragFromX = 0;
int dragFromY = 0;
//bei "true" kann die Platte nach Mausklick gezogen werden
boolean candrag = false;
public void mousePressed(MouseEvent mmp) {
new Thread() {
#Override
public void run() {
int x = mmp.getX();
int y = mmp.getY();
if (x >= plateX && x <= (plateX + platesizeY) && y >= plateY && y <= (plateY + platesizeX)) {
candrag = true;
dragFromX = x - plateX;
dragFromY = y - plateY;
}
else {
candrag = false;
}
System.out.println("Hallo");
}
}.start();
}
#Override
public void mouseDragged(MouseEvent mmd) {
new Thread() {
#Override
public void run() {
if (candrag) {
//Plattenposition wechseln
plateX = mmd.getX() - dragFromX;
plateY = mmd.getY() - dragFromY;
//Entferne die Platte nicht aus dem Fenster
plateX = Math.max(plateX, 0);
plateX = Math.min(plateX, getWidth() - platesizeY);
plateY = Math.max(plateY, 0);
plateY = Math.min(plateY, getHeight() - platesizeX);
repaint();
}
}
}.start();
}
public void mouseExited(MouseEvent mme) {
candrag = false;
}
#Override
public void mouseMoved(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseClicked(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
// Plate plate = new Plate();
#Override
public void run() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Plate g2d = new Plate(2, 3, EFieldStatePlate.B6, EFieldStateMarble.EMPTY);
g2d.setPreferredSize(new Dimension(650, 650));
f.add(g2d);
f.pack();
f.setLocation(200, 800);
f.setVisible(true);
}
});
}
}
No where in your code is there a call to addMouseListener(...) or addMouseMotionListener(...). You need to add a listener to a Swing component for the listener to work -- In other words, a listener has to listen to something. e.g.,
// Konstruktor
public Plate(int r, int c, EFieldStatePlate fieldStatePlate,
EFieldStateMarble fieldStateMarble) {
plate = new String[r][c];
for (r = 0; r < plate.length; r++) {
for (c = 0; c < plate[r].length; c++) {
plate[r][c] = fieldStatePlate.toString() + fieldStateMarble.toString();
}
}
// ***** added *****
PlateDragged plateDragged = new PlateDragged();
addMouseListener(plateDragged);
addMouseMotionListener(plateDragged);
}
Frankly questions of this nature, so basic with regards to MouseListener use suggest that you're coding by guessing and without studying the tutorial first. For your sake, don't do this. Please check the MouseListener Tutorial.
Other issue: why are you creating a thread off of the Swing event thread and calling code from it?
Related
I don't really understand why this program draws three pawns instead of one and two of which seem to have a random(probably not so random) positions. enter image description here
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GamePanel extends JPanel implements MouseListener {
static final int SCREEN_EDGE = 800;
static final int GAME_UNITS = 64;
static final int UNIT_SIZE = 100;
final int[] x = new int[GAME_UNITS];
final int[] y = new int[GAME_UNITS];
boolean running = false;
public GamePanel() {
this.setPreferredSize(new Dimension(SCREEN_EDGE, SCREEN_EDGE));
this.setFocusable(true);
this.addKeyListener(new MyKeyAdapter());
startGame();
int[] position = {0,0};
int[] position1 = {1, 0};
new Pawn(position,-1);
}
private void startGame() {
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
draw(g);
}
public void draw(Graphics g){
int counter = 1;
for (int y = 0; y < SCREEN_EDGE/UNIT_SIZE; y++) {
// 1 == "white" 2 == "black"
int color = (y % 2 == 0) ? 1 : 2;
for (int x = 0; x < SCREEN_EDGE/UNIT_SIZE; x++) {
g.setColor(color == 1 ? new Color(239,217, 181) : new Color(180, 136,98));
g.fillRect(x*UNIT_SIZE, y*UNIT_SIZE, UNIT_SIZE, UNIT_SIZE);
color = color == 1 ? 2 : 1;
}
}
for (int i = 0; i < Figure.figures.length; i++) {
JLabel figureSprite = new JLabel(Figure.figures[i].image, JLabel.CENTER);
figureSprite.setSize(90,90);
figureSprite.setLocation(Figure.figures[i].position[0] + 5,Figure.figures[i].position[1] + 5);
this.add(figureSprite);
}
}
#Override
public void mouseClicked(MouseEvent e) {
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
public class MyKeyAdapter extends KeyAdapter {
#Override
public void keyPressed(KeyEvent e) {
}
}
}
import javax.swing.*;
public abstract class Figure{
protected int value;
protected ImageIcon image;
protected int[][] possibleMoves;
public int[] position;
// white = -1 black = 1
protected int whiteOrBlack;
protected static int figureCount = 1;
// int[figureCount][0 = x][1 = y][2 = color]
public static Figure[] figures = new Figure[figureCount];
public Figure(int value, int[] position, int[][] possibleMoves , int whiteOrBlack) {
this.value = value;
this.position = position;
this.possibleMoves = possibleMoves;
this.whiteOrBlack = whiteOrBlack;
Figure[] oldFigures = figures;
figures = new Figure[figureCount];
for (int i = 0; i < oldFigures.length; i++) {
figures[i] = oldFigures[i];
}
figures[figureCount - 1] = this;
figureCount++;
}
public abstract void move(int[] coordinates);
}
import javax.swing.*;
import java.awt.*;
import java.io.*;
public class Pawn extends Figure{
public Pawn(int[] position, int whiteOrBlack) {
super(1, position, new int[3][2], whiteOrBlack);
super.image = new ImageIcon(getClass().getClassLoader().getResource("graphics/" + (whiteOrBlack == -1 ? "whitePawn.png" : "blackPawn.png")));
Image newImage = super.image.getImage().getScaledInstance(90,90, Image.SCALE_AREA_AVERAGING);
super.image = new ImageIcon(newImage);
}
public void checkMoves(){
for (int i = 0; i < figures.length; i++) {
if((position[0] - 1) == figures[i].position[0] && (position[1] + this.whiteOrBlack) == figures[i].position[1] && figures[i].whiteOrBlack != this.whiteOrBlack) {
possibleMoves[0][0] = position[0] - 1;
possibleMoves[0][1] = position[1] + this.whiteOrBlack;
}else possibleMoves[0] = new int[2];
if((position[0]) != figures[i].position[0] && (position[1]) != figures[i].position[1]){
possibleMoves[1][0] = position[0];
possibleMoves[1][1] = position[1] + 1;
}else possibleMoves[1] = new int[2];
if((position[0] + 1) == figures[i].position[0] && (position[1] + this.whiteOrBlack) == figures[i].position[1] && figures[i].whiteOrBlack != this.whiteOrBlack) {
possibleMoves[2][0] = position[0] + 1;
possibleMoves[2][1] = position[1] + this.whiteOrBlack;
}else possibleMoves[2] = new int[2];
}
}
#Override
public void move(int[] coordinates) {
}
}
import javax.swing.*;
public class GameFrame extends JFrame {
public GameFrame(){
this.add(new GamePanel());
this.setTitle("Chess");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
this.setResizable(false);
this.setVisible(true);
this.setLocationRelativeTo(null);
}
}
public class ChessGame {
public static void main(String[] args) {
new GameFrame();
}
}
I tried few thing like changing JLabel to BufferedImage but it would've generate other problems down the line like not being able to use MouseListener so i feel stuck. I would love to know why this code generates 3 textures too.
It looks like you are adding FigureSprites from within the drawComponent() method. The more often you draw the window, the more figures you have to draw.
Instead within drawComponent() just draw the current state but do not modify it. Adding figures has to come from somewhere else. For example, you could create the necessary pawns in the constructor. Or in extra methods that might get triggered based on user input.
In case you modify the GamePanel's state enough so that it should get painted freshly, just invoke repaint(). Swing will mark this component for repainting and decide on it's own when to run the paint() method, which in turn will run paintComponent().
noob here trying to make a simple snake game. followed along with tutorial on youtube and my code mayches the working code as best i can tell...snake not responding to commands, seems KeyListener not working. printed out requestFocusInWindow in jpanel constructor to make sure it was in focus and got back false, even though i entered setFocusable(true) asfirst arg in panel constructor.
please help me figure out why snake not responding to movement commands
package otherSnake;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import java.util.Random;
import javax.swing.JPanel;
public class Panel extends JPanel implements Runnable {
public static final int width = 800, height = 800;
private boolean running = false;
private Thread thread;
private Bodypart b;
private ArrayList<Bodypart> snake;
private Apple apple;
private ArrayList<Apple> apples;
private Random r;
private int size = 5;
private int x = 10, y = 10;
private boolean right = true, left = false, up = false, down = false;
private int ticks = 0;
private Key key;
public Panel() {
setFocusable(true);
key = new Key();
addKeyListener(key);
setPreferredSize(new Dimension(width, height));
r = new Random();
snake = new ArrayList<Bodypart>();
apples = new ArrayList<Apple>();
start();
}
public void tick() {
if (snake.size() == 0) {
b = new Bodypart(x, y, 10);
snake.add(b);
}
if (apples.size() == 0) {
int xCord = r.nextInt(79);
int yCord = r.nextInt(79);
apple = new Apple(xCord, yCord, 10);
apples.add(apple);
}
ticks++;
if (ticks > 250000) {
if (right)
x++;
if (left)
x--;
if (up)
y--;
if (down)
y++;
ticks = 0;
b = new Bodypart(x, y, 10);
snake.add(b);
if (snake.size() > size) {
snake.remove(0);
}
}
}
public void paint(Graphics g) {
g.clearRect(0, 0, width, height);
g.setColor(Color.BLACK);
for (int i = 0; i < width / 10; i++) {
g.drawLine(i * 10, 0, i * 10, height);
}
for (int i = 0; i < height / 10; i++) {
g.drawLine(0, i * 10, width, i * 10);
}
for (int i = 0; i < snake.size(); i++) {
snake.get(i).draw(g);
}
for (int i = 0; i < apples.size(); i++) {
apples.get(i).draw(g);
}
}
public void start() {
running = true;
thread = new Thread(this, "Game Loop");
thread.start();
}
public void stop() {
running = false;
try {
thread.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void run() {
while (running) {
tick();
repaint();
}
}
private class Key implements KeyListener {
#Override
public void keyTyped(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_RIGHT ) {
up = false;
down = false;
right = true;
//left=false;
}
if (key == KeyEvent.VK_LEFT ) {
up = false;
down = false;
left = true;
//right=false;
}
if (key == KeyEvent.VK_UP ) {
up = true;
down = false;
left = false;
right = false;
}
if (key == KeyEvent.VK_DOWN ) {
up = false;
down = true;
left = false;
right = false;
}
}
#Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
}
}
I trying to implement tic tac toe logic into this code. I don't want anything super fancy. It just needs to be a player vs player and must show winner and ask if you want to play again. I've been trying to make this work for a while now and I've had no success.
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class TicTacToe {
public static void main(String[] args) {
JFrame frame = new JFrame(" TicTacToe");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(290, 300);
Board board = new Board();
frame.add(board);
frame.setResizable(false);
frame.setVisible(true);
}
}
class Board extends JComponent {
private int w = 265, h = 265;
char player = 'X';
public Board() {
addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent me) {
int x = me.getX();
int y = me.getY();
int sideWidth = w / 3;
int sideHeight = h / 3;
int a = x / sideWidth;
int b = y / sideHeight;
int xStart = sideWidth * a + 10;
int yStart = sideHeight * b + +sideHeight - 10;
Graphics g = getGraphics();
g.setFont(new Font("monospaced", Font.PLAIN, 110));
g.drawString(player + "", xStart, yStart);
if (player == 'X') {
player = 'O';
} else {
player = 'X';
}
if
}
});
}
public void paint(Graphics g) {
g.drawLine(90, 0, 90, 300);
g.drawLine(185, 0, 185, 300);
g.drawLine(0, 85, 300, 85);
g.drawLine(0, 175, 300, 175);
}
}
Say who won, ask if you would like to play again.
Obviously the game logic is for you to code, but you can easily draw the board using a few loops.
I would try to get the cell index that you clicked on and store player data into a matrix. This way you can simply recall the values when you need to paint. This also adds a layer of validation as to who owns which cell.
char[][] cells = new char[3][3];
#Override
void mousePressed(MouseEvent e) {
int tileWidth = (int) Math.floor(BOARD_WIDTH / cells.length);
int tileHeight = (int) Math.floor(BOARD_HEIGHT / cells[0].length);
int col = (int) Math.floor(e.getX() / tileWidth);
int row = (int) Math.floor(e.getY() / tileHeight);
setPlayer(row, col);
}
void setPlayer(int row, int col) {
if (col < cells.length && row < cells[0].length) {
if (cells[row][col] == 0) {
cells[row][col] = player;
player = player == 'X' ? 'O' : 'X';
repaint();
}
}
}
Also, you should use paintComponent(g) instead of paint(g).
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class TicTacToe implements Runnable {
public static final String TITLE = "TicTacToe";
#Override
public void run() {
JFrame frame = new JFrame(TITLE);
Board board = new Board();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(board);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new TicTacToe());
}
private class Board extends JComponent implements MouseListener {
private static final long serialVersionUID = 5427550843122167512L;
public static final int BOARD_WIDTH = 256;
public static final int BOARD_HEIGHT = 256;
private char[][] cells = new char[3][3];
private char player = 'X';
private int fontHeight = 110;
private Font font = new Font("monospaced", Font.PLAIN, fontHeight);
public Board() {
this.setPreferredSize(new Dimension(BOARD_WIDTH, BOARD_HEIGHT));
this.addMouseListener(this);
}
#Override
protected void paintComponent(Graphics g) {
g.setFont(font);
drawBoard(g);
drawValues(g);
}
private void drawBoard(Graphics g) {
int tileWidth = BOARD_WIDTH / cells.length;
int tileHeight = BOARD_HEIGHT / cells[0].length;
g.drawRect(0, 0, BOARD_WIDTH, BOARD_HEIGHT);
for (int row = 0; row < cells.length; row++) {
g.drawLine(0, row * tileHeight, BOARD_WIDTH, row * tileHeight);
}
for (int col = 0; col < cells[0].length; col++) {
g.drawLine(col * tileWidth, 0, col * tileWidth, BOARD_HEIGHT);
}
}
private void drawValues(Graphics g) {
int tileWidth = BOARD_WIDTH / cells.length;
int tileHeight = BOARD_HEIGHT / cells[0].length;
for (int row = 0; row < cells.length; row++) {
for (int col = 0; col < cells[row].length; col++) {
String text = cells[row][col] + "";
int charWidth = g.getFontMetrics().stringWidth(text);
int xOffset = (int) Math.floor((tileWidth - charWidth) / 2);
int yOffset = (int) Math.floor((tileHeight - fontHeight) * 1.5);
int x = col * tileWidth + xOffset;
int y = row * tileHeight + fontHeight + yOffset;
System.out.println(yOffset);
g.drawString(text, x, y);
}
}
}
private void setPlayer(int row, int col) {
if (col < cells.length && row < cells[0].length) {
if (cells[row][col] == 0) {
cells[row][col] = player;
player = player == 'X' ? 'O' : 'X';
repaint();
}
}
}
#Override
public void mousePressed(MouseEvent e) {
int tileWidth = (int) Math.floor(BOARD_WIDTH / cells.length);
int tileHeight = (int) Math.floor(BOARD_HEIGHT / cells[0].length);
int col = (int) Math.floor(e.getX() / tileWidth);
int row = (int) Math.floor(e.getY() / tileHeight);
setPlayer(row, col);
}
#Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
}
}
My friend code this brick breaker game rip off, but he keep getting this error
"Error: The method getImg() is undefined for the type javax.swing.ImageIcon" and I don't know how to fix it. Can someone help?
here the code:
public class Ball extends Sprite implements iFace{
private int xDir;
private int yDir;
public Ball(){
xDir = 1;
yDir = -1;
String path = "MAJOR_JAVA_ASSESSMENT/ball.png";
ImageIcon i = new ImageIcon(this.getClass().getResource(path));
img = i.getImg();
iWidth = img.getWidth(null);
iHeight = img.getHeight(null);
reset(); }
public void move()
{
x += xDir;
y += yDir;
if(x == 0)
{
setXDir(1);
}
if(x == width - iWidth)
{
setXDir(-1);
}
if (y == 0)
{
setYDir(1);
} }
private void reset()
{
x = initBallX;
y = initBallY;
}
public void setXDir(int x)
{
xDir = x;
}
public void setYDir(int y)
{
yDir = y;
}
public int getYDir()
{
return yDir;
}
}
here another code for you:
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JPanel;
public class Board extends JPanel implements iFace
{
private Timer timer;
private String message = "You lose";
private Ball ball;
private Paddle paddle;
private Brick bricks[];
private boolean inGame = true;
public Board()
{
initBoard();
}
private void initBoard()
{
addKeyListener(new timeAdapter());
setFocusable(true);
bricks = new Brick[numOfBricks];
setDoubleBuffered(true);
timer = new Timer();
timer.scheduleAtFixedRate(new ScheduleTask(), delay, period);
}
#Override
public void addNotify()
{
super.addNotify();
gameInit();
}
private void gameInit()
{
ball = new Ball();
paddle = new Paddle();
int k = 0;
for(int i = 0; i < 5; i++)
{
for(int j = 0; j < 6; j++)
{
bricks[k] = new Brick(j * 40 + 30, i * 10 + 50);
k++;
}
}
}
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D graphics2D = (Graphics2D) g;
graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
graphics2D.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
if (inGame)
{
drawObj(graphics2D);
}
else
{
gameDone(graphics2D);
}
Toolkit.getDefaultToolkit().sync();
}
private void drawObj(Graphics graphics2D)
{
graphics2D.drawImage(ball.getImg(), ball.getX(), ball.getY(), ball.getWidth(), ball.getHeight(), this);
graphics2D.drawImage(paddle.getImg(), paddle.getX(), paddle.getY(), paddle.getWidth(), paddle.getHeight(), this);
for (int i = 0; i < numOfBricks; i++)
{
if(!bricks[i].isDead())
{
graphics2D.drawImage(bricks[i].getImg(), bricks[i].getX(), bricks[i].getY(), bricks[i].getWidth(), bricks[i].getHeight(), this);
}
}
}
private void gameDone(Graphics2D graphics2D)
{
Font f = new Font("TimesRoman", Font.BOLD, 20);
FontMetrics fm = this.getFontMetrics(f);
graphics2D.setColor(Color.RED);
graphics2D.setFont(f);
graphics2D.drawString(message, (iFace.width - fm.stringWidth(message)) / 2, iFace.width / 2);
}
private class timeAdapter extends KeyAdapter
{
#Override
public void keyReleased(KeyEvent p)
{
keyReleased(p);
}
#Override
public void keyPressed(KeyEvent p)
{
keyPressed(p);
}
}
private class ScheduleTask extends TimerTask
{
#Override
public void run()
{
ball.move();
paddle.move();
checkCollision();
repaint();
}
}
private void stopGame()
{
inGame = false;
timer.cancel();
}
private void checkCollision()
{
if(ball.getRectangle().getMaxY() > iFace.bottom)
{
stopGame();
}
for(int i = 0, j = 0; i < numOfBricks; i++)
{
if(bricks[i].isDead())
{
j++;
}
if(j == numOfBricks)
{
message = "GG YOU WIN";
stopGame();
}
}
if ((ball.getRectangle()).intersects(paddle.getRectangle()))
{
int paddlePos = (int) paddle.getRectangle().getMinX();
int ballPos = (int) ball.getRectangle().getMinX();
int first = paddlePos + 8;
int second = paddlePos + 16;
int third = paddlePos + 24;
int fourth = paddlePos + 32;
if (ballPos < first)
{
ball.setXDir(-1);
ball.setYDir(-1);
}
if (ballPos >= first && ballPos < second)
{
ball.setXDir(-1);
ball.setYDir(-1 + ball.getYDir());
}
if (ballPos >= second && ballPos < third)
{
ball.setXDir(0);
ball.setYDir(-1);
}
if (ballPos >= third && ballPos < fourth)
{
ball.setXDir(1);
ball.setYDir(-1);
}
}
for (int i = 0; i < numOfBricks; i++)
{
if ((ball.getRectangle()).intersects(bricks[i].getRectangle()))
{
int ballLeft = (int) ball.getRectangle().getMinX();
int ballHeight = (int) ball.getRectangle().getHeight();
int ballWidth = (int) ball.getRectangle().getWidth();
int ballTop = (int) ball.getRectangle().getMinY();
Point pR = new Point(ballLeft + ballWidth + 1, ballTop);
Point pL = new Point(ballLeft - 1, ballTop);
Point pT = new Point(ballLeft, ballTop - 1);
Point pB = new Point(ballLeft, ballTop + ballHeight + 1);
if (!bricks[i].isDead())
{
if (bricks[i].getRectangle().contains(pR))
{
ball.setXDir(-1);
}
else if
(bricks[i].getRectangle().contains(pL))
{
ball.setXDir(1);
}
if (bricks[i].getRectangle().contains(pT))
{
ball.setYDir(1);
}
else if (bricks[i].getRectangle().contains(pB))
{
ball.setYDir(-1);
}
bricks[i].setDeath(true);
}
}
}
}
}
i only give you the ball code as the two codes that have problems are basically have the same problem, so if someone can fix this one then, then we can the rest.
Also give you board as it the biggest and most important code, so this code may be the problem?
Thank you for reading this, and I hope you can help my friend.
getImg does not exist in the ImageIcon API, I think you'll find that it's ImageIcon#getImage instead
Having said that, I'd recommend using the ImageIO API instead
I am creating a simple game where shapes fall and the player shoots them, but I am having problems creating bullet at every click of the mouse. I have tried various logic with no help, so am just going to put the code up here so you guys can take a look at it and help me out.
The bullet I created is not been created on every click just one is created and it moves on every click which is wrong........I want one bullet to be created per click.
// My main class: mousework2
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.util.*;
import java.awt.geom.*;
public class mousework2 extends JFrame
{
public static int Width = 300;
public static int Height = 400;
private JPanel p1;
private Image pixMage,gunMage;
public mousework2()
{
super("shoot-em-up");
this.setSize(Width, Height);
this.setResizable(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Dimension pos = Toolkit.getDefaultToolkit().getScreenSize();
int x = (pos.width - Width) / 2;
int y = (pos.height - Height) / 2;
this.setLocation(x, y);
p1 = new CreateImage();
this.add(p1);
this.getContentPane();
Thread t = new recMove(this);
t.start();
}
class recMove extends Thread
{
JFrame b;
public recMove(JFrame b)
{
this.b = b;
}
public void run()
{
while (true) {
b.repaint();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
}
}
}
}
class CreateImage extends JPanel implements MouseListener
{
ArrayList<fallShape> rect = new ArrayList<fallShape>();
int x_pos = mousework.Width / 2;
int y_pos = mousework.Height - 50;
int bx_pos = mousework.Width / 2;
int by_pos = mousework.Height;
int y_speed = -10;
boolean clicked;
public CreateImage()
{
for (int i = 0; i < 10; i++) {
rect.add(new fallShape(15, 15, rect));
}
Toolkit picx = Toolkit.getDefaultToolkit();
gunMage = picx.getImage("gunner.jpg");
gunMage = gunMage.getScaledInstance(200, -1, Image.SCALE_SMOOTH);
Toolkit pic = Toolkit.getDefaultToolkit();
pixMage = pic.getImage("ballfall3.jpg");
pixMage = pixMage.getScaledInstance(200, -1, Image.SCALE_SMOOTH);
addMouseListener(this);
addMouseMotionListener(new MouseMotionAdapter() {
#Override
public void mouseMoved(MouseEvent e)
{
x_pos = e.getX() - 5;
}
});
}
public void mousePressed(MouseEvent e)
{
if (e.getButton() == 1) {
clicked = true;
}
}
public void mouseReleased(MouseEvent e)
{
if (e.getButton() == 1) {
clicked = false;
}
}
public void mouseExited(MouseEvent e)
{
}
public void mouseEntered(MouseEvent e)
{
}
public void mouseClicked(MouseEvent e)
{
}
public void paint(Graphics g)
{
super.paint(g);
g.drawImage(pixMage, 0, 0, Width, Height, null);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.drawImage(gunMage,x_pos,y_pos,10,20,null);
if (clicked) {
by_pos += y_speed;
Shape bullet = new Rectangle2D.Float(bx_pos, by_pos, 3, 10);
g2.setColor(Color.BLACK);
g2.fill(bullet);
g2.draw(bullet);
}
g2.setColor(Color.RED);
for (fallShape b : rect) {
b.move();
g2.fill(b);
}
}
}
public static void main(String[] args)
{
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run()
{
new mousework2().setVisible(true);
}
});
}
}
And:
// My falling shapes class: fallShape
import java.awt.geom.*;
import java.util.*;
public class fallShape extends Rectangle2D.Float
{
public int x_speed, y_speed;
public int l, b;
public int height = mousework.Height;
public int width = mousework.Width;
public ArrayList<fallShape> fall;
public fallShape(int breadth, int length, ArrayList<fallShape> fall)
{
super((int) (Math.random() * (mousework.Width - 20) + 1), 0, breadth, length);
this.b = breadth;
this.l = length;
this.x_speed = (int) Math.random() * (10) + 1;
this.y_speed = (int) Math.random() * (10) + 1;
this.fall = fall;
}
public void move()
{
Rectangle2D rec = new Rectangle2D.Float(super.x, super.y, b, l);
for (fallShape f : fall) {
if (f != this && f.intersects(rec)) {
int rxspeed = x_speed;
int ryspeed = y_speed;
x_speed = f.x_speed;
y_speed = f.y_speed;
f.x_speed = rxspeed;
f.y_speed = ryspeed;
}
}
if (super.x < 0) {
super.x =+ super.x;
//super.y =+ super.y;
x_speed = Math.abs(x_speed);
}
if (super.x> mousework.Width - 30) {
super.x =+ super.x;
super.y =+ super.y;
x_speed =- Math.abs(x_speed);
}
if (super.y < 0) {
super.y = 0;
y_speed = Math.abs(y_speed);
}
super.x += x_speed;
super.y += y_speed;
}
}
if(clicked){
by_pos+=y_speed;
This code only draws the bullet when the mouse is down. This is because you are setting clicked to false in your mouseReleased method:
public void mouseReleased(MouseEvent e){
if(e.getButton()==1)
clicked=false;
}
If you were to remove the body of the mouseReleased method, your bullet would move properly.
However, say you wanted to have more than just one bullet. Currently, your paint method only draws one bullet at a time. To draw multiple bullets, you would need to create a list of the coordinates of the bullets, and add a new coordinate pair to the list whenever you click. Then, in the paint method, just update each position in a for loop.
ArrayList<Integer> by_poss = new ArrayList<>();
by_poss is the list of all the y-positions of your bullets.
public void mousePressed(MouseEvent e){
if(e.getButton() == 1)
by_poss.add(mousework.Height);
}
The mousePressed method adds a new "bullet", in the form of a y-position, to the coordinates.
public void mouseReleased(MouseEvent e){
//do nothing
}
Nothing needs to happen in the mouseReleased method.
//update the bullets
public void paint(Graphics g){
...
g2.setColor(Color.BLACK);
Shape bullet;
for(int i = 0; i < by_poss.size(); i++){
by_poss.set(i, by_poss.get(i) + y_speed); //move the bullet
bullet = new Rectangle2D.Float(bx_pos, by_poss.get(i), 3, 10);
g2.fill(bullet);
g2.draw(bullet);
}
...
}
The for loop in your paint method draws all the bullets, one by one, usin g the y-positions from the by_poss list.