Restarting a Thread to restart a game - java

I am making a multiplayer air hockey game as a project. When the ball falls my game stops and I want to restart the game, to count player scores. My question is how can I restart the game?
My code is:
package proje;
import java.awt.Color;
import java.awt.Graphics;
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.JFrame;
import javax.swing.JPanel;
public class BallGame extends JPanel implements KeyListener, ActionListener,
Runnable {
static boolean right = false;
static boolean left = false;
static boolean right2 = false;
static boolean left2 = false;
int disk2x = 60;
int disk2y = 20;
int disk1x = 60;
int disk1y = 450;
public boolean intersects(Rectangle r, Rectangle p) {
int a;
int b;
int radiusR = (r.width / 2);
int radiusP = (p.width / 2);
double hip;
a = Math.abs((r.x) - (p.x));// x düzleminde yarıçapları farkı
b = Math.abs((r.y)) - ((p.y));// y düzleminde yarıçapları farkı
hip = Math.abs(Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2)));
if (hip < radiusR + radiusP) {
return true;
} else
return false;
}
int ballx = 60;
int bally = 43;
Rectangle Ball = new Rectangle(ballx, bally, 20, 20);
Rectangle disk1 = new Rectangle(disk1x, disk1y, 56, 56);
Rectangle disk2 = new Rectangle(disk2x, disk2y, 56, 56);
Thread t;
BallGame() {
addKeyListener(this);
setFocusable(true);
t = new Thread(this);
t.start();
}
public static void main(String[] args) {
JFrame frame = new JFrame();
BallGame game = new BallGame();
frame.setSize(500, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(game);
frame.setLocationRelativeTo(null);// pencere ortada olsun diye
frame.setResizable(false);
frame.setVisible(true);
}
public void paint(Graphics g) {
g.setColor(Color.black);
g.fillRect(0, 0, 500, 600);
g.setColor(Color.green);
g.fillRect(0, 0, 200, 7);
g.setColor(Color.green);
g.fillRect(300, 0, 200, 7);
g.setColor(Color.green);
g.fillRect(0, 566, 200, 7);
g.setColor(Color.green);
g.fillRect(300, 566, 200, 7);
g.setColor(Color.green);
g.fillRect(0, 0, 7, 600);
g.setColor(Color.green);
g.fillRect(489, 0, 7, 600);
g.setColor(Color.red);
g.fillOval(Ball.x, Ball.y, Ball.width, Ball.height);
g.setColor(Color.blue);
g.fillOval(disk1.x, disk1.y, disk1.width, disk1.height);
g.setColor(Color.black);
g.fillRect(500, 600, 500, 600);
g.setColor(Color.yellow);
g.fillOval(disk2.x, disk2.y, disk2.width, disk2.height);
}
int movex = -2;
int movey = -2;
boolean BallFall = false;
int count = 0;
public void run() {
while (BallFall == false) {
if (intersects(disk2, Ball)) {
movey = -movey;
}
repaint();
Ball.x += movex;
Ball.y += movey;
if (left2 == true) {
disk2.x -= 3;
right2 = false;
}
if (right2 == true) {
disk2.x += 3;
left2 = false;
}
if (left == true) {
disk1.x -= 3;
right = false;
}
if (right == true) {
disk1.x += 3;
left = false;
}
if (disk1.x <= 4) {
disk1.x = 4;
} else if (disk1.x >= 445) {
disk1.x = 445;
}
if (intersects(Ball, disk1)) {
movey = -movey;
}
if ((200 <= Ball.x) && (Ball.x <= 300) && (Ball.y <= 0)) {
BallFall = true;
}
if (Ball.x <= 0 || Ball.x + Ball.height >= 480) {
movex = -movex;
}
if (Ball.y <= 0) {
movey = -movey;
}
if ((Ball.y >= 560) && (Ball.x >= 300)) {
movey = -movey;
}
if ((Ball.y >= 560) && (Ball.x <= 200)) {
movey = -movey;
}
if ((200 <= Ball.x) && (Ball.x <= 300) && (Ball.y >= 600)) {
BallFall = true;
}
try {
Thread.sleep(8);
} catch (Exception ex) {
}
}
}
#Override
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_LEFT) {
left = true;
}
if (keyCode == KeyEvent.VK_RIGHT) {
right = true;
}
if (keyCode == KeyEvent.VK_A) {
left2 = true;
}
if (keyCode == KeyEvent.VK_D) {
right2 = true;
}
}
#Override
public void keyReleased(KeyEvent e) {
int keyCode = e.getKeyCode();
if (keyCode == KeyEvent.VK_LEFT) {
left = false;
}
if (keyCode == KeyEvent.VK_RIGHT) {
right = false;
}
if (keyCode == KeyEvent.VK_A) {
left2 = false;
}
if (keyCode == KeyEvent.VK_D) {
right2 = false;
}
}
#Override
public void keyTyped(KeyEvent arg0) {
}
#Override
public void actionPerformed(ActionEvent e) {
}
}

Related

I'm trying to make a shape move in a circular fashion in JPanel/JFrame

If you move the shape over a little by pressing an arrow (release arrow key)and then press space bar it does like a diamond shape.
I want to be able to press the space-bar and then my shape draws a circle, instead of being able to go just Left
or Just Right
Can I code it do to Left and Down? To take two keyInputs?
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Tutorial extends JPanel implements ActionListener, KeyListener
{
Timer tm = new Timer(5, this);
int x = 250, y = 250, velX = 0, velY = 0;
public Tutorial()
{
tm.start();
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.RED);
g.fillRect(x, y, 50,50);
}
public void actionPerformed(ActionEvent e)
{
if (x < 0)
{
velX =0;
x = 0;
}
if (x > 450 )
{
velX = 0;
x = 450;
}
if (y < 0)
{
velY = 0;
y = 0;
}
if (y > 450)
{
velY = 0;
y = 450;
}
x = x + velX;
y = y + velY;
repaint();
}
public void keyPressed(KeyEvent e)
{
float speed = .3f;
int c = e.getKeyCode();
if(c == KeyEvent.VK_LEFT)
{
velX = -1; //LEFT
velY = 0;
}
if (c == KeyEvent.VK_UP)
{
velX = 0;
velY = -1; //UP
}
if (c == KeyEvent.VK_RIGHT)
{
velX = 1; //RIGHT
velY = 0;
}
if (c == KeyEvent.VK_DOWN)
{
velX = 0;
velY = 1; //DOWN
}
if (c == KeyEvent.VK_SPACE) {
if (y < 175) {
velX = 1; //RIGHT
}
if (c == KeyEvent.VK_SPACE) {
if (x > 275) {
velY = 1; //DOWN
}
}
if (c == KeyEvent.VK_SPACE) {
if (y > 275) {
velX = -1; //LEFT
}
}
if (c == KeyEvent.VK_SPACE) {
if (x < 175) {
velY = -1; //UP
}
}
}
}
public void keyTyped(KeyEvent e){}
public void keyReleased(KeyEvent e)
{
velX = 0;
velY = 0;
}
public static void main(String[] args)
{
Tutorial t = new Tutorial();
JFrame jf = new JFrame();
jf.setTitle("Tutorial");
jf.setSize(500,500);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.add(t);
}
}

(Java 1.8, Eclipse) SNAKEGAME - Texture-Problems

i made a SnakeGame and its working in its basics, but i started to texture my snake with images.
i wanted the textures to change the direction whenever the snake changes directions aswell. and it is working, the problem i have is that every time the snake changes direction all of the snake body parts change direction at the same time which leads to texture bugs, how can i change the texture for the next bodyPart per one Timer tick?
And also how can i edit the Texture for the last bodyPart only for a tail
the code below is only the code from the important class "gamepanel"
the texture code is in the method draw(Graphics g)
thanks for the help i could not find any solutions to this.
package game;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
public class gamepanel extends JPanel implements ActionListener {
/**
*
*/
private static final long serialVersionUID = 42L;
static final int SCREEN_WIDTH = 600;
static final int SCREEN_HEIGHT = 600;
static final int UNIT_SIZE = 25;
static final int GAME_UNITS = (SCREEN_WIDTH*SCREEN_HEIGHT)/UNIT_SIZE;
int DELAY = 100;
final int x[] = new int[GAME_UNITS];
final int y[] = new int[GAME_UNITS];
int bodyParts = 6;
String str = String.valueOf(bodyParts);
int applesEaten;
int appleX;
int appleY;
char direction = 'R';
boolean running = false;
Timer timer;
Random random;
Image apple = new ImageIcon(this.getClass().getResource("/images/redapple.png")).getImage();
Image headup = new ImageIcon(this.getClass().getResource("/images/headup.png")).getImage();
Image headr = new ImageIcon(this.getClass().getResource("/images/headr.png")).getImage();
Image headl = new ImageIcon(this.getClass().getResource("/images/headl.png")).getImage();
Image headd = new ImageIcon(this.getClass().getResource("/images/headd.png")).getImage();
Image bodyup = new ImageIcon(this.getClass().getResource("/images/bodyup.png")).getImage();
Image bodyd = new ImageIcon(this.getClass().getResource("/images/bodyd.png")).getImage();
Image bodyr = new ImageIcon(this.getClass().getResource("/images/bodyr.png")).getImage();
Image bodyl = new ImageIcon(this.getClass().getResource("/images/bodyl.png")).getImage();
gamepanel(){
random = new Random();
this.setPreferredSize(new Dimension(SCREEN_WIDTH,SCREEN_HEIGHT));
this.setBackground(new Color(33, 33, 33));
this.setFocusable(true);
this.addKeyListener(new MyKeyAdapter());
startGame();
}
public void startGame() {
newApple();
running = true;
timer = new Timer(DELAY,this);
timer.start();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
draw(g);
}
public void draw(Graphics g) {
if(running) {
/* for(int i=0;i<SCREEN_HEIGHT/UNIT_SIZE;i++) {
g.drawLine(i*UNIT_SIZE, 0, i*UNIT_SIZE, SCREEN_HEIGHT);
g.drawLine(0, i*UNIT_SIZE, SCREEN_WIDTH, i*UNIT_SIZE);
} */
//g.setColor(new Color(73, 235, 116));
//g.fillOval(appleX,appleY, UNIT_SIZE, UNIT_SIZE);
g.drawImage(apple, appleX,appleY, UNIT_SIZE, UNIT_SIZE, null, null);
for(int i = 0;i< bodyParts; i++) {
//HEAD TEXTURE
if(i==0 && direction=='U') {
g.drawImage(headup,x[i],y[i],UNIT_SIZE, UNIT_SIZE,null);
} else if(i==0 && direction=='R') {
g.drawImage(headr,x[i],y[i],UNIT_SIZE, UNIT_SIZE,null);
} else if(i==0 && direction=='L') {
g.drawImage(headl,x[i],y[i],UNIT_SIZE, UNIT_SIZE,null);
} else if(i==0 && direction=='D') {
g.drawImage(headd,x[i],y[i],UNIT_SIZE, UNIT_SIZE,null);
//BODY TEXTURE
} else if(i!=0 && direction=='U') {
g.drawImage(bodyup,x[i],y[i],UNIT_SIZE, UNIT_SIZE,null);
} else if(i!=0 && direction=='R') {
g.drawImage(bodyr,x[i],y[i],UNIT_SIZE, UNIT_SIZE,null);
} else if(i!=0 && direction=='L') {
g.drawImage(bodyl,x[i],y[i],UNIT_SIZE, UNIT_SIZE,null);
} else if(i!=0 && direction=='D') {
g.drawImage(bodyd,x[i],y[i],UNIT_SIZE, UNIT_SIZE,null);
}
}
g.setColor(Color.red);
g.setFont(new Font("Arial",Font.BOLD,40));
FontMetrics metrics = getFontMetrics(g.getFont());
g.drawString("Score: "+applesEaten, (SCREEN_WIDTH - metrics.stringWidth("Score: "+applesEaten))/2, g.getFont().getSize());
}else {
gameOver(g);
}
}
public void newApple() {
appleX = random.nextInt((int)(SCREEN_WIDTH/UNIT_SIZE))*UNIT_SIZE;
appleY = random.nextInt((int)(SCREEN_HEIGHT/UNIT_SIZE))*UNIT_SIZE;
}
public void move() {
for(int i = bodyParts;i>0;i--) {
x[i] = x[i-1];
y[i] = y[i-1];
}
switch(direction) {
case 'U' :
y[0] = y[0] - UNIT_SIZE;
break;
case 'D' :
y[0] = y[0] + UNIT_SIZE;
break;
case 'L' :
x[0] = x[0] - UNIT_SIZE;
break;
case 'R' :
x[0] = x[0] + UNIT_SIZE;
break;
}
}
public void checkApple() {
int i = bodyParts;
if((x[i] == appleX) && (y[i] == appleY)) {
newApple();
} else if((x[0] == appleX) && (y[0] == appleY)) {
bodyParts++;
applesEaten++;
DELAY--;
newApple();
}
}
public void checkCollisions() {
//checks if head collides with body
for(int i = bodyParts; i>0;i--) {
if ((x[0]==x[i]) && (y[0]==y[i])) {
running = false;
}
}
// checks if head touches left border
if(x[0] < 0) {
running = false;
}
// check right border collide
if(x[0] > SCREEN_WIDTH) {
running = false;
}
// check top border
if(y[0] < 0) {
running = false;
}
//checkk bottom border
if(y[0] > SCREEN_HEIGHT) {
running = false;
}
if(!running) {
timer.stop();
}
}
public void gameOver(Graphics g) {
//SCORE
g.setColor(Color.red);
g.setFont(new Font("Arial",Font.BOLD,40));
FontMetrics metrics1 = getFontMetrics(g.getFont());
g.drawString("Your Score: "+applesEaten, (SCREEN_WIDTH - metrics1.stringWidth("Your Score: "+applesEaten))/2, g.getFont().getSize());
//GAme Over Text
g.setColor(Color.red);
g.setFont(new Font("Arial",Font.BOLD,75));
FontMetrics metrics2 = getFontMetrics(g.getFont());
g.drawString("Game Over", (SCREEN_WIDTH - metrics2.stringWidth("Game Over"))/2, SCREEN_HEIGHT/2);
}
#Override
public void actionPerformed(ActionEvent e) {
if(running) {
move();
checkApple();
checkCollisions();
}
repaint();
}
public class MyKeyAdapter extends KeyAdapter{
#Override
public void keyPressed(KeyEvent e) {
switch(e.getKeyCode()) {
case KeyEvent.VK_LEFT:
if(direction != 'R') {
direction = 'L';
}
break;
case KeyEvent.VK_RIGHT:
if(direction != 'L') {
direction = 'R';
}
break;
case KeyEvent.VK_UP:
if(direction != 'D') {
direction = 'U';
}
break;
case KeyEvent.VK_DOWN:
if(direction != 'U') {
direction = 'D';
}
break;
}
}
}
}
maybe try updating the textures for each body part starting from the head 1 per game frame at a time? like 0 = head piece and will be updated first, 1 is the next body part in line so will be updated in the next frame when the snake has moved 1 unit and therefore lining up the timings

Java Tetris Key Listener Not Working (No Errors On Console)

I'm working on a project for my AP computer science class and can't seem to figure out how to get my key listeners to work I've tried using if statements and switch cases but neither of these make the key listeners work. The code consists of three classes Tetris Runner, Canvas, PeiceMaker everything functions fine with exception of the key listeners The key listeners are located at the bottom of the canvas class any help would be appreciated thanks.
Canvas Class
package Tetris;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;
import Tetris.PieceMaker.Tetronimos;
#SuppressWarnings("serial")
public class Canvas extends JPanel implements ActionListener
{
public static final int CANVASWIDTH = 10;
public static final int CANVASHEIGHT = 22;
private Color[] colors =
{
new Color(0, 0, 0),
new Color(204, 102, 102),
new Color(102, 204, 102),
new Color(102, 102, 204),
new Color(204, 204, 102),
new Color(204, 102, 204),
new Color(102, 204, 204),
new Color(218, 170, 0)
};
private boolean blockSet = false;
private boolean startGame = false;
private boolean pauseGame = false;
private int linesErased = 0;
private int currentX = 0;
private int currentY = 0;
private JLabel scoreLabel;
private Timer time;
private PieceMaker currentShape;
private Tetronimos[] canvas;
public Canvas(TetrisRunner run)
{
setFocusable(true);
currentShape = new PieceMaker();
time = new Timer(500, this);
scoreLabel = run.getScoreLabel();
canvas = new Tetronimos[CANVASWIDTH * CANVASHEIGHT];
clearCanvas();
addKeyListener(new TetrisAdap());
}
public int blockWidth()
{
return (int)getSize().getWidth()/CANVASWIDTH;
}
public int blockHeight()
{
return (int)getSize().getHeight()/CANVASHEIGHT;
}
public Tetronimos shapeLocation(int x, int y)
{
return canvas[y * CANVASWIDTH + x];
}
public void clearCanvas()
{
for(int i = 0; i < CANVASHEIGHT * CANVASWIDTH; i++)
{
canvas[i] = Tetronimos.noShape;
}
}
public void droppedPiece()
{
for(int i = 0; i < 4; i++)
{
int newX = currentX + currentShape.getXPosition(i);
int newY = currentY - currentShape.getYPosition(i);
canvas[newY * CANVASWIDTH + newX] = currentShape.getShape();
}
clearRow();
if(!blockSet)
{
makeNewPiece();
}
}
public void makeNewPiece()
{
currentShape.chooseRandomShape();
currentX = CANVASWIDTH / 2 + 1;
currentY = CANVASHEIGHT - 1 + currentShape.minY();
if(!movePiece(currentShape, currentX, currentY - 1))
{
currentShape.setShape(Tetronimos.noShape);
time.stop();
startGame = false;
scoreLabel.setText("GAME OVER");
}
}
public void moveDownLine()
{
if(!movePiece(currentShape, currentX, currentY - 1))
{
droppedPiece();
}
}
public void actionPerformed(ActionEvent e)
{
if(blockSet)
{
blockSet = false;
makeNewPiece();
} else {
moveDownLine();
}
}
public void drawShape(int x, int y, Tetronimos shape, Graphics g)
{
Color color = colors[shape.ordinal()];
g.setColor(color);
g.fillRect(x + 1, y + 1, blockWidth() - 2, blockHeight() - 2);
g.setColor(color.brighter());
g.drawLine(x, y + blockHeight() - 1, x, y);
g.drawLine(x, y, x + blockWidth() - 1, y);
g.setColor(color.darker());
g.drawLine(x + 1, y + blockHeight() - 1, x + blockWidth() - 1, y + blockHeight() - 1);
g.drawLine(x + blockWidth() - 1, y + blockHeight() - 1, x + blockWidth() - 1, y + 1);
}
public void paint(Graphics g)
{
super.paint(g);
Dimension size = getSize();
int topOfCanvas = (int)size.getHeight() - CANVASHEIGHT * blockHeight();
for(int i = 0; i < CANVASHEIGHT; i++)
{
for(int p = 0; p < CANVASWIDTH; p++)
{
Tetronimos shape = shapeLocation(p, CANVASHEIGHT - i - 1);
if(shape != Tetronimos.noShape)
{
drawShape(p * blockWidth(), topOfCanvas + i * blockHeight(), shape, g);
}
}
}
if(currentShape.getShape() != Tetronimos.noShape)
{
for(int i = 0; i < 4; i++)
{
int x = currentX + currentShape.getXPosition(i);
int y = currentY - currentShape.getYPosition(i);
drawShape(x * blockWidth(), topOfCanvas + (CANVASHEIGHT - y - 1) * blockHeight(), currentShape.getShape(), g);
}
}
}
public void start()
{
if(pauseGame)
{
return;
}
startGame = true;
blockSet = false;
linesErased = 0;
clearCanvas();
makeNewPiece();
time.start();
}
public void pause()
{
if(!startGame)
{
return;
}
pauseGame = !pauseGame;
if(pauseGame)
{
time.stop();
scoreLabel.setText("PAUSED");
} else {
time.start();
scoreLabel.setText(String.valueOf(linesErased));
}
repaint();
}
public boolean movePiece(PieceMaker newPiece, int xVel, int yVel)
{
for(int i = 0; i < 4; i++)
{
int x = xVel + newPiece.getXPosition(i);
int y = yVel - newPiece.getYPosition(i);
if(x < 0 || x >= CANVASWIDTH || y < 0 || y >= CANVASHEIGHT)
{
return false;
}
if(shapeLocation(x, y) != Tetronimos.noShape)
{
return false;
}
}
currentShape = newPiece;
currentX = xVel;
currentY = yVel;
repaint();
return true;
}
public void clearRow()
{
int fullRows = 0;
for(int i = CANVASHEIGHT - 1; i >= 0; i--)
{
boolean rowIsFull = true;
for(int p = 0; p < CANVASWIDTH; p++)
{
if(shapeLocation(p, i) == Tetronimos.noShape)
{
rowIsFull = false;
break;
}
}
if(rowIsFull)
{
fullRows++;
for(int j = i; j < CANVASHEIGHT - 1; j++)
{
for(int k = 0; k < CANVASWIDTH; k++)
{
canvas[j * CANVASWIDTH + k] = shapeLocation(j, k + 1);
}
}
}
if(fullRows > 0)
{
linesErased += fullRows;
scoreLabel.setText(String.valueOf(linesErased));
blockSet = true;
currentShape.setShape(Tetronimos.noShape);
repaint();
}
}
}
public void dropRows()
{
int nextY = currentY;
while(nextY > 0)
{
if(!movePiece(currentShape, currentX, nextY - 1))
{
break;
}
nextY--;
}
droppedPiece();
}
//Tetris Adapter
public class TetrisAdap extends KeyAdapter {
public void KeyPressed(KeyEvent ke)
{
if(!startGame || currentShape.getShape() == Tetronimos.noShape)
{
System.out.println("Here");
return;
}
int keyCode = ke.getKeyCode();
if(keyCode == 'p' || keyCode == 'P')
pause();
if(pauseGame)
return;
if(keyCode == KeyEvent.VK_LEFT)
{
System.out.println("left");
movePiece(currentShape, currentX - 1, currentY);
}
if(keyCode == KeyEvent.VK_RIGHT)
{
System.out.println("right");
movePiece(currentShape, currentX + 1, currentY);
}
if(keyCode == KeyEvent.VK_DOWN)
{
System.out.println("down");
movePiece(currentShape.rotateRight(), currentX, currentY);
}
if(keyCode == KeyEvent.VK_UP)
{
System.out.println("up");
movePiece(currentShape.rotateLeft(), currentX, currentY);
}
if(keyCode == KeyEvent.VK_SPACE)
{
dropRows();
}
if(keyCode == 'd')
moveDownLine();
if(keyCode == 'D')
moveDownLine();
/*
* switch(keyCode)
{
case KeyEvent.VK_LEFT:
System.out.println("left");
movePiece(currentShape, currentX - 1, currentY);
break;
case KeyEvent.VK_RIGHT:
System.out.println("right");
movePiece(currentShape, currentX + 1, currentY);
break;
case KeyEvent.VK_DOWN:
System.out.println("down");
movePiece(currentShape.rotateRight(), currentX, currentY);
break;
case KeyEvent.VK_UP:
System.out.println("up");
movePiece(currentShape.rotateLeft(), currentX, currentY);
break;
case KeyEvent.VK_SPACE:
dropRows();
break;
case 'd' :
moveDownLine();
break;
case 'D' :
moveDownLine();
}
*
*/
}
}
}
Tetris Runner
package Tetris;
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
#SuppressWarnings("serial")
public class TetrisRunner extends JFrame
{
private JLabel scoreLabel;
public TetrisRunner()
{
scoreLabel = new JLabel("0");
add(scoreLabel, BorderLayout.SOUTH);
Canvas canvas = new Canvas(this);
add(canvas);
canvas.makeNewPiece();
canvas.start();
setSize(400, 800);
setTitle("Tetris");
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
TetrisRunner runner = new TetrisRunner();
runner.setLocationRelativeTo(null);
runner.setVisible(true);
}
public JLabel getScoreLabel()
{
return scoreLabel;
}
}
Peice Maker
package Tetris;
import java.util.Random;
public class PieceMaker
{
private Tetronimos shapeChoice;
private int[][] coordinates;
public PieceMaker()
{
coordinates = new int[4][2];
setShape(Tetronimos.noShape);
}
enum Tetronimos
{
noShape(new int[][] { {0,0}, {0,0}, {0,0}, {0,0} }),
lineShape(new int[][] { {0,-1}, {0,0}, {0,1}, {0,2} }),
sShape(new int[][] { {0,-1}, {0,0}, {1,0}, {1,1} }),
zShape(new int[][] { {0,-1}, {0,0}, {-1,0}, {-1,1} }),
tShape(new int[][] { {-1,0}, {0,0}, {1,0}, {0,1} }),
lShape(new int[][] { {-1,-1}, {0,-1}, {0,0}, {0,1} }),
jShape(new int[][] { {-1,-1}, {0,-1}, {0,0}, {0,1} }),
blockShape(new int[][] { {0,0}, {1,0}, {0,1}, {1,1} });
public int[][] shapeCoordinates;
private Tetronimos(int[][] coordinates)
{
this.shapeCoordinates = coordinates;
}
}
public void chooseRandomShape()
{
Random rand = new Random();
int randChoice = Math.abs(rand.nextInt() % 7 + 1);
Tetronimos[] choice = Tetronimos.values();
setShape(choice[randChoice]);
}
public void setShape(Tetronimos shape)
{
for(int i = 0; i < 4; i++)
{
for(int p = 0; p < 2; p++)
{
coordinates[i][p] = shape.shapeCoordinates[i][p];
}
}
shapeChoice = shape;
}
public void setXPosition(int oldX, int newX)
{
coordinates[oldX][0] = newX;
}
public void setYPosition(int oldY, int newY)
{
coordinates[oldY][1] = newY;
}
public int getXPosition(int newX)
{
return coordinates[newX][0];
}
public int getYPosition(int newY)
{
return coordinates[newY][1];
}
public Tetronimos getShape()
{
return shapeChoice;
}
public int minX()
{
int minX = coordinates[0][0];
for(int i = 0; i < 4; i++)
{
minX = Math.min(minX, coordinates[i][0]);
}
return minX;
}
public int minY()
{
int minY = coordinates[0][1];
for(int i = 0; i < 4; i++)
{
minY = Math.min(minY, coordinates[i][1]);
}
return minY;
}
//Rotate piece Left
public PieceMaker rotateLeft()
{
System.out.println("left");
if(shapeChoice == Tetronimos.blockShape)
{
return this;
}
PieceMaker res = new PieceMaker();
res.shapeChoice = shapeChoice;
for(int i = 0; i < 4; i++)
{
res.setXPosition(i, getYPosition(i));
res.setYPosition(i, -getXPosition(i));
}
return res;
}
//Rotate piece right
public PieceMaker rotateRight()
{
System.out.println("right");
if(shapeChoice == Tetronimos.blockShape)
{
return this;
}
PieceMaker res = new PieceMaker();
res.shapeChoice = shapeChoice;
for(int i = 0; i < 4; i++)
{
res.setXPosition(i, -getYPosition(i));
res.setYPosition(i, getXPosition(i));
}
return res;
}
}
You misspelled your keyPressed()-Method. Use
public class TetrisAdap extends KeyAdapter {
public void keyPressed(KeyEvent ke) { ...
instead of
public class TetrisAdap extends KeyAdapter {
public void KeyPressed(KeyEvent ke)
{

Java applet - MouseMotionListener works in eclipse but not on browser

I'm having some problems with my java applet...
MouseMotionListener works in eclipse applet viewer but not on browsers(I tried Chrome and Firefox and IE). In the game, I try to move a object using mouse.
The MouseMotionListener is in the initComponents method.
package tk.miloskostadinovski.game;
import java.applet.Applet;
import java.awt.Button;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.PointerInfo;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Random;
import javax.swing.SwingUtilities;
public class Game extends Applet implements Runnable {
private static final long serialVersionUID = 1L;
// varibles
Thread thread;
boolean running = false;
Random random = new Random();
boolean pauseRunning = false;
int width = 600, height = 700;
int x = 350, y = 560;
int fruitSpeed = 2;
int points = 0;
int lives = 5;
int basketWH = 100;
int fruitWH = 70;
int aX = getRandNumbX(), aY = getRandNumbY();
int oX = getRandNumbX(), oY = getRandNumbY();
int sX = getRandNumbX(), sY = getRandNumbY();
int bX = getRandNumbX(), bY = getRandNumbY();
int hX = getRandNumbX(), hY = getRandNumbY();
int basketX = 350;
int basketY = 580;
private Image i;
private Graphics doubleG;
Image apple, orange, banana, straw, hamburger, background, basket, heart,
mellon;
public void init() {
initComponents();
setSize(width, height);
setLayout(null);
apple = getImage(getDocumentBase(), "pictures/apple.png");
orange = getImage(getDocumentBase(), "pictures/orange.png");
banana = getImage(getDocumentBase(), "pictures/banana.png");
straw = getImage(getDocumentBase(), "pictures/straw.gif");
hamburger = getImage(getDocumentBase(), "pictures/hamburger.png");
background = getImage(getDocumentBase(), "pictures/background.jpg");
basket = getImage(getDocumentBase(), "pictures/basket.png");
heart = getImage(getDocumentBase(), "pictures/heart.png");
mellon = getImage(getDocumentBase(), "pictures/mellon.png");
}
public void start() {
}
public void stop() {
running = false;
if (thread != null) {
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void destroy() {
}
public void run() {
pauseButton.setVisible(true);
while (running) {
while (pauseRunning) {
repaint();
}
fruitMoving();
repaint();
if (aY >= height) {
aY = getRandNumbY();
aX = getRandNumbX();
lives--;
}
if (oY >= height) {
oY = getRandNumbY();
oX = getRandNumbX();
lives--;
}
if (bY >= height) {
bY = getRandNumbY();
bX = getRandNumbX();
lives--;
}
if (sY >= height) {
sY = getRandNumbY();
sX = getRandNumbX();
lives--;
}
if (hY >= height) {
hY = getRandNumbY();
hX = getRandNumbX();
}
if (hY <= basketY + basketWH && hY >= basketY && hX >= basketX - 40
&& hX <= basketX + basketWH) {
lives--;
hY = getRandNumbY();
hX = getRandNumbX();
}
if (sY <= basketY + basketWH && sY >= basketY && sX >= basketX - 40
&& sX <= basketX + basketWH) {
points++;
sY = getRandNumbY();
sX = getRandNumbX();
}
if (bY <= basketY + basketWH && bY >= basketY && bX >= basketX - 40
&& bX <= basketX + basketWH) {
points++;
bY = getRandNumbY();
bX = getRandNumbX();
}
if (oY <= basketY + basketWH && oY >= basketY && oX >= basketX - 40
&& oX <= basketX + basketWH) {
points++;
oY = getRandNumbY();
oX = getRandNumbX();
}
if (aY <= basketY + basketWH && aY >= basketY && aX >= basketX - 40
&& aX <= basketX + basketWH) {
points++;
aY = getRandNumbY();
aX = getRandNumbX();
}
if (basketX >= width - basketWH) {
basketX = width - basketWH;
}
if (basketX <= 0) {
basketX = 0;
}
if (lives <= 0) {
tryAgain.setVisible(true);
while (true) {
if (tryAgain.isVisible() == false) {
aY = getRandNumbY();
aX = getRandNumbX();
oY = getRandNumbY();
oX = getRandNumbX();
sY = getRandNumbY();
sX = getRandNumbX();
bY = getRandNumbY();
bX = getRandNumbX();
hY = getRandNumbY();
hX = getRandNumbX();
lives = 5;
points = 0;
break;
}
}
}
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
#Override
public void paint(Graphics g) {
super.paintComponents(g);
g.drawImage(background, 0, 0, this);
g.drawImage(apple, aX, aY, this);
g.drawImage(orange, oX, oY, this);
g.drawImage(banana, bX, bY, this);
g.drawImage(straw, sX, sY, this);
g.drawImage(hamburger, hX, hY, this);
g.drawImage(basket, basketX, basketY, this);
g.drawImage(heart, 100, 10, this);
g.drawImage(mellon, 20, 10, this);
g.setFont(new Font("Seris", Font.PLAIN, 20));
g.drawString(lives + "", 125, 30);
g.drawString(points + "", 50, 30);
if (lives <= 0) {
g.setFont(new Font("Seris", Font.PLAIN, 30));
g.drawString("Game over", 220, 300);
}
if (pauseRunning) {
g.drawString("Game Paused", 220, 300);
}
}
#Override
public void update(Graphics g) {
if (i == null) {
i = createImage(this.getSize().width, this.getSize().height);
doubleG = i.getGraphics();
}
doubleG.setColor(getBackground());
doubleG.fillRect(0, 0, width, height);
doubleG.setColor(getForeground());
paint(doubleG);
g.drawImage(i, 0, 0, this);
}
public void initComponents() {
// startGame button, pointsBox, livesBox, pause button, game over, play
// again, resume game
setFocusable(true);
addMouseMotionListener(new MouseAdapter() {
#Override
public void mouseMoved(MouseEvent evt) {
formMouseMoved(evt);
}
});
addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent evt) {
formKeyPressed(evt);
}
});
startGame = new Button("Start Game");
startGame.setFocusable(false);
startGame.setLocation(230, 300);
startGame.setSize(130, 40);
startGame.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
startGameActionPerformed(e);
}
});
tryAgain = new Button("Try Again?");
tryAgain.setFocusable(false);
tryAgain.setLocation(230, 350);
tryAgain.setSize(130, 40);
tryAgain.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
tryAgainActionPerformed(e);
}
});
tryAgain.setVisible(false);
pauseButton = new Button("Pause");
pauseButton.setFocusable(false);
pauseButton.setLocation(550, 10);
pauseButton.setSize(40, 25);
pauseButton.setVisible(false);
pauseButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
pauseButtonActionPerformed(e);
}
});
add(startGame);
add(tryAgain);
add(pauseButton);
}
public void startGameActionPerformed(ActionEvent e) {
running = true;
thread = new Thread(this);
thread.start();
startGame.setVisible(false);
}
public void tryAgainActionPerformed(ActionEvent e) {
points = 0;
lives = 5;
tryAgain.setVisible(false);
}
public void pauseButtonActionPerformed(ActionEvent e) {
if (pauseRunning == false) {
pauseRunning = true;
} else {
pauseRunning = false;
}
}
public int getRandNumbX() {
return random.nextInt(520) + 10;
}
public int getRandNumbY() {
return (random.nextInt(+600) + 100) * -1;
}
public void fruitMoving() {
aY += fruitSpeed;
oY += fruitSpeed;
sY += fruitSpeed;
bY += fruitSpeed;
hY += fruitSpeed;
}
public void formMouseMoved(MouseEvent evt) {
PointerInfo a = MouseInfo.getPointerInfo();
Point point = new Point(a.getLocation());
SwingUtilities.convertPointFromScreen(point, evt.getComponent());
basketX = (int) point.getX() - 50;
repaint();
}
public void formKeyPressed(KeyEvent evt) {
if (pauseRunning == false) {
if (evt.getKeyCode() == KeyEvent.VK_RIGHT)
basketX += 20;
if (evt.getKeyCode() == KeyEvent.VK_LEFT)
basketX -= 20;
}
}
// Component declaration
Button startGame, tryAgain, pauseButton;
}

Skipping and Tearing in Java Animation

the following code draws a square with two smaller square rotating inside it. whenever you click an arrow on the keyboard, the whole system will move in that direction. however i'm having some problems with the image tearing and at times skipping (its small but still there). i was wondering if anybody knew how i could fix these issues w/o massively altering the code.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import static java.awt.Color.*;
public class GUI extends JPanel implements ActionListener, KeyListener
{
int x, y, x1, y1, x2, y2, changeX, changeY, changeX2, changeY2;
JFrame frame;
Runtime r;
public static void main(String[] args)
{
new GUI();
}
public GUI()
{
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e)
{
e.printStackTrace();
}
setSize(1020,770);
setBackground(WHITE);
setOpaque(true);
setVisible(true);
x = 0;
y = 0;
x1 = 0;
y1 = 0;
x2 = 0;
y2 = 0;
changeX=1;
changeY=0;
changeX2=1;
changeY2=0;
r = Runtime.getRuntime();
frame = new JFrame();
frame.setSize(1020,819);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setJMenuBar(createMenuBar());
frame.validate();
frame.setBackground(WHITE);
frame.addKeyListener(this);
frame.setTitle("GUI");
frame.setContentPane(this);
frame.setVisible(true);
frame.createBufferStrategy(2);
Timer t = new Timer(100,this);
t.setActionCommand("Draw");
t.start();
repaint();
}
public JMenuBar createMenuBar()
{
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
JMenuItem save = new JMenuItem("Save");
save.setMnemonic(KeyEvent.VK_S);
save.setContentAreaFilled(false);
save.setOpaque(false);
save.addActionListener(this);
JMenuItem load = new JMenuItem("Load");
load.setMnemonic(KeyEvent.VK_L);
load.setContentAreaFilled(false);
load.setOpaque(false);
load.addActionListener(this);
JMenuItem quit = new JMenuItem("Quit");
quit.setMnemonic(KeyEvent.VK_Q);
quit.setContentAreaFilled(false);
quit.setOpaque(false);
quit.addActionListener(this);
fileMenu.add(save);
fileMenu.add(load);
fileMenu.addSeparator();
fileMenu.add(quit);
fileMenu.setContentAreaFilled(false);
fileMenu.setBorderPainted(false);
fileMenu.setOpaque(false);
JMenu editMenu = new JMenu("Edit");
JMenuItem undo = new JMenuItem("Undo");
undo.setMnemonic(KeyEvent.VK_U);
undo.setContentAreaFilled(false);
undo.setOpaque(false);
undo.addActionListener(this);
JMenuItem redo = new JMenuItem("Redo");
redo.setMnemonic(KeyEvent.VK_R);
redo.setContentAreaFilled(false);
redo.setOpaque(false);
redo.addActionListener(this);
editMenu.add(undo);
editMenu.add(redo);
editMenu.setContentAreaFilled(false);
editMenu.setBorderPainted(false);
editMenu.setOpaque(false);
JMenu helpMenu = new JMenu("Help");
JMenuItem controls = new JMenuItem("Controls");
controls.setMnemonic(KeyEvent.VK_C);
controls.setContentAreaFilled(false);
controls.setOpaque(false);
controls.addActionListener(this);
JMenuItem about = new JMenuItem("About");
about.setMnemonic(KeyEvent.VK_A);
about.setContentAreaFilled(false);
about.setOpaque(false);
about.addActionListener(this);
helpMenu.add(controls);
helpMenu.addSeparator();
helpMenu.add(about);
helpMenu.setContentAreaFilled(false);
helpMenu.setBorderPainted(false);
helpMenu.setOpaque(false);
menuBar.add(fileMenu);
menuBar.add(editMenu);
menuBar.add(helpMenu);
return menuBar;
}
public void paintComponent(Graphics g)
{
g.clearRect(0, 0, 1020, 770);
g.setColor(BLACK);
g.fillRect(x,y,100,100);
g.setColor(RED);
g.fillRect(x1,y1,50,50);
g.setColor(BLUE);
g.fillRect(x2,y2,25,25);
g.dispose();
}
public void change()
{
if(x1>=x+50&&changeY==0&&changeX==1)
{
changeX=0;
changeY=1;
}
else if(y1>=y+50&&changeX==0&&changeY==1)
{
changeX=-1;
changeY=0;
}
else if(x1<=x&&changeX==-1&&changeY==0)
{
changeX=0;
changeY=-1;
}
else if(y1<=y&&changeY==-1&&changeX==0)
{
changeX=1;
changeY=0;
}
x1+=changeX*5;
y1+=changeY*5;
}
public void change2()
{
if(x2>=x1+25&&changeY2==0&&changeX2==1)
{
changeX2=0;
changeY2=1;
}
else if(y2>=y1+25&&changeX2==0&&changeY2==1)
{
changeX2=-1;
changeY2=0;
}
else if(x2<=x1&&changeX2==-1&&changeY2==0)
{
changeX2=0;
changeY2=-1;
}
else if(y2<=y1&&changeY2==-1&&changeX2==0)
{
changeX2=1;
changeY2=0;
}
x2+=changeX2*2;
y2+=changeY2*2;
}
public void actionPerformed(ActionEvent e)
{
if(e.getActionCommand().equalsIgnoreCase("Draw"))
{
r.runFinalization();
r.gc();
change();
change2();
repaint();
}
}
public void keyPressed(KeyEvent e)
{
if(e.getKeyCode()==KeyEvent.VK_UP)
{
if(y-10>=0)
{
y-=10;
y1-=10;
y2-=10;
}
}
if(e.getKeyCode()==KeyEvent.VK_DOWN)
{
if(y+110<=getHeight())
{
y+=10;
y1+=10;
y2+=10;
}
}
if(e.getKeyCode()==KeyEvent.VK_LEFT)
{
if(x-10>=0)
{
x-=10;
x1-=10;
x2-=10;
}
}
if(e.getKeyCode()==KeyEvent.VK_RIGHT)
{
if(x+110<=getWidth())
{
x+=10;
x1+=10;
x2+=10;
}
}
repaint();
}
public void keyReleased(KeyEvent e)
{
}
public void keyTyped(KeyEvent e)
{
}
}
You are not constructing on the EDT. An instance of javax.swing.Timer makes this easy, as the action event handler executes on the EDT.
Addendum 1: You may decide you need double buffering, but first compare the code below to yours and see. If you go that route, you might look at this tutorial.
Addendum 2: The example below shows how to maintain an offscreen buffer, but it is sometimes easier to use the JPanel(boolean isDoubleBuffered) constructor for a similar effect.
import java.awt.event.KeyAdapter;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import static java.awt.Color.*;
/** #see http://stackoverflow.com/questions/2114455 */
public class GUI extends JPanel implements ActionListener {
int x, y, x1, y1, x2, y2, changeY, changeY2;
int changeX = 1; int changeX2 = 1;
Timer t = new Timer(100, this);
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
new GUI(true).display();
}
});
}
public GUI(boolean doubleBuffered) {
super(doubleBuffered);
this.setPreferredSize(new Dimension(320, 240));
}
private void display() {
JFrame frame = new JFrame("GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.addKeyListener(new KeyListener());
frame.add(this);
frame.pack();
frame.setVisible(true);
t.start();
}
#Override
public void paintComponent(Graphics g) {
g.setColor(WHITE);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(BLACK);
g.fillRect(x, y, 100, 100);
g.setColor(RED);
g.fillRect(x1, y1, 50, 50);
g.setColor(BLUE);
g.fillRect(x2, y2, 25, 25);
}
public void change() {
if (x1 >= x + 50 && changeY == 0 && changeX == 1) {
changeX = 0;
changeY = 1;
} else if (y1 >= y + 50 && changeX == 0 && changeY == 1) {
changeX = -1;
changeY = 0;
} else if (x1 <= x && changeX == -1 && changeY == 0) {
changeX = 0;
changeY = -1;
} else if (y1 <= y && changeY == -1 && changeX == 0) {
changeX = 1;
changeY = 0;
}
x1 += changeX * 5;
y1 += changeY * 5;
}
public void change2() {
if (x2 >= x1 + 25 && changeY2 == 0 && changeX2 == 1) {
changeX2 = 0;
changeY2 = 1;
} else if (y2 >= y1 + 25 && changeX2 == 0 && changeY2 == 1) {
changeX2 = -1;
changeY2 = 0;
} else if (x2 <= x1 && changeX2 == -1 && changeY2 == 0) {
changeX2 = 0;
changeY2 = -1;
} else if (y2 <= y1 && changeY2 == -1 && changeX2 == 0) {
changeX2 = 1;
changeY2 = 0;
}
x2 += changeX2 * 2;
y2 += changeY2 * 2;
}
#Override
public void actionPerformed(ActionEvent e) {
change();
change2();
repaint();
}
private class KeyListener extends KeyAdapter {
#Override
public void keyPressed(KeyEvent e) {
int d = 5;
if (e.getKeyCode() == KeyEvent.VK_UP) {
if (y - d >= 0) {
y -= d;
y1 -= d;
y2 -= d;
}
}
if (e.getKeyCode() == KeyEvent.VK_DOWN) {
if (y + 100 + d <= getHeight()) {
y += d;
y1 += d;
y2 += d;
}
}
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
if (x - d >= 0) {
x -= d;
x1 -= d;
x2 -= d;
}
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
if (x + 100 + d <= getWidth()) {
x += d;
x1 += d;
x2 += d;
}
}
}
}
}
I would take a look at double buffering. Basically, you draw to an offscreen graphics object and then draw the offscreen graphics object onto the JPanel's graphics object.
~Bolt

Categories