Java having a image reappear once off screen - java

I am kind of stuck on this issue.
Basically I have a car image that I need to have go back to the start point once it disappers off the screen on the x axis. I thought I had it fixed by my checkOFFscreen but it did not work so I am suck and asking for some guidance on how to solve this.
Mainpanel.java
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.Timer;
public class MainPanel extends JPanel {
Player myPlayer;
Player myOtherPlayer;
private int WIDTH = 1000;
private int HEIGHT = 1000;
private int WALLWIDTH = 100;
private int WALLHEIGHT = 100;
private ArrayList<Wall> walls = new ArrayList<Wall>();
Timer myTimer = new Timer(500, new timerListener());
JLabel myTimeLabel;
int time =1;
public MainPanel()
{
setPreferredSize(new Dimension(WIDTH,HEIGHT));
JLabel myLabel= new JLabel ("Game ends once 30 seconds is receahed:");
myLabel.setFont(new Font("Serif", Font.BOLD,32));
myLabel.setForeground(Color.WHITE);
myTimeLabel= new JLabel (Integer.toString(time));
myTimeLabel.setFont(new Font("Serif", Font.BOLD,32));
myTimer.start();
add(myLabel);
add(myTimeLabel);
myPlayer = new Player(0,100, "toad.png", KeyEvent.VK_UP, KeyEvent.VK_DOWN, KeyEvent.VK_LEFT, KeyEvent.VK_RIGHT,this, 50, 38);
myOtherPlayer = new Player(200,200, "toad.png", KeyEvent.VK_W, KeyEvent.VK_S, KeyEvent.VK_A, KeyEvent.VK_D,this, 50, 38);
createWalls();
}
public ArrayList<Wall> getWalls() {
return walls;
}
public void createWalls()
{
int j = 0;
for(int i = 0; i < HEIGHT/WALLHEIGHT; i++)
{
for(int k = 0; k < WIDTH/WALLWIDTH; k++)
{
if(i == 0 || i == (HEIGHT/WALLHEIGHT-1))
{
walls.add(new Wall(k*WALLWIDTH,j,"road.png", 100, 100));
}
}
j+=WALLHEIGHT;
}
}
private class timerListener implements ActionListener
{
public void actionPerformed(ActionEvent e) {
time++;
myTimeLabel.setText(Integer.toString(time));
myTimeLabel.setForeground(Color.WHITE);
if(time >= 30)
{
myTimer.stop();
}
repaint();
}
}
public void paintComponent(Graphics page)
{
super.paintComponent(page);
page.drawImage(myPlayer.getImageIcon().getImage(), myPlayer.getX(), myPlayer.getY(), null);
page.drawImage(myOtherPlayer.getImageIcon().getImage(), myOtherPlayer.getX(), myOtherPlayer.getY(), null);
for(int i = 0; i < walls.size(); i++)
{
page.drawImage(walls.get(i).getImageIcon().getImage(), walls.get(i).getX(), walls.get(i).getY(), null);
}
page.setFont(new Font("Arial", Font.PLAIN,32));
page.drawString("Player 1 Score: " + myPlayer.getScore(), 100, 800);
page.drawString("Player 2 Score: " + myOtherPlayer.getScore(), 100, 850);
if(time > 30)
{
page.drawString("GAME OVER", WIDTH/2-100, HEIGHT/2);
JOptionPane.showMessageDialog(null, "Please enter your email");
}
}
}
Player.java
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import javax.swing.ImageIcon;
public class Player extends GameObject implements KeyListener{
private int Up;
private int Down;
private int Left;
private int Right;
private MainPanel myPanel;
private Movement myMovement = new Movement();
private int score = 0;
public Player(int x, int y, String imagePath, int Up, int Down, int Left, int Right, MainPanel myPanel, int HEIGHT, int WIDTH)
{
super(x,y,imagePath, HEIGHT, WIDTH);
this.Up = Up;
this.Down = Down;
this.Left = Left;
this.Right = Right;
this.myPanel = myPanel;
myPanel.addKeyListener(this);
myPanel.setFocusable(true);
checkOffScreen();
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public void checkOffScreen(){
if (x >=1050){
x=0;
}
}
public int getScore()
{
return score;
}
#Override
public void keyPressed(KeyEvent arg0) {
// TODO Auto-generated method stub
int key = arg0.getKeyCode();
if(key == Left)
{
x-=myMovement.getDistanceLeft();
if(checkWalls())
{
x+=10;
}
}
else if(key == Right)
{
x+=myMovement.getDistanceRight();
if(checkWalls())
{
x-=10;
}
}
myPanel.repaint();
}
public boolean checkWalls()
{
ArrayList<Wall> walls = myPanel.getWalls();
for(int i = 0 ; i < walls.size(); i++)
{
if(areRectsColliding(x,x+HEIGHT,y,y+WIDTH,walls.get(i).getX(), walls.get(i).getX()+ walls.get(i).getHEIGHT(),
walls.get(i).getY(),walls.get(i).getY()+walls.get(i).getWIDTH()))
{
return true;
}
}
return false;
}
#Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
private boolean areRectsColliding(int r1TopLeftX, int r1BottomRightX,
int r1TopLeftY, int r1BottomRightY, int r2TopLeftX,
int r2BottomRightX, int r2TopLeftY, int r2BottomRightY) {
if (r1TopLeftX < r2BottomRightX && r1BottomRightX > r2TopLeftX
&& r1TopLeftY < r2BottomRightY && r1BottomRightY > r2TopLeftY) {
return true;
} else {
return false;
}
}
#Override
public ImageIcon getImageIcon() {
// TODO Auto-generated method stub
return new ImageIcon(imagePath);
}
}

checkOffScreen looks like it's in your initialization of the player, not the main loop of the game. You need to check the x when you repaint, just like when you're moving the image of the car, every time you call to move the image of the car, you need to check your x axis after it's been moved.
Pseudo code
Player.checkOffScreen();
myPanel.repaint();
This should move the car back to the beginning after it's reached the parameters given.

Related

Inconsistent movement in JFrame

I am trying to built psuedo-galaga and I want consistent movement of my JComponents. They are laid out in a null layout, custom JPanel within a custom JFrame container. When I move my character, the speed of the bullets changes - by using the timer I am trying to limit the frame rate so that they move consistently but that has not worked.
Why does my code slow down when the user is moving? I feel like it is a focus subsystem issue or that I should maybe be using multiple threads?
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
#SuppressWarnings("serial")
public class Frame extends JFrame {
private Dimension dimension;
private final int WIDTH, HEIGHT;
private JPanel screen;
public Frame(int width, int height) {
WIDTH = width;
HEIGHT = height;
dimension = new Dimension(WIDTH, HEIGHT);
this.setPreferredSize(dimension);
this.setResizable(false);
this.setMinimumSize(dimension);
this.setMaximumSize(dimension);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
this.setVisible(true);
this.setTitle("Galaga");
this.setBackground(Color.black);
this.setForeground(Color.white);
screen = new LevelOneScreen(dimension);
this.getContentPane().add(screen);
screen.requestFocus();
screen.requestFocusInWindow();
}
public void display() {
this.pack();
this.setVisible(true);
this.repaint();
if(screen instanceof LevelOneScreen && ((LevelOneScreen) screen).isDone()) {
this.dispatchEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING));
}
}
}
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import javax.swing.JPanel;
#SuppressWarnings("serial")
public class LevelOneScreen extends JPanel {
public static ArrayList<LevelOneBullet> enemyBullets;
private ArrayList<LevelOneEnemy> enemies;
private boolean direction;
private Dimension dimension;
private User user;
private int score;
private boolean isDone;
public LevelOneScreen(Dimension dimension) {
this.dimension = dimension;
isDone = false;
enemies = new ArrayList<LevelOneEnemy>();
enemyBullets = new ArrayList<LevelOneBullet>();
direction = true;
this.setLayout(null);
setBackground(Color.BLACK);
createEnemies();
createUser();
user.requestFocusInWindow();
user.requestFocus();
score = 0;
this.setSize(dimension);
this.setVisible(true);
}
private void createUser() {
user = new User((int) (dimension.getWidth() / 2), (int) (dimension.getHeight() - 100));
user.setVisible(true);
this.add(user);
}
private void createEnemies() {
BufferedImage img = null;
try {
img = ImageIO.read(new File("Enemy1.png"));
} catch (IOException e) {
System.out.println("Error Reading \"Enemy1.png\"");
}
// dimension.width
for (int i = 0; i < 15; i++) {
enemies.add(new LevelOneEnemy(i * 40 + 5, 30, img));
enemies.get(i).setVisible(true);
}
for (LevelOneEnemy e : enemies) {
this.add(e);
}
}
private void paintEnemies(Graphics g) {
for (LevelOneEnemy e : enemies) {
e.paint(g);
if (!direction)
e.setLocation(e.getX() - 1, e.getY());
else
e.setLocation(e.getX() + 1, e.getY());
}
if (enemies.get(enemies.size() - 1).getX() + 45 > dimension.getWidth() && direction) {
direction = false;
} else if (enemies.get(0).getX() < 5 && !direction) {
direction = true;
}
}
private void paintCollisionObjects(Graphics g) {
if (!enemies.isEmpty()) {
paintEnemies(g);
// check for bullet collision
if (!user.getBullets().isEmpty()) {
for (int i = enemies.size() - 1; i >= 0; i--) {
for (int j = user.getBullets().size() - 1; j >= 0; j--) {
if (enemies.get(i).getBounds().intersects(user.getBullets().get(j).getBounds())) {
this.remove(enemies.get(i));
enemies.remove(i);
user.getBullets().remove(j);
score += 100;
// To prevent ArrayOutOfBoundsException when
// Enemies are destroyed faster than they're removed
if (enemies.size() == 0)
break;
}
}
}
}
// check for user collision
if (!enemies.isEmpty()) {
for (int i = enemies.size() - 1; i >= 0; i--) {
if (enemies.get(i).getBounds().intersects(user.getBounds())) {
enemies.get(i).setLocation(0, getParent().getHeight() + 100);
this.remove(enemies.get(i));
enemies.remove(i);
user.decrementHealth();
score += 100;
}
}
}
if (!enemyBullets.isEmpty()) {
for (int i = enemyBullets.size() - 1; i >= 0; i--) {
enemyBullets.get(i).paint(g);
if (enemyBullets.get(i).getY() > getParent().getHeight() + 50) {
enemyBullets.remove(i);
} else if (enemyBullets.get(i).getBounds().intersects(user.getBounds())) {
enemyBullets.remove(i);
user.decrementHealth();
}
}
}
}
}
public void paintComponent(Graphics g) {
this.requestFocusInWindow();
super.paintComponent(g);
user.paintComponent(g);
paintCollisionObjects(g);
if(!isDone && enemies.isEmpty())
isDone = true;
}
public boolean isDone() {
return isDone;
}
public boolean isDead() {
return user.healthPercent() < .1;
}
public int getScore() {
return score;
}
public double getHealth() {
return user.healthPercent();
}
public String toString() {
String s = "Level One Screen\n";
for (int i = 0; i < this.getComponentCount(); i++) {
s = s + this.getComponent(i) + "\n";
}
return s;
}
}
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JComponent;
#SuppressWarnings("serial")
public class LevelOneBullet extends JComponent {
private Image img;
private int dy;
public LevelOneBullet(int x, int y, boolean isEnemy) {
BufferedImage img = null;
try {
if(isEnemy)
img = ImageIO.read(new File("EnemyLaserShot.png"));
else
img = ImageIO.read(new File("UserLaserShot.png"));
} catch (IOException e) {
if(isEnemy)
System.out.println("Error Reading \"EnemyLaserShot.png\"");
else
System.out.println("Error Reading \"UserLaserShot.png\"");
}
this.img = img;
super.setLocation(x, y);
this.setVisible(true);
this.setBounds(x, y, 16, 30);
dy = isEnemy ? 3 : -3;
}
public void paint(Graphics g) {
g.drawImage(img, super.getX(), super.getY(), 16, 30, null);
//super.setLocation(super.getX(), super.getY() + dy);
this.setBounds(super.getX(), super.getY()+dy, 16, 30);
}
public String toString() {
return "LevelOneBullet: #" + super.getX() + ", " +super.getY();
}
}
import java.awt.Graphics;
import java.awt.Image;
import java.util.Random;
import javax.swing.JComponent;
#SuppressWarnings("serial")
public class LevelOneEnemy extends JComponent {
private Image im;
private int health;
private int shootSeed;
private long time;
private long lastTimeFired;
public LevelOneEnemy(int x, int y, Image im, int health) {
Random rand = new Random();
super.setBounds(x, y, 30, 30);
super.setLocation(x, y);
this.im = im;
this.health = health;
shootSeed = rand.nextInt(1000)+5000;
time = System.currentTimeMillis();
lastTimeFired = 0;
}
public LevelOneEnemy(int x, int y, Image im) {
Random rand = new Random();
super.setBounds(x, y, 30, 30);
super.setLocation(x, y);
this.im = im;
this.health = 100;
shootSeed = rand.nextInt(1000)+6000;
time = System.currentTimeMillis();
lastTimeFired = 0;
}
public LevelOneEnemy(int x, int y, Image im, boolean isLevelOne) {
Random rand = new Random();
super.setBounds(x, y, 30, 30);
super.setLocation(x, y);
this.im = im;
this.health = 100;
shootSeed = rand.nextInt(1000)+6000;
time = System.currentTimeMillis();
lastTimeFired = 0;
}
public void paint(Graphics g) {
if((System.currentTimeMillis()-time) % shootSeed < (shootSeed/30) &&
System.currentTimeMillis() - lastTimeFired > 5000) {
LevelOneScreen.enemyBullets.add(new LevelOneBullet(this.getX()+15, this.getY()+10, true));
lastTimeFired = System.currentTimeMillis();
}
g.drawImage(im, super.getX(), super.getY(), 30, 30, null);
}
public int getHealth() {
return health;
}
public String toString() {
return "LevelOneEnemy #(" + this.getX() + ", " + this.getY() + ")";
}
}
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
public class Runner {
public final static int SCREENHEIGHT = 1000;
public final static int SCREENWIDTH = 800;
private static Frame frame;
public static void main(String[] args) {
frame = new Frame(SCREENWIDTH, SCREENHEIGHT);
FrameRateListener listen = new FrameRateListener();
Timer timer = new Timer(34, listen);
timer.start();
}
private static class FrameRateListener implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
frame.display();
}
}
}
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
public class UserKeyboardListener implements KeyListener {
private int dx, dy;
private int shoot;
private int speed;
private ArrayList<Integer> keysPressed;
public UserKeyboardListener() {
keysPressed = new ArrayList<Integer>();
shoot = 0;
speed = 1;
}
#Override
public void keyTyped(KeyEvent e) {
}
public int getdx() {
return dx;
}
public int getdy() {
return dy;
}
public int getShoot() {
return shoot;
}
public boolean decrementShoot() {
if (shoot - 1 < 0) {
return false;
} else {
shoot = shoot - 1;
return true;
}
}
#Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_SPACE) {
} else {
if (!keysPressed.contains(key))
keysPressed.add(key);
if(keysPressed.contains(KeyEvent.VK_C))
speed = 2;
else
speed = 1;
if (keysPressed.contains(KeyEvent.VK_RIGHT) && keysPressed.contains(KeyEvent.VK_LEFT)) {
dx = 0;
} else if (keysPressed.contains(KeyEvent.VK_RIGHT)) {
dx = 1*speed;
} else if (keysPressed.contains(KeyEvent.VK_LEFT)) {
dx = -1*speed;
} else {
dx = 0;
}
if (keysPressed.contains(KeyEvent.VK_UP) && keysPressed.contains(KeyEvent.VK_DOWN)) {
dy = 0;
} else if (keysPressed.contains(KeyEvent.VK_UP)) {
dy = -1*speed;
} else if (keysPressed.contains(KeyEvent.VK_DOWN)) {
dy = 1*speed;
} else {
dy = 0;
}
}
}
#Override
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_SPACE) {
shoot++;
} else {
if (keysPressed.contains(key))
keysPressed.remove(keysPressed.indexOf(key));
if(keysPressed.contains(KeyEvent.VK_C))
speed = 2;
else
speed = 1;
if (keysPressed.contains(KeyEvent.VK_RIGHT) && keysPressed.contains(KeyEvent.VK_LEFT)) {
dx = 0;
} else if (keysPressed.contains(KeyEvent.VK_RIGHT)) {
dx = 1*speed;
} else if (keysPressed.contains(KeyEvent.VK_LEFT)) {
dx = -1*speed;
} else {
dx = 0;
}
if (keysPressed.contains(KeyEvent.VK_UP) && keysPressed.contains(KeyEvent.VK_DOWN)) {
dy = 0;
} else if (keysPressed.contains(KeyEvent.VK_UP)) {
dy = -1*speed;
} else if (keysPressed.contains(KeyEvent.VK_DOWN)) {
dy = 1*speed;
} else {
dy = 0;
}
}
}
public String toString() {
return "UserKeyListener: (" + dx + ", " + dy + ")";
}
}
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import javax.imageio.ImageIO;
import javax.swing.JComponent;
#SuppressWarnings("serial")
public class User extends JComponent {
private Image im;
private double health;
private double initialHealth;
private double healthDecrement;
private double stamina;
private int staminaDecrement;
private long lastBulletFired;
private ArrayList<LevelOneBullet> bullets;
public User(int x, int y, double health) {
BufferedImage img = null;
try {
img = ImageIO.read(new File("UserShip.png"));
} catch (IOException e) {
System.out.println("Error Reading \"UserShip.png\"");
}
bullets = new ArrayList<LevelOneBullet>();
super.setLocation(x, y);
super.setBounds(x, y, 50, 50);
this.addKeyListener(new UserKeyboardListener());
this.im = img;
this.health = 100 * health;
this.initialHealth = 100;
this.healthDecrement = 100/5.0;
this.stamina = 100;
this.staminaDecrement = 10;
this.setFocusable(true);
}
public User(int x, int y) {
BufferedImage img = null;
try {
img = ImageIO.read(new File("UserShip.png"));
} catch (IOException e) {
System.out.println("Error Reading \"UserShip.png\"");
}
bullets = new ArrayList<LevelOneBullet>();
super.setLocation(x, y);
super.setBounds(x, y, 50, 50);
this.addKeyListener(new UserKeyboardListener());
this.im = img;
this.health = 100;
this.initialHealth = 100;
this.healthDecrement = health/5.0;
this.stamina = 100;
this.staminaDecrement = 10;
this.setFocusable(true);
}
public void paintComponent(Graphics g) {
this.requestFocus();
this.requestFocusInWindow();
if (this.getKeyListeners().length > 0 &&
this.getKeyListeners()[0] instanceof UserKeyboardListener) {
UserKeyboardListener listen = (UserKeyboardListener) this.getKeyListeners()[0];
if(listen.getdx() != 0) {
if(this.getX()+listen.getdx() + this.getWidth() < this.getParent().getWidth() &&
this.getX()+listen.getdx() > 5)
this.setLocation(this.getX() + listen.getdx(), this.getY());
if(this.getX() < 10) {
this.setLocation(10, this.getY());
}
else if(this.getX()+this.getWidth() > this.getParent().getWidth() - 10)
this.setLocation(this.getParent().getWidth()-10-this.getWidth(), this.getY());
}
if(listen.getdy() != 0) {
if(this.getY() + listen.getdy() > 30 &&
this.getY()+this.getHeight()+listen.getdy() < this.getParent().getHeight()-10)
this.setLocation(this.getX(), this.getY()+listen.getdy());
if(this.getY() < 30) {
this.setLocation(30, this.getY());
}
else if(this.getY()+this.getHeight() > this.getParent().getHeight()-10)
this.setLocation(this.getX(), this.getParent().getHeight()-10-this.getHeight());
}
if (listen.getShoot() > 0 && stamina > 10) {
bullets.add(new LevelOneBullet(super.getX() + 17, super.getY() - 5, false));
decrementStamina();
listen.decrementShoot();
lastBulletFired = System.currentTimeMillis();
}
}
for (int i = bullets.size() - 1; i >= 0; i--) {
bullets.get(i).paint(g);
if (bullets.get(i).getY() < -50)
bullets.remove(i);
}
if(System.currentTimeMillis() - lastBulletFired > 1000 && stamina < 100) {
stamina += .5;
}
g.drawImage(im, super.getX(), super.getY(), this.getWidth(), this.getHeight(), null);
}
public double healthPercent() {
return health/initialHealth;
}
public void decrementHealth() {
health -= healthDecrement;
}
public double staminaPercent() {
return stamina / 100.0;
}
public void decrementStamina() {
stamina -= staminaDecrement;
}
public String toString() {
return "User: " + "(" + super.getX() + ", " + super.getY() + ")";
}
public ArrayList<LevelOneBullet> getBullets() {
return bullets;
}
}
The issue came from what #VGR said, updating components position in the paintComponents(..) method. This should be done from another method that is called when the timer's action occurs. This then updates the positions of the JComponents based off of when they should be refreshed from the timer rather than when paintComponents(..) is called - which we do not have control over.

Java.awt Affine Transform doesn't seem to update image location

I am trying to make a chess game in java, by having a class of pieces and a subclass for each piece. However, When I try to draw the pieces, The position doesn't seem to register.
Here is my Piece class:
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.geom.AffineTransform;
import java.net.URL;
public class Piece {
public int Id;
public int color;
public int state;
public Image Sprite;
public AffineTransform tx;
public boolean dragged;
public int x;
public int y;
public Piece(int Id, int color, int position){
dragged = false;
this.Id = Id;
this.color = color;
int x = 100*(position % 8);
int y = 100*(position / 8);
System.out.println(x);
tx = AffineTransform.getTranslateInstance(x, y);
init(x, y);
}
private void init (double a, double b) {
tx.setToTranslation(a, b);
tx.scale(0.1, 0.1);
}
private void update(){
tx.setToTranslation(x*1000, y*1000);
tx.scale(0.1, 0.1);
}
protected Image getImage(String path) {
Image tempImage = null;
try {
URL imageURL = Piece.class.getResource(path);
tempImage = Toolkit.getDefaultToolkit().getImage(imageURL);
} catch (Exception e) {e.printStackTrace();}
return tempImage;
}
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
update();
g2.drawImage(Sprite, tx, null);
}
}
my pawn class:
public class Pawn extends Piece {
public Pawn(int Id, int color, int position) {
super(Id, color, position);
this.state = 0;
String path = "/imgs/Pieces/";
if(color == 0){
path += "W";
} else{
path += "B";
}
path += "_Pawn.png";
Sprite = getImage(path);
}
}
my Board class:
Piece[][] board;
public Board(){
board = new Piece[8][8];
for(int i = 0; i < 8; i++){
board[1][i] = new Pawn(i, 1, 8+i);
}
for(int i = 0; i < 8; i++){
board[6][i] = new Pawn(i, 0, 8+i);
}
}
}
and my main class:
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Main extends JPanel implements ActionListener, MouseListener, KeyListener{
Color GREEN = new Color( 41, 176, 59);
Color WHITE = new Color(254, 255, 228);
Board board = new Board();
public static void main(String[] args) {
new Main();
}
public void paint(Graphics g){
super.paintComponent(g);
boolean flag = true;
for(int i = 0; i < 8; i++){
for(int j = 0; j < 8; j++){
if(flag){
g.setColor(WHITE);
} else{
g.setColor(GREEN);
}
g.fillRect((j*100), (i*100), ((j+1)*100), ((i+1)*100));
flag = !flag;
}
flag = !flag;
}
for(int i = 0; i < 8; i++){
for(int j = 0; j < 8; j++){
if(board.board[i][j] != null){
board.board[i][j].paint(g);
}
}
}
}
public Main() {
JFrame f = new JFrame("Chess");
f.setSize(new Dimension(800, 800));
f.setBackground(Color.blue);
f.add(this);
f.setResizable(false);
f.setLayout(new GridLayout(1,2));
f.addMouseListener(this);
f.addKeyListener(this);
Timer t = new Timer(16, this);
t.start();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
}
I had previously written a game that implemented this techqnique, so I'm not sure what could have gone wrong with this one
It's really important to read the documentation, especially for something that is (to my simple brain), complicated.
If you have a read of the documentation for AffineTransform#scale
Concatenates this transform with a scaling transformation
(emphis added by me)
This is important, as it seems to apply that each time you call it, it will apply ANOTHER scaling operation.
Based on your avaliable code, this means that when the Piece is created, a scale is applied and the each time it's painted, a new scale is applied, until you're basically scaled out of existence.
Sooo. I took out your init (applied the scale within the constructor directly instead) and update methods and was able to get a basic result
Scaling from 1.0, 0.75, 0.5, 0.25and0.1` (it's there but I had to reduce the size of the output)
Runnable example...
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
JFrame frame = new JFrame();
frame.add(new Main());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
}
public class Main extends JPanel implements ActionListener, MouseListener, KeyListener {
Color GREEN = new Color(41, 176, 59);
Color WHITE = new Color(254, 255, 228);
Board board;
public Main() throws IOException {
board = new Board();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(800, 800);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
super.paintComponent(g);
boolean flag = true;
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if (flag) {
g.setColor(WHITE);
} else {
g.setColor(GREEN);
}
g.fillRect((j * 100), (i * 100), ((j + 1) * 100), ((i + 1) * 100));
flag = !flag;
}
flag = !flag;
}
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
if (board.board[i][j] != null) {
board.board[i][j].paint(g);
}
}
}
}
#Override
public void actionPerformed(ActionEvent e) {
}
#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) {
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
}
}
public class Board {
Piece[][] board;
public Board() throws IOException {
board = new Piece[8][8];
for (int i = 0; i < 8; i++) {
board[1][i] = new Pawn(i, 1, 8 + i);
}
for (int i = 0; i < 8; i++) {
board[6][i] = new Pawn(i, 0, 16 + i);
}
}
}
public class Pawn extends Piece {
public Pawn(int Id, int color, int position) throws IOException {
super(Id, color, position);
this.state = 0;
String path = "/imgs/Pieces/";
if (color == 0) {
path += "W";
} else {
path += "B";
}
path += "_Pawn.png";
Sprite = getImage(path);
}
}
public class Piece {
public int Id;
public int color;
public int state;
public Image Sprite;
public AffineTransform tx;
public boolean dragged;
public int x;
public int y;
public Piece(int Id, int color, int position) {
dragged = false;
this.Id = Id;
this.color = color;
x = 100 * (position % 8);
y = 100 * (position / 8);
System.out.println(x + "x" + y);
tx = AffineTransform.getTranslateInstance(x, y);
tx.scale(0.1, 0.1);
}
protected Image getImage(String path) throws IOException {
BufferedImage img = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = img.createGraphics();
g2d.setFont(new JLabel().getFont().deriveFont(Font.PLAIN, 16));
g2d.setColor(Color.BLACK);
FontMetrics fm = g2d.getFontMetrics();
int cellX = x;
int cellY = y;
String text = x + "x" + y;
int x = (100 - fm.stringWidth(text)) / 2;
int y = ((100 - fm.getHeight()) / 2) + fm.getAscent();
g2d.drawString(text, x, y);
g2d.setStroke(new BasicStroke(16));
g2d.drawRect(0, 0, 99, 99);
g2d.dispose();
return img;
}
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
g2.drawImage(Sprite, tx, null);
}
}
}

snake game in java won't detect arrow keys (snake won't respond to input)

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
}
}
}

Space Invaders Alien Array Issue - Java

I am developing a space invaders application for a college assignment and I've come into a problem where the aliens change direction one by one as they hit a wall rather than the whole array of objects switching direction when any alien touches the boundary. I hae a feeling it is an issue in my for loop where my move method containing reverseDirection() method acts on each element individually but I do not know how to fix this and any help would be greatly appreciated. Here is my code for you;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.*;
import javax.swing.*;
import java.awt.image.*;
public class InvadersApplication extends JFrame implements Runnable {//, KeyListener {
private static final Dimension WindowSize = new Dimension(800, 600);
private static final int NUMALIENS = 16;
private Alien AliensArray[] = new Alien[NUMALIENS];
private Image alienImage;
private Image playerImage;
private String workingDirectory = "C:\\Users\\brads\\IdeaProjects\\Assignment3\\src\\workingDirectory\\";
private Player playerShip;
private BufferStrategy strategy;
public InvadersApplication() {
System.out.println(System.getProperty("user.dir"));
setDefaultCloseOperation(EXIT_ON_CLOSE);
Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
int x = screenSize.width / 2 - WindowSize.width / 2;
int y = screenSize.height / 2 - WindowSize.height / 2;
setBounds(x, y, WindowSize.width, WindowSize.height);
this.setTitle("Alien Invaders App");
ImageIcon playerIcon = new ImageIcon(workingDirectory + "player_ship.png");
playerImage = playerIcon.getImage();
ImageIcon alienIcon = new ImageIcon(workingDirectory + "alien_ship_1.png");
alienImage = alienIcon.getImage();
playerShip = new Player(playerImage);
// addKeyListener(this);
setVisible(true);
createBufferStrategy(2);
strategy = getBufferStrategy();
for (int i = 0; i < NUMALIENS; i++) {
AliensArray[i] = new Alien(alienImage);
AliensArray[i].setPosition(70 * (i%4), 70 * (i/4));
AliensArray[i].setXspeed(1);
}
Thread thread1 = new Thread(this);
thread1.start();
repaint();
}
#Override
public void run(){
while(true){
try{
for(int i = 0; i < NUMALIENS; i++) {
AliensArray[i].move();
}
repaint();
Thread.sleep(5);
} catch (Exception e) {
e.printStackTrace();
}
}
}
/* public void keyPressed(KeyEvent e) {
int KeyCode = e.getKeyCode();
if (KeyCode == KeyEvent.VK_LEFT) {
playerShip.movePlayer(-8);
} else if (KeyCode == KeyEvent.VK_RIGHT) {
playerShip.movePlayer(8);
}
}
*/
public void keyReleased(KeyEvent e){
}
public void keyTyped(KeyEvent e){}
public void paint(Graphics g){
g = strategy.getDrawGraphics();
g.setColor(Color.BLACK);
g.fillRect(0,0,800,600);
for(int i=0; i < NUMALIENS; i++){
AliensArray[i].paint(g);
}
// playerShip.paint(g);
//playerShip.paintPlayer(g);
strategy.show();
this.repaint();
}
public static void main(String[] args){
InvadersApplication x = new InvadersApplication();
}
}
Sprite2D class;
public class Sprite2D{
protected int x = 0,y = 30;
protected Image myImage;
public Sprite2D(Image myImage){
this.x = x;
this.y = y;
this.myImage = myImage;
}
public void setPosition(int xx, int yy){
x = xx;
y = yy;
}
public void paint(Graphics g){
g.drawImage(myImage, x,y, null);
}
}
Alien subclass of sprite2D;
import java.awt.*;
import java.util.Random;
import javax.swing.*;
public class Alien extends Sprite2D {
private int xi;
private int xj;
public Alien(Image myImage) {
super(myImage);
this.myImage = myImage;
this.x = x;
this.y = y;
this.xi = xi;
this.xj = xj;
}
// #Override
// public void setPosition(int xx, int yy){
// xx = x;
// yy = y;
//
// }
public void move() {
y+=xj;
x+= xi;
if(x >= 750) {
reverseDirection();
x = x + xi;
}
else if (x < 0)
{
reverseDirection();
x = x + xi;
}
}
public void setXspeed(int xi) {
this.xi = xi;
}
public void setYspeed(int xj) {
this.xj = xj;
}
public void reverseDirection() {
xi = -xi;
System.out.println("reverse");
}
// #Override
// public void paint(Graphics g) {
//
//
// g.drawImage(myImage, xx, yy, null);
// }
}

Java Draw not moving snake

I am trying to create a snake clone just as a practice. ive drawn the snake and added the movement patterns but the snake eats on it self when I press any key to move. but its not moving. the array retracts the reactacles on the starting point and does nothing.
here is my snake class I have removed my comments as they where more than the code and the posting system was not allowing me to post
Edit
If you need anything from the other classes please let me know. but I think my error is somewhere in here
EDIT 2
Added the entire code, you can just copy paste in inside a new project and you will reproduce my error.
public class Snake {
List<Point> sPoints;
int xDir,yDir;
boolean isMoving,addTail;
final int sSize = 20, startX = 150 , startY = 150;
public Snake(){
sPoints = new ArrayList<Point>();
xDir = 0;
yDir = 0;
isMoving = false;
addTail = false;
sPoints.add(new Point(startX,startY));
for(int i=1; i<sSize; i++) {
sPoints.add(new Point(startX - i * 4,startY));
}
}
public void draw(Graphics g){
g.setColor(Color.white);
for(Point p : sPoints) {
g.fillRect(p.getX(),p.getY(),4,4);
}
}
public void move(){
if (isMoving) {
Point temp = sPoints.get(0);
Point last = sPoints.get(sPoints.size() - 1);
Point newstart = new Point(temp.getX() + xDir * 4, temp.getY() + yDir * 4);
for (int i = sPoints.size() - 1; i >= 1; i--) {
sPoints.set(i, sPoints.get(i - 1));
}
sPoints.set(0, newstart);
}
}
public int getxDir() {
return xDir;
}
public void setxDir(int x) {
this.xDir = xDir;
}
public int getyDir() {
return yDir;
}
public void setyDir(int y) {
this.yDir = yDir;
}
public int getX(){
return sPoints.get(0).getX();
}
public int getY(){
return sPoints.get(0).getY();
}
public boolean isMoving() {
return isMoving;
}
public void setIsMoving(boolean b) {
isMoving = b;
}
}
The following is the point class. just some getters setters for the points ,for those i used the IntelliJ to auto generate them.. (again i removed comments )
public class Point {
private int x,y;
public Point() {
x = 0;
y = 0;
}
public Point(int x, int y) {
this.x =x;
this.y =y;
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
and finally my main class called game.
in here what I do is create my applet give it background color. create my threat for the runnable. and also add the movement patterns for up/right/down/left...
and use several classes to update my drawing patterns so it can simulate movement by updating each of state of my rect list.
import java.applet.Applet;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class Game extends Applet implements Runnable, KeyListener {
//setting up double buffering.
Graphics graphics;
Image img;
Thread thread;
Snake snake;
public void init() {
//setting the size of our Applet
this.resize(400,400);
//we gonna create the image just the same size as our applet.
img = createImage(400,400);
//this represents our offscreen image that we will draw
graphics = img.getGraphics();
this.addKeyListener(this);
snake = new Snake();
thread = new Thread(this);
thread.start();
}
public void paint(Graphics g) {
//Setting the background of our applet to black
graphics.setColor(Color.black);
//Fill rectangle 0 , 0 (starts from) for top left corner and then 400,400 to fill our entire background to black
graphics.fillRect(0,0,400,400);
snake.draw(graphics);
//painting the entire image
g.drawImage(img,0,0,null);
}
//Update will call on Paint(g)
public void update(Graphics g){
paint(g);
}
//Repaint will call on Paint(g)
public void repaint(Graphics g){
paint(g);
}
public void run() {
//infinite loop
for(;;) {
snake.move();
//drawing snake
this.repaint();
//Creating a time delay
try {
Thread.sleep(40);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void keyTyped(KeyEvent keyEvent) {
}
public void keyPressed(KeyEvent keyEvent) {
if(!snake.isMoving()){ //this will allow the snake to start moving, but will disable LEFT for just the 1st move
if(keyEvent.getKeyCode() == KeyEvent.VK_UP || keyEvent.getKeyCode() == KeyEvent.VK_RIGHT ||
keyEvent.getKeyCode() == KeyEvent.VK_DOWN ) {
snake.setIsMoving(true);
}
}
//setting up Key mapping so when the user presses UP,RIGHT,DOWN,LEFT. the Snake will move accordingly
if(keyEvent.getKeyCode() == KeyEvent.VK_UP) {
if (snake.getyDir() != 1) {
snake.setyDir(-1);
snake.setxDir(0);
}
}
if(keyEvent.getKeyCode() == KeyEvent.VK_RIGHT) {
if (snake.getxDir() != -1) {
snake.setxDir(1);
snake.setyDir(0);
}
}
if(keyEvent.getKeyCode() == KeyEvent.VK_DOWN) {
if (snake.getyDir() != -1) {
snake.setyDir(1);
snake.setxDir(0);
}
}
if(keyEvent.getKeyCode() == KeyEvent.VK_LEFT) {
if (snake.getxDir() != 1) {
snake.setxDir(-1);
snake.setyDir(0);
}
}
}
public void keyReleased(KeyEvent keyEvent) {
}
}
Here is some opinion I have reading your code.
The reason your snake won't move is because your snake.setyDir() and
snake.setxDir() didn't take the input to overwrite xDir and yDir. They are assigning to itself.
There is a Point2D class ready for you in JDK
When moving the snake, you just need to remove the tail and add one
more block before the head. You can keep the body tight (according
to my common knowledge to snake).
Consider a L shape snake on the left, the bottom end is the head and it is currently heading right. To move the snake, remove the tail (green block) and add one more to the head according to its direction (red block). It final state become the snake on the right. LinkedList suit the needs.
If using two int (xDir and yDir) to control the snake direction
is confusing, you can help your self by creating a enum. Those -1,
0, 1 with x and y may confuse you.
Declare constant instead of magic number. e.g. the width of block 4,
image size 400
Is Snake.addTail unnecessary?
Attribute should has accessibility modifier
End result:
Game.java
import java.applet.Applet;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Arrays;
public class Game extends Applet implements Runnable, KeyListener {
private final int GAMEBOARD_WIDTH = 400;
// setting up double buffering.
private Graphics graphics;
private Image img;
private Thread thread;
private Snake snake;
public void init() {
// setting the size of our Applet
this.resize(GAMEBOARD_WIDTH, GAMEBOARD_WIDTH);
// we gonna create the image just the same size as our applet.
img = createImage(GAMEBOARD_WIDTH, GAMEBOARD_WIDTH);
// this represents our offscreen image that we will draw
graphics = img.getGraphics();
this.addKeyListener(this);
snake = new Snake();
thread = new Thread(this);
thread.start();
}
public void paint(Graphics g) {
// Setting the background of our applet to black
graphics.setColor(Color.BLACK);
// Fill rectangle 0 , 0 (starts from) for top left corner and then 400,400 to
// fill our entire background to black
graphics.fillRect(0, 0, GAMEBOARD_WIDTH, GAMEBOARD_WIDTH);
snake.draw(graphics);
// painting the entire image
g.drawImage(img, 0, 0, null);
}
// Update will call on Paint(g)
public void update(Graphics g) {
paint(g);
}
// Repaint will call on Paint(g)
public void repaint(Graphics g) {
paint(g);
}
public void run() {
// infinite loop
for (;;) {
snake.move();
// drawing snake
this.repaint();
// Creating a time delay
try {
Thread.sleep(40);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void keyTyped(KeyEvent keyEvent) {
}
public void keyPressed(KeyEvent keyEvent) {
int keyCode = keyEvent.getKeyCode();
if (!snake.isMoving()) {
// this will allow the snake to start moving, but will disable LEFT for just the
// 1st move
if (matchKey(keyCode, KeyEvent.VK_UP, KeyEvent.VK_RIGHT, KeyEvent.VK_DOWN)) {
snake.setIsMoving(true);
}
}
// setting up Key mapping so when the user presses UP,RIGHT,DOWN,LEFT. the Snake
// will move accordingly
if (matchKey(keyCode, KeyEvent.VK_UP)) {
snake.setDirection(Direction.UP);
}
if (matchKey(keyCode, KeyEvent.VK_RIGHT)) {
snake.setDirection(Direction.RIGHT);
}
if (matchKey(keyCode, KeyEvent.VK_DOWN)) {
snake.setDirection(Direction.DOWN);
}
if (matchKey(keyCode, KeyEvent.VK_LEFT)) {
snake.setDirection(Direction.LEFT);
}
}
// return true if targetKey contains the provided keyCode
private boolean matchKey(int keyCode, int... targetKey) {
return Arrays.stream(targetKey).anyMatch(i -> i == keyCode);
}
public void keyReleased(KeyEvent keyEvent) {
}
}
Snake.java
import java.awt.Color;
import java.awt.Graphics;
import java.awt.geom.Point2D;
import java.util.LinkedList;
public class Snake {
private final int sSize = 20, startX = 150, startY = 150;
private final int BLOCK_WIDTH = 4;
private LinkedList<Point2D.Float> sPoints;
private boolean isMoving;
private Direction direction;
public Snake() {
sPoints = new LinkedList<Point2D.Float>();
isMoving = false;
sPoints.add(new Point2D.Float(startX, startY));
for (int i = 1; i < sSize; i++) {
sPoints.add(new Point2D.Float(startX - i * BLOCK_WIDTH, startY));
}
}
public void draw(Graphics g) {
g.setColor(Color.white);
for (Point2D p : sPoints) {
g.fillRect((int) p.getX(), (int) p.getY(), BLOCK_WIDTH, BLOCK_WIDTH);
}
}
public void move() {
if (isMoving) {
sPoints.removeLast();
steer(sPoints.getFirst());
}
}
private void steer(Point2D head) {
Point2D.Float newHead = new Point2D.Float();
switch (this.getDirection()) {
case UP:
newHead.setLocation(head.getX(), head.getY() - BLOCK_WIDTH);
break;
case DOWN:
newHead.setLocation(head.getX(), head.getY() + BLOCK_WIDTH);
break;
case LEFT:
newHead.setLocation(head.getX() - BLOCK_WIDTH, head.getY());
break;
case RIGHT:
newHead.setLocation(head.getX() + BLOCK_WIDTH, head.getY());
break;
}
this.sPoints.addFirst(newHead);
}
public int getX() {
return (int) sPoints.get(0).getX();
}
public int getY() {
return (int) sPoints.get(0).getY();
}
public boolean isMoving() {
return isMoving;
}
public void setIsMoving(boolean b) {
isMoving = b;
}
public Direction getDirection() {
return direction;
}
public void setDirection(Direction d) {
if (this.getDirection() == null) {
this.direction = d;
} else if (!this.getDirection().isOpposite(d)) {
this.direction = d;
}
}
}
Direction.java
public enum Direction {
UP(-1), DOWN(1), LEFT(-2), RIGHT(2);
int vector;
Direction(int i) {
this.vector = i;
}
public boolean isOpposite(Direction d) {
return this.vector + d.vector == 0;
}
}
Snack.java
import java.awt.EventQueue;
import javax.swing.JFrame;
public class Snake extends JFrame {
public Snake() {
initUI();
}
private void initUI() {
add(new Board());
setResizable(false);
pack();
setTitle("Snake");
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
JFrame ex = new Snake();
ex.setVisible(true);
});
}
}
Board.java
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Board extends JPanel implements ActionListener {
private final int B_WIDTH = 300;
private final int B_HEIGHT = 300;
private final int DOT_SIZE = 10;
private final int ALL_DOTS = 900;
private final int RAND_POS = 29;
private final int DELAY = 140;
private final int x\[\] = new int\[ALL_DOTS\];
private final int y\[\] = new int\[ALL_DOTS\];
private int dots;
private int apple_x;
private int apple_y;
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 ball;
private Image apple;
private Image head;
public Board() {
initBoard();
}
private void initBoard() {
addKeyListener(new TAdapter());
setBackground(Color.black);
setFocusable(true);
setPreferredSize(new Dimension(B_WIDTH, B_HEIGHT));
loadImages();
initGame();
}
private void loadImages() {
ImageIcon iid = new ImageIcon("src/resources/dot.png");
ball = iid.getImage();
ImageIcon iia = new ImageIcon("src/resources/apple.png");
apple = iia.getImage();
ImageIcon iih = new ImageIcon("src/resources/head.png");
head = iih.getImage();
}
private void initGame() {
dots = 3;
for (int z = 0; z < dots; z++) {
x\[z\] = 50 - z * 10;
y\[z\] = 50;
}
locateApple();
timer = new Timer(DELAY, this);
timer.start();
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
doDrawing(g);
}
private void doDrawing(Graphics g) {
if (inGame) {
g.drawImage(apple, apple_x, apple_y, this);
for (int z = 0; z < dots; z++) {
if (z == 0) {
g.drawImage(head, x\[z\], y\[z\], this);
} else {
g.drawImage(ball, x\[z\], y\[z\], this);
}
}
Toolkit.getDefaultToolkit().sync();
} else {
gameOver(g);
}
}
private void gameOver(Graphics g) {
String msg = "Game Over";
Font small = new Font("Helvetica", Font.BOLD, 14);
FontMetrics metr = getFontMetrics(small);
g.setColor(Color.white);
g.setFont(small);
g.drawString(msg, (B_WIDTH - metr.stringWidth(msg)) / 2, B_HEIGHT / 2);
}
private void checkApple() {
if ((x\[0\] == apple_x) && (y\[0\] == apple_y)) {
dots++;
locateApple();
}
}
private void move() {
for (int z = dots; z > 0; z--) {
x\[z\] = x\[(z - 1)\];
y\[z\] = y\[(z - 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;
}
}
private void checkCollision() {
for (int z = dots; z > 0; z--) {
if ((z > 4) && (x\[0\] == x\[z\]) && (y\[0\] == y\[z\])) {
inGame = false;
}
}
if (y\[0\] >= B_HEIGHT) {
inGame = false;
}
if (y\[0\] < 0) {
inGame = false;
}
if (x\[0\] >= B_WIDTH) {
inGame = false;
}
if (x\[0\] < 0) {
inGame = false;
}
if (!inGame) {
timer.stop();
}
}
private void locateApple() {
int r = (int) (Math.random() * RAND_POS);
apple_x = ((r * DOT_SIZE));
r = (int) (Math.random() * RAND_POS);
apple_y = ((r * DOT_SIZE));
}
#Override
public void actionPerformed(ActionEvent e) {
if (inGame) {
checkApple();
checkCollision();
move();
}
repaint();
}
private class TAdapter extends KeyAdapter {
#Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if ((key == KeyEvent.VK_LEFT) && (!rightDirection)) {
leftDirection = true;
upDirection = false;
downDirection = false;
}
if ((key == KeyEvent.VK_RIGHT) && (!leftDirection)) {
rightDirection = true;
upDirection = false;
downDirection = false;
}
if ((key == KeyEvent.VK_UP) && (!downDirection)) {
upDirection = true;
rightDirection = false;
leftDirection = false;
}
if ((key == KeyEvent.VK_DOWN) && (!upDirection)) {
downDirection = true;
rightDirection = false;
leftDirection = false;
}
}
}
}

Categories

Resources