For some reason, my game will NOT freeze when the level starts, while the menu loads just fine!
The game will freeze when the boss music starts.
EDIT: Sorry, I found out that the screen froze because the canMove variables were stuck to false. But, the game will still randomly crash and say the image can not be found.
Here is my code:
This is the menu (Which works fine):
//Sprite sheeting
private SpriteSheet sleepSpriteSheet;
private Animation sleepAnimation;
private SpriteSheet walkSpriteSheet;
private Animation walkAnimation;
//System info
private String operatingSystem = Client.getOS();
//Game texuring
private static String IntroBackground = "res/images/level/IntroBackground.png";
private static String KnightQuestLogo = "res/images/icons/KnightQuestLogo.png";
//Menu Info
private static boolean readyForIntro = false;
private static boolean readyForPlay = false;
private static boolean showArrow = false;
private static String playButton = Button.PlayButton;
private static boolean playerSleeping = true;
private static boolean knightWalking = false;
private static float knightX = 145;
private static float knightY = 456;
private static float knightQuestLogoX = -750;
private static float knightQuestLogoY = 75;
private static boolean soundStarted = false;
public GameMenu(int State) {
}
// Render the game
#Override
public void render(GameContainer GameContainer, StateBasedGame SBG,
Graphics G) throws SlickException {
//Draw Background Image
G.drawImage(new Image(IntroBackground), 0, 0);
//Choose what animation to use
if(playerSleeping) {
sleepAnimation.draw(145, 406, 250, 250);
}
else {
walkAnimation.draw(knightX, knightY, 175, 200);
}
//Draw Floor
G.drawImage(new Image(Block.GroundTile), 0, 656);
//Draw The Logo
G.drawImage(new Image(KnightQuestLogo), knightQuestLogoX, knightQuestLogoY);
//Draw the Play Button
if(readyForPlay) {
G.drawImage(new Image(playButton), 750, 315);
if(showArrow) {
G.drawImage(new Image(Icon.Arrow), 730, 335);
}
}
//System Info
G.drawString("Game State: " + this.getID(), 10, 30);
G.drawString("X:" + Mouse.getX() + " Y:" + Mouse.getY(), 10, 50);
G.drawString("Your OS: " + operatingSystem, 10, 70);
}
// Update the game
#Override
public void update(GameContainer GameContainer, StateBasedGame SBG,
int Delta) throws SlickException {
//Start Sound (Would be started in init(), But the StopSound function will not work if done so.
if(!soundStarted) {
PlaySound.playSound("res/sounds/startup/MainMenu.wav");
soundStarted = true;
}
//When ready, slide the logo to the right
if (readyForIntro) {
if (knightQuestLogoX < 750.0) {
knightQuestLogoX += Delta * .5f;
}
}
//When ready, allow the player the press the play button
if(readyForPlay) {
if(Mouse.getX() > 755 && Mouse.getX() < 875 && Mouse.getY() > 345 && Mouse.getY() < 400) {
showArrow = true;
if(Mouse.isButtonDown(0)) {
playerSleeping = false;
knightWalking = true;
}
}
else {
showArrow = false;
}
}
//If the knight is walking in the intro, slide him off the screen
if(knightWalking) {
if(knightX < 1290) {
knightX += Delta* .5f;
}
else {
SBG.enterState(1, new FadeOutTransition(new Color(Color.black)), new FadeInTransition(new Color(Color.black)));
PlaySound.stopSound();
PlaySound.playSound("res/sounds/events/LeaveState.wav");
}
}
}
// Initialize the GameState
#Override
public void init(GameContainer GameContainer, StateBasedGame SBG)
throws SlickException {
//Start the thread for the Intro
new Thread(new MenuIntro()).start();
//Create the Sprite sheets
sleepSpriteSheet = new SpriteSheet("res/images/characters/knight/spritesheets/SleepAnimation.png", 52, 50);
sleepAnimation = new Animation(sleepSpriteSheet, 250);
walkSpriteSheet = new SpriteSheet("res/images/characters/knight/spritesheets/WalkAnimation.png", 35, 48);
walkAnimation = new Animation(walkSpriteSheet, 75);
}
// Get the ID of the GameState
#Override
public int getID() {
return 0;
}
// MenuIntro thread
static class MenuIntro implements Runnable {
#Override
public void run() {
try {
Thread.sleep(3000);
readyForIntro = true;
Thread.sleep(4000);
readyForPlay = true;
} catch (Exception e) {
e.printStackTrace();
}
}
}
This is the game level (Which is broken):
//Colors RGB
private static String Grey = "rgb/Grey.png";
private static String Blue = "rgb/Blue.png";
private static String Red = "rgb/Red.png";
// Level Variables
private static boolean stateStarted = false;
private static boolean startBossBattle = false;
private static boolean startedBossBattle = false;
private static boolean startedBossMusic = false;
private static boolean BothTouching = false;
// Player Variables
/* Coordinates, And Direction */
private static float PlayerX = 25;
private static float PlayerY = 470;
private static String Knight = "res/images/characters/knight/Knight.png";
private static String PlayerDirection = "right";
private static int PlayerHealth = 100;
private static boolean PlayerWalking = false;
private static boolean PlayerJumping = false;
private static boolean PlayerJumped = false;
private static float AmountPlayerJumped;
private static boolean PlayerAttacking = false;
private static boolean PlayerCanAttack = true;
private static int PlayerRegenTime = 100;
/* Sprite Sheets */
private static String PlayerLeftSword = "res/images/icons/sword/SwordLeft.png";
private static String PlayerLeftAttackSword = "res/images/icons/sword/SwordLeftAttacking.png";
private static String PlayerRightSword = "res/images/icons/sword/SwordRight.png";
private static String PlayerRightAttackSword = "res/images/icons/sword/SwordRightAttacking.png";
private static String PlayerCurrentSword = PlayerRightSword;
private static String RightKnight = "res/images/characters/knight/ResizedKnightRight.png";
private static String LeftKnight = "res/images/characters/knight/ResizedKnightLeft.png";
/* Everything Else */
private static boolean PlayerCanMove = false;
// AI Variables
/* Coordiantes and Direction */
private static float EnemyX = 1000;
private static float EnemyY = 470;
private static String EnemyKnight = "res/images/characters/knight/Knight.png";
private static String EnemyDirection = "right";
private static int EnemyHealth = 100;
private static boolean EnemyWalking = false;
private static boolean DecidedJump = false;
private static int JumpPossibility = 1;
private static boolean EnemyJumping = false;
private static boolean EnemyJumped = false;
private static float AmountEnemyJumped;
private static boolean EnemyAttacking = false;
private static boolean EnemyCanAttack = true;
private static int EnemyRegenTime = 100;
/* Sprite Sheets */
private static String EnemyLeftSword = "res/images/icons/sword/SwordLeft.png";
private static String EnemyLeftAttackSword = "res/images/icons/sword/SwordLeftAttacking.png";
private static String EnemyRightSword = "res/images/icons/sword/SwordRight.png";
private static String EnemyRightAttackSword = "/res/images/icons/sword/SwordRightAttacking.png";
private static String EnemyCurrentSword = EnemyRightSword;
private static String RightEnemy = "res/images/characters/knight/ResizedKnightRight.png";
private static String LeftEnemy = "res/images/characters/knight/ResizedKnightLeft.png";
/* Everything Else */
private static boolean EnemyTalking = false;
private static String EnemyMessage = "";
private static boolean EnemyCanMove = false;
// Mixed Variables
/* Sprite Sheets */
private static SpriteSheet WalkRightSpriteSheet;
private static Animation WalkRightAnimation;
private static SpriteSheet WalkLeftSprite;
private static Animation WalkLeftAnimation;
private static int SpriteSheetWidth = 135;
private static int SpriteSheetHeight = 188;
// System Variables
private String operatingSystem = Client.getOS();
// Constructor
public FinalBattle(int State) {
}
#Override
public void render(GameContainer GameContainer, StateBasedGame SBG,
Graphics G) throws SlickException {
//GameContainer Things
GameContainer.setShowFPS(false);
//Level
/* Draw Background */
G.drawImage(new Image("res/images/level/FinalBattle.png"), 0, 0);
/* Draw Floor */
G.drawImage(new Image(Block.GroundTile), 0, 656);
//Player
/* Draw Player */
if(PlayerWalking) {
if(PlayerDirection.equalsIgnoreCase("right")) {
if(!PlayerJumping) {
WalkRightAnimation.draw(PlayerX, PlayerY, SpriteSheetWidth, SpriteSheetHeight);
}
else {
G.drawImage(new Image(RightKnight), PlayerX, PlayerY);
}
G.drawImage(new Image(PlayerCurrentSword), PlayerX + 60, PlayerY + 90);
}
if(PlayerDirection.equalsIgnoreCase("left")) {
if(!PlayerJumping) {
WalkLeftAnimation.draw(PlayerX, PlayerY, SpriteSheetWidth, SpriteSheetHeight);
}
else {
G.drawImage(new Image(LeftKnight), PlayerX, PlayerY);
}
G.drawImage(new Image(PlayerCurrentSword), PlayerX + 6, PlayerY + 90);
}
}
/* Draw his/her sword */
else {
if(PlayerDirection.equalsIgnoreCase("right")) {
G.drawImage(new Image(RightKnight), PlayerX, PlayerY);
G.drawImage(new Image(PlayerCurrentSword), PlayerX + 60, PlayerY + 90);
}
if(PlayerDirection.equalsIgnoreCase("left")) {
G.drawImage(new Image(LeftKnight), PlayerX, PlayerY);
G.drawImage(new Image(PlayerCurrentSword), PlayerX + 6, PlayerY + 90);
}
}
/* Draw his/her power level */
G.setColor(new Color(Color.blue.darker()));
G.drawString("Knight Power Level", 10, 20);
G.setColor(new Color(Color.white));
G.drawImage(new Image(Grey).getScaledCopy(100, 10), 10, 40);
G.drawImage(new Image(Blue).getScaledCopy(PlayerRegenTime, 10), 10, 40);
/* Draw his/her health level */
G.setColor(new Color(Color.red.darker()));
G.drawString("Knight Health", 10, 60);
G.setColor(new Color(Color.white));
G.drawImage(new Image(Grey).getScaledCopy(100, 10), 10, 80);
G.drawImage(new Image(Red).getScaledCopy(PlayerHealth, 10), 10, 80);
/* Draw his/her name */
G.setColor(new Color(Color.red.darker()));
G.drawString("You\n |\n\\ /", PlayerX + 50, PlayerY - 70);
G.setColor(new Color(Color.white));
//Enemy
if(EnemyWalking) {
if(EnemyDirection.equalsIgnoreCase("right")) {
if(!EnemyJumping) {
WalkRightAnimation.draw(EnemyX, EnemyY, SpriteSheetWidth, SpriteSheetHeight);
}
else {
G.drawImage(new Image(RightKnight), EnemyX, EnemyY);
}
G.drawImage(new Image(EnemyCurrentSword), EnemyX + 60, EnemyY + 90);
}
if(EnemyDirection.equalsIgnoreCase("left")) {
if(!EnemyJumping) {
WalkLeftAnimation.draw(EnemyX, EnemyY, SpriteSheetWidth, SpriteSheetHeight);
}
else {
G.drawImage(new Image(LeftKnight), EnemyX, EnemyY);
}
G.drawImage(new Image(EnemyCurrentSword), EnemyX + 6, EnemyY + 90);
}
}
/* Draw enemy sword */
else {
if(EnemyDirection.equalsIgnoreCase("right")) {
if(!EnemyAttacking) {
EnemyCurrentSword = EnemyRightSword;
}
G.drawImage(new Image(RightKnight), EnemyX, EnemyY);
G.drawImage(new Image(EnemyCurrentSword), EnemyX + 60, EnemyY + 90);
}
if(EnemyDirection.equalsIgnoreCase("left")) {
if(!EnemyAttacking) {
EnemyCurrentSword = EnemyLeftSword;
}
G.drawImage(new Image(LeftKnight), EnemyX, EnemyY);
G.drawImage(new Image(EnemyCurrentSword), EnemyX + 6, EnemyY + 90);
}
}
/* Draw enemy power level */
G.setColor(new Color(Color.blue.darker()));
G.drawString("Enemy Power Level", 1115, 20);
G.setColor(new Color(Color.white));
G.drawImage(new Image(Grey).getScaledCopy(100, 10), 1165, 40);
G.drawImage(new Image(Blue).getScaledCopy(EnemyRegenTime, 10), 1165, 40);
/* Draw enemy health level */
G.setColor(new Color(Color.red.darker()));
G.drawString("Enemy Health", 1115, 60);
G.setColor(new Color(Color.white));
G.drawImage(new Image(Grey).getScaledCopy(100, 10), 1165, 80);
G.drawImage(new Image(Red).getScaledCopy(EnemyHealth, 10), 1165, 80);
// System Info (Not used currently)
/*G.drawString("Game State: " + this.getID(), 10, 30);
G.drawString("X:" + Mouse.getX() + " Y:" + Mouse.getY(), 10, 50);
G.drawString("Your OS: " + operatingSystem, 10, 70);
G.drawString("Player X: " + PlayerY + " Enemy X:" + EnemyX, 10, 170);*/
}
#Override
public void update(GameContainer GameContainer, StateBasedGame SBG,
int Delta) throws SlickException {
// Fixes for some stuff that might happen
if(PlayerY > 470) {
PlayerY = 470;
}
if(EnemyY > 470) {
EnemyY = 470;
}
// Enemy
if(!EnemyTalking) {
new Thread(new startFight()).start();
EnemyTalking = true;
}
/* Boss Battle Music */
if(startBossBattle && !startedBossBattle) {
if(!startedBossMusic) {
PlaySound.playSound("res/sounds/events/BossBattleLoop.wav");
PlaySound.startLoop(1000);
startedBossMusic = true;
}
startedBossBattle = true;
}
// Player
/* Player Movement */
if(PlayerCanMove) {
Input playerInput = GameContainer.getInput();
if(playerInput.isKeyDown(Input.KEY_A)) {
PlayerX -= Delta*.3f;
PlayerWalking = true;
PlayerDirection = "left";
if(!PlayerAttacking) {
PlayerCurrentSword = PlayerLeftSword;
}
}
else if(playerInput.isKeyDown(Input.KEY_D)) {
PlayerX += Delta*.3f;
PlayerWalking = true;
PlayerDirection = "right";
if(!PlayerAttacking) {
PlayerCurrentSword = PlayerRightSword;
}
}
else {
PlayerWalking = false;
}
/* Player Jumping */
if(playerInput.isKeyPressed(Input.KEY_SPACE)) {
if(!PlayerJumped) {
new Thread(new playerJump()).start();
}
}
if(PlayerJumping) {
PlayerY -= Delta*.5f;
AmountPlayerJumped = PlayerY;
}
else {
if(PlayerY < 470) {
PlayerY += Delta*.5f;
}
if(Math.round(PlayerY) == 470 || Math.round(PlayerY) == 471) {
PlayerJumped = false;
}
}
/* Player Attack */
if(playerInput.isKeyPressed(Input.KEY_ENTER)) {
if(PlayerCanAttack) {
new Thread(new playerAttack()).start();
}
else {
}
}
}
/* Player Collision Detection */
if(PlayerX < 0) {
PlayerX = 0;
}
if (PlayerX > 1155) {
PlayerX = 1155;
}
//Enemy
/* Enemy Movement and Jumping */
if(EnemyCanMove) {
if(PlayerX < EnemyX) {
if(PlayerDirection.equalsIgnoreCase("right")) {
if(!(EnemyX - 125 < PlayerX)) {
EnemyX -= Delta*.2f;
EnemyDirection = "right";
EnemyWalking = true;
BothTouching = false;
if(!(EnemyX - 50 < PlayerX)) {
if(!DecidedJump) {
int Jump = GenerateNumber.generateNumber(JumpPossibility);
if(Jump == JumpPossibility) {
new Thread(new enemyJump()).start();
}
DecidedJump = true;
}
}
else {
DecidedJump = false;
}
}
else {
EnemyWalking = false;
BothTouching = true;
if(EnemyRegenTime == 100) {
if(EnemyCanAttack) {
new Thread(new enemyAttack()).start();
}
}
}
}
if(PlayerDirection.equalsIgnoreCase("left")) {
if(!(EnemyX - 110 < PlayerX)) {
EnemyX -= Delta*.2f;
EnemyDirection = "left";
EnemyWalking = true;
BothTouching = false;
if(!(EnemyX + 50 < PlayerX)) {
if(!DecidedJump) {
int Jump = GenerateNumber.generateNumber(JumpPossibility);
if(Jump == JumpPossibility) {
new Thread(new enemyJump()).start();
}
DecidedJump = true;
}
}
else {
DecidedJump = false;
}
}
else {
EnemyWalking = false;
BothTouching = true;
if(EnemyRegenTime == 100) {
if(EnemyRegenTime == 100) {
if(EnemyCanAttack) {
new Thread(new enemyAttack()).start();
}
}
}
}
}
EnemyDirection = "left";
}
if(PlayerX > EnemyX) {
if(PlayerDirection.equalsIgnoreCase("right")) {
if(!(EnemyX + 119 > PlayerX)) {
EnemyX += Delta*.2f;
EnemyDirection = "right";
EnemyWalking = true;
BothTouching = false;
if(!(EnemyX - 50 < PlayerX)) {
if(!DecidedJump) {
int Jump = GenerateNumber.generateNumber(JumpPossibility);
if(Jump == JumpPossibility) {
new Thread(new enemyJump()).start();
}
DecidedJump = true;
}
}
else {
DecidedJump = false;
}
}
else {
EnemyWalking = false;
BothTouching = true;
if(EnemyRegenTime == 100) {
if(EnemyRegenTime == 100) {
if(EnemyCanAttack) {
new Thread(new enemyAttack()).start();
}
}
}
}
}
if(PlayerDirection.equalsIgnoreCase("left")) {
if(!(EnemyX + 135 > PlayerX)) {
EnemyX += Delta*.2f;
EnemyDirection = "left";
EnemyWalking = true;
BothTouching = false;
if(!(EnemyX + 50 < PlayerX)) {
if(!DecidedJump) {
int Jump = GenerateNumber.generateNumber(JumpPossibility);
if(Jump == JumpPossibility) {
new Thread(new enemyJump()).start();
}
DecidedJump = true;
}
}
else {
DecidedJump = false;
}
}
else {
EnemyWalking = false;
BothTouching = true;
if(EnemyRegenTime == 100) {
if(EnemyRegenTime == 100) {
if(EnemyCanAttack) {
new Thread(new enemyAttack()).start();
}
}
}
}
}
EnemyDirection = "right";
}
/* Enemy Jumping */
if(EnemyJumping) {
EnemyY -= Delta*.5f;
AmountEnemyJumped = EnemyY;
}
else {
if(EnemyY < 470) {
EnemyY += Delta*.5f;
}
if(Math.round(EnemyY) == 470 || Math.round(EnemyY) == 471) {
EnemyJumped = false;
}
}
}
}
// Initializing Constructor
#Override
public void init(GameContainer GameContainer, StateBasedGame SBG)
throws SlickException {
WalkRightSpriteSheet = new SpriteSheet("res/images/characters/knight/spritesheets/WalkAnimationRight.png", 35, 48);
WalkRightAnimation = new Animation(WalkRightSpriteSheet, 100);
WalkLeftSprite = new SpriteSheet("res/images/characters/knight/spritesheets/WalkAnimationLeft.png", 35, 48);
WalkLeftAnimation = new Animation(WalkLeftSprite, 100);
}
// Gets the ID of the current State
#Override
public int getID() {
return 1;
}
// Start Fight
static class startFight implements Runnable {
#Override
public void run() {
try {
Thread.sleep(1000);
startBossBattle = true;
} catch (Exception e) {
e.printStackTrace();
}
}
}
// Player Threads
/* Player Attack */
static class playerAttack implements Runnable {
#Override
public void run() {
try {
PlayerAttacking = true;
if(PlayerDirection.equalsIgnoreCase("right")) {
PlayerCurrentSword = PlayerRightAttackSword;
}
if(PlayerDirection.equalsIgnoreCase("left")) {
PlayerCurrentSword = PlayerLeftAttackSword;
}
if(BothTouching) {
EnemyHealth -= 10;
}
Thread.sleep(100);
if(PlayerDirection.equalsIgnoreCase("right")) {
PlayerCurrentSword = PlayerRightSword;
}
if(PlayerDirection.equalsIgnoreCase("left")) {
PlayerCurrentSword = PlayerLeftSword;
}
PlayerAttacking = false;
PlayerCanAttack = false;
PlayerRegenTime = 0;
while(PlayerRegenTime != 100) {
Thread.sleep(100);
PlayerRegenTime++;
}
PlayerCanAttack = true;
}
catch (Exception e) {
}
}
}
/* Player Jump */
static class playerJump implements Runnable {
#Override
public void run() {
try {
PlayerJumped = true;
PlayerJumping = true;
Thread.sleep(750);
PlayerJumping = false;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
// Enemy Threads
/* Enemy Attack */
static class enemyAttack implements Runnable {
#Override
public void run() {
try {
EnemyAttacking = true;
if(EnemyDirection.equalsIgnoreCase("right")) {
EnemyCurrentSword = EnemyRightAttackSword;
}
if(EnemyDirection.equalsIgnoreCase("left")) {
EnemyCurrentSword = EnemyLeftAttackSword;
}
PlayerHealth -= 10;
Thread.sleep(100);
if(EnemyDirection.equalsIgnoreCase("right")) {
EnemyCurrentSword = EnemyRightSword;
}
if(EnemyDirection.equalsIgnoreCase("left")) {
EnemyCurrentSword = EnemyLeftSword;
}
EnemyAttacking = false;
EnemyCanAttack = false;
EnemyRegenTime = 0;
while(EnemyRegenTime != 100) {
Thread.sleep(100);
EnemyRegenTime++;
}
EnemyCanAttack = true;
}
catch (Exception e) {
e.printStackTrace();
}
}
}
/* Decide Jump */
static class decideJump implements Runnable {
#Override
public void run() {
try {
Thread.sleep(1000 * 10);
int number = GenerateNumber.generateNumber(20);
if(number == 20) {
if(!EnemyJumping) {
new Thread(new enemyJump()).start();
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
/* Enemy Jump */
static class enemyJump implements Runnable {
#Override
public void run() {
try {
EnemyJumped = true;
EnemyJumping = true;
Thread.sleep(750);
EnemyJumping = false;
}
catch (Exception e) {
}
}
}
Turns out, that I wasnt adding it to the build path. If you are viewing this with this problem, make sure to add it to your build path in Eclipse (Or netbeans).
Related
I am programming a game for a school project and when I run the code, it works sometimes and then ill run it again and the paddle or ball won't move and the print statements in my keylistener dont show up.
Now I am running two timers, one for the animation and one for a countdown, could this be an issue? It seems like multiple threads are running or when I close the jframe and then rerun the program is picking up where it left off?
public class LobPong extends JPanel implements KeyListener {
public static double xCoordinate;
public static double yCoordinate;
public static Timer timer;
static int xPaddleLeft;
private static int yPaddle = 800;
private static int score = 0;
private static int level = 1;
public static JLabel scoreLabel = new JLabel(" Score: 0 ");
public static JLabel timeLabel = new JLabel(" ");
public static JLabel levelLabel = new JLabel(" Level: ");
private static int life = 3;
private static int levelTime = 30000;
public static int dx, dy;
private static double times = 0;
public static void main(String[] args) {
JFrame LobPongApp = new JFrame();
LobPong canvas = new LobPong();
canvas.setBackground(Color.BLUE);
LobPongApp.add(canvas);
LobPongApp.setSize(800, 900);
LobPongApp.setTitle("Lob Pong");
LobPongApp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
LobPongApp.setVisible(true);
canvas.setFocusable(true);
LobPongApp.addKeyListener(canvas);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.GREEN);
g.fillOval((int) xCoordinate, (int) yCoordinate, 50, 50);
g.fillRect(xPaddleLeft, yPaddle, 100, 10);
drawLife(g, getLife());
}
public LobPong() {
timer = new Timer(1, new timerCallBack());
timer.start();
setLayout(new FlowLayout());
scoreLabel.setOpaque(true);
timeLabel.setOpaque(true);
levelLabel.setOpaque(true);
scoreLabel.setBackground(Color.black);
timeLabel.setBackground(Color.black);
levelLabel.setBackground(Color.black);
scoreLabel.setForeground(Color.WHITE);
timeLabel.setForeground(Color.WHITE);
levelLabel.setForeground(Color.WHITE);
levelLabel.setText("Level: " + 1);
add(scoreLabel);
add(timeLabel);
add(levelLabel);
xPaddleLeft = 375; //debug
xCoordinate = 0;
yCoordinate = 0;
setTime(levelTime); //sets current level time (increases by 10 seconds every 2 levels)
}
public static void nextLevel(Graphics g, int levels) {
level += 1;
g.drawString("NEXT LEVEL!", 400, 400);
timer.stop();
//TODO call run() ?
}
public static void updateScore(int scoreAdd) {
score += scoreAdd;
scoreLabel.setText("Score: " + score);
}
public static int getScore() {
return score;
}
public static void updateLife(int x) {
life += x;
}
public static int getLife() {
return life;
}
public static void drawLife(Graphics g, int x) {
g.setColor(Color.RED);
for(int i = 0; i < (x * 10); i += 10) { //for loop to offset lives and draw enough balls per lives
g.fillOval(30 + i, 10, 10, 10);
}
}
public static void extraLife(boolean x) {
if (x == true) {
updateLife(1);
}
}
Timer timerDisplay = new Timer(1000, new TimerListener());
private static int totalTime;
public static void setTime(int time) {
totalTime = time;
}
public static int getTime() {
return totalTime;
}
protected class TimerListener implements ActionListener { //handles countdown timer
#Override
public void actionPerformed(ActionEvent arg0) {
setTime(getTime() - 1000);
LobPong.timeLabel.setText("Time Remaining: " + getTime()/1000 + " ");
if(getTime() <= 0) {
timerDisplay.stop();
timer.stop();
}
}
}
public void keyPressed(KeyEvent arg0) {
int key = arg0.getKeyCode();
System.out.println("testing");
if(key == 37) {
if (xPaddleLeft > 0) {
xPaddleLeft -= 50;
System.out.println("TEST"); //debug
}
}
if(key == 39) {
if (xPaddleLeft < (getWidth() - 50)) {
xPaddleLeft += 50;
}
}
if(key == KeyEvent.VK_ENTER) {
dx = 2;
timer.start();
timerDisplay.start();
System.out.println("start"); //debug
}
repaint();
}
boolean horizontal = true; //handles horizontal movement
boolean vertical = true; //handles vertical
double upwards;
public class timerCallBack implements ActionListener {
#Override
public void actionPerformed(ActionEvent arg0) {
times += .01;
if (horizontal == true) { //check
xCoordinate += dx;
}
if(xCoordinate <= 0) { //check
horizontal = true;
}
if(xCoordinate >= getWidth()) { //check
horizontal = false;
}
if(horizontal == false) { //check
xCoordinate -= dx;
}
if(vertical == true) { //check
dy = (int) times;
yCoordinate += dy;
}
if (vertical == false) { //check
dy = (int) (upwards - times);
yCoordinate -= dy;
}
if(dy == 0) { //check
vertical = true;
times = 0;
}
if(yCoordinate == getHeight()) { //check
updateLife(-1);
if (getLife() == 0) {
timer.stop();
timerDisplay.stop();
//TODO you lose and print high score
}
extraLife(false);
xCoordinate = 0;
yCoordinate = 0;
dy = 0;
dx = 0;
vertical = true;
}
if(xCoordinate <= (xPaddleLeft + 100) && xCoordinate >= xPaddleLeft && (yCoordinate + 50) == yPaddle) {
upwards = times;
times = 0;
vertical = false;
updateScore(1);
repaint();
//TODO plus one point, paddle bounce physics, direction
}
repaint();
}
}
#Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
}
I'm trying to make an addition to a pong game framework.I want the ball size to increase everytime the ball make contact with a paddle.
Here is my attempt. The first block of code is where I think the problem lays. The 2nd block is the whole class.
public class PlayState extends State {
private Paddle paddleRight, paddleLeft;
private static final int PADDLE_WIDTH = 30;
private static final int PADDLE_HEIGHT = 60;
private Ball ball;
//bDiam stands for ball diameter
private static int bDiam = 10;
private int playerScore = 0;
private Font scoreFont;
#Override
public void init() {
paddleLeft = new Paddle(0, 195, PADDLE_WIDTH, PADDLE_HEIGHT);
paddleRight = new Paddle(785, 195, PADDLE_WIDTH, PADDLE_HEIGHT);
scoreFont = new Font("SansSerif", Font.BOLD, 25);
ball = new Ball(300, 200, bDiam, bDiam);
}
#Override
public void onClick(MouseEvent e) {
// playerScore = 5;
}
#Override
public void update() {
paddleLeft.update();
paddleRight.update();
ball.update();
if (ballCollides(paddleLeft)) {
playerScore++;
bDiam+= 20;
ball.onCollideWith(paddleLeft);
Resources.hit.play();
} else
if (ballCollides(paddleRight)) {
playerScore++;
bDiam= bDiam + 20;
ball.onCollideWith(paddleRight);
Resources.hit.play();
} else if (ball.isDead()) {
playerScore -= 3;
ball.reset();
}
}
The Complete Class
public class PlayState extends State {
private Paddle paddleRight, paddleLeft;
private static final int PADDLE_WIDTH = 30;
private static final int PADDLE_HEIGHT = 60;
private Ball ball;
//bDiam stands for ball diameter
private static int bDiam = 10;
private int playerScore = 0;
private Font scoreFont;
#Override
public void init() {
paddleLeft = new Paddle(0, 195, PADDLE_WIDTH, PADDLE_HEIGHT);
paddleRight = new Paddle(785, 195, PADDLE_WIDTH, PADDLE_HEIGHT);
scoreFont = new Font("SansSerif", Font.BOLD, 25);
ball = new Ball(300, 200, bDiam, bDiam);
}
#Override
public void onClick(MouseEvent e) {
// playerScore = 5;
}
#Override
public void update() {
paddleLeft.update();
paddleRight.update();
ball.update();
if (ballCollides(paddleLeft)) {
playerScore++;
bDiam+= 20;
ball.onCollideWith(paddleLeft);
Resources.hit.play();
} else
if (ballCollides(paddleRight)) {
playerScore++;
bDiam= bDiam + 20;
ball.onCollideWith(paddleRight);
Resources.hit.play();
} else if (ball.isDead()) {
playerScore -= 3;
ball.reset();
}
}
#Override
public void render(Graphics g) {
// Draw Background
g.setColor(Resources.darkBlue);
g.fillRect(0, 0, GameMain.GAME_WIDTH, GameMain.GAME_HEIGHT);
g.setColor(Resources.darkRed);
g.fillRect(GameMain.GAME_WIDTH / 2, 0, GameMain.GAME_WIDTH / 2,
GameMain.GAME_HEIGHT);
// Draw Separator Line
g.drawImage(Resources.line, (GameMain.GAME_WIDTH / 2) - 2, 0, null);
// Draw Paddles
g.setColor(Color.white);
g.fillRect(paddleLeft.getX(), paddleLeft.getY(), paddleLeft.getWidth(),
paddleLeft.getHeight());
g.fillRect(paddleRight.getX(), paddleRight.getY(),
paddleRight.getWidth(), paddleRight.getHeight());
// Draw Ball
g.drawRect(ball.getX(), ball.getY(), ball.getWidth(), ball.getHeight());
// Draw UI
g.setFont(scoreFont); // Sets scoreFont as current font
g.drawString("" + playerScore, 350, 40); // Draws String using current
// font
}
#Override
public void onKeyPress(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_UP) {
paddleLeft.accelUp();
paddleRight.accelUp();
} else if (e.getKeyCode() == KeyEvent.VK_DOWN) {
paddleLeft.accelDown();
paddleRight.accelDown();
}
}
#Override
public void onKeyRelease(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_UP
|| e.getKeyCode() == KeyEvent.VK_DOWN) {
paddleLeft.stop();
paddleRight.stop();
}
}
private boolean ballCollides(Paddle p) {
return ball.getRect().intersects(p.getRect());
}
}
Your diameter variable is being passed by value into your Ball constructor. That means changing its value in your main program won't change it for the ball.
You need something like
ball.setDiameter(ball.getDiameter() +20)
I have a working class where I can move a circle around the screen using the keyboard while there are other circles moving across the screen at different speeds.
I reached this point, and I'm trying to figure out how to make it so that I can find out whether my shape has touched another shape, but that's the part I'm stuck at, as I don't have many ideas about how to make it work. I have tried various methods, but most of them don't work.
public class Test extends Panel implements Runnable, KeyListener, MouseMotionListener {
static final int left = 37;
static final int right = 39;
static final int down = 40;
static final int up = 38;
static boolean leftPress = false;
static boolean rightPress = false;
static boolean upPress = false;
static boolean downPress = false;
/*****/
static int upperLeftX;
static int upperLeftY;
static int lowerLeftX;
static int lowerLeftY;
static int upperRightX;
static int upperRightY;
static int lowerRightX;
static int lowerRightY;
int eUpperLeftX;
int eUpperLeftY;
int eLowerLeftX;
int eLowerLeftY;
int eUpperRightX;
int eUpperRightY;
int eLowerRightX;
int eLowerRightY;
/*****/
static boolean eat = false;
static boolean eaten = false;
static int mouseLocationX;
static int mouseLocationY;
static String mouseLocation = "";
/**/
int x1_;
int y1_;
int eSize;
int eRandSpawn;
int sleep;
Color eColor;
/**/
static int x1 = 250;
static int y1 = 250;
static int size = 30;
static JFrame frame = new JFrame("Fishy");
static Test panel = new Test(500, 500, 9);
// static Test time1 = new Test(1000);
// static Test time2 = new Test(500);
// static Test time3 = new Test(250);
// static Test time4 = new Test(Methods.randNum(6,20),Methods.randNum(0, 450));
// static Test time5 = new Test(Methods.randNum(6,20),Methods.randNum(0, 450));
static Test eFish[] = new Test[20];
/** CONSTRUCTOR **/
public Test() {
sleep = Methods.randNum(6, 50);
y1_ = Methods.randNum(0, 450);
eRandSpawn = Methods.randNum(1, 2);
eColor = Methods.randColor();
eSize = Methods.randNum(5, 120);
if (eRandSpawn == 1) {
x1_ = -100;
} else {
x1_ = 600;
}
eUpperLeftX = x1_;
eUpperLeftY = y1_;
eLowerLeftX = x1_;
eLowerLeftY = y1_ + eSize;
eUpperRightX = x1_ + eSize;
eUpperRightY = y1_;
eLowerRightX = x1_ + eSize;
eLowerRightY = x1_ + eSize;
}
/** CONSTRUCTOR **/
public Test(int width, int length, int minusBy) {
super(width, length, minusBy);
}
/** MAIN **/
public static void main(String args[]) throws InterruptedException {
for (int i = 0; i < 20; i++) {
eFish[i] = new Test();
}
Thread time[] = new Thread[20];
for (int i = 0; i < 20; i++) {
time[i] = new Thread(eFish[i]);
}
// Thread time1_ = new Thread(time1);
// Thread time2_ = new Thread(time2);
// Thread time3_ = new Thread(time3);
// Thread time4_ = new Thread(time4);
// Thread time5_ = new Thread(time5);
frame.add(panel);
frame.addKeyListener(panel);
panel.addMouseMotionListener(panel);
Frame.showFrame(frame);
// time1_.start();
// time2_.start();
// time3_.start();
// time4_.start();
// time5_.start();
for (int i = 0; i < 20; i++) {
time[i].start();
}
while (true) {
if (upPress) {
y1--;
}
if (downPress) {
y1++;
}
if (leftPress) {
x1--;
}
if (rightPress) {
x1++;
}
if (upPress || downPress || leftPress || rightPress) {
upperLeftX = x1;
upperLeftY = y1;
lowerLeftX = x1;
lowerLeftY = y1 + size;
upperRightX = x1 + size;
upperRightY = y1;
lowerRightX = x1 + size;
lowerRightY = x1 + size;
Thread.sleep(6);
frame.repaint();
}
for (int i = 0; i < 20; i++) {
if (eat) {
size++;
eFish[i].eRandSpawn = Methods.randNum(1, 2);
if (eFish[i].eRandSpawn == 1) {
eFish[i].y1_ = Methods.randNum(0, 450);
eFish[i].x1_ = -100;
eFish[i].sleep = Methods.randNum(6, 50);
eFish[i].eSize = Methods.randNum(5, 120);
eFish[i].eColor = Methods.randColor();
} else {
eFish[i].y1_ = Methods.randNum(0, 450);
eFish[i].x1_ = 600;
eFish[i].sleep = Methods.randNum(6, 50);
eFish[i].eSize = Methods.randNum(5, 120);
eFish[i].eColor = Methods.randColor();
}
eFish[i].eUpperLeftX = eFish[i].x1_;
eFish[i].eUpperLeftY = eFish[i].y1_;
eFish[i].eLowerLeftX = eFish[i].x1_;
eFish[i].eLowerLeftY = eFish[i].y1_ + eFish[i].eSize;
eFish[i].eUpperRightX = eFish[i].x1_ + eFish[i].eSize;
eFish[i].eUpperRightY = eFish[i].y1_;
eFish[i].eLowerRightX = eFish[i].x1_ + eFish[i].eSize;
eFish[i].eLowerRightY = eFish[i].x1_ + eFish[i].eSize;
}
eat = false;
}
}
}
/** PAINT **/
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.CYAN);
g.fillRect(0, 0, 501, 501);
g.setColor(Color.BLACK);
mouseLocation = String.format("%s,%s,%s", x1, y1, size);
g.drawString(mouseLocation, 100, 100);
g.setColor(Color.GREEN);
g.fillOval(x1, y1, size, size);
// g.drawOval(time4.x1_,time4.y1_,50,50);
// g.drawOval(time5.x1_,time5.y1_,50,50);
for (int i = 0; i < 20; i++) {
g.setColor(eFish[i].eColor);
g.fillOval(eFish[i].x1_, eFish[i].y1_, eFish[i].eSize, eFish[i].eSize);
}
/*
* for (int i = 0; i < 10; i++) { g.setColor(Methods.randColor()); g.drawRect(x1 + i, y1 + i, width - i * 2, height - i * 2);
*
* }
*/
// g.drawString(time1.time, 20, 50);
// g.drawString(time2.time, 20, 100);
// g.drawString(time3.time, 20, 150);
}
#Override
public void run() {
while (true) {
try {
Thread.sleep(sleep);
eUpperLeftX = x1_;
eUpperLeftY = y1_;
eLowerLeftX = x1_;
eLowerLeftY = y1_ + eSize;
eUpperRightX = x1_ + eSize;
eUpperRightY = y1_;
eLowerRightX = x1_ + eSize;
eLowerRightY = x1_ + eSize;
if (x1_ == -150) {
y1_ = Methods.randNum(0, 450);
x1_ = 600;
sleep = Methods.randNum(6, 50);
eSize = Methods.randNum(5, 120);
eColor = Methods.randColor();
}
if (x1_ == 650) {
y1_ = Methods.randNum(0, 450);
x1_ = -100;
sleep = Methods.randNum(6, 50);
eSize = Methods.randNum(5, 120);
eColor = Methods.randColor();
}
if (eRandSpawn == 1) {
x1_++;
} else {
x1_--;
}
frame.repaint();
} catch (InterruptedException e) {
}
}
}
#Override
public void keyPressed(KeyEvent e) {
if (up == e.getKeyCode()) {
upPress = true;
}
if (down == e.getKeyCode()) {
downPress = true;
}
if (left == e.getKeyCode()) {
leftPress = true;
}
if (right == e.getKeyCode()) {
rightPress = true;
}
}
#Override
public void keyReleased(KeyEvent e) {
if (up == e.getKeyCode()) {
upPress = false;
}
if (down == e.getKeyCode()) {
downPress = false;
}
if (left == e.getKeyCode()) {
leftPress = false;
}
if (right == e.getKeyCode()) {
rightPress = false;
}
}
#Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void mouseDragged(MouseEvent e) {
// TODO Auto-generated method stub
}
#Override
public void mouseMoved(MouseEvent e) {
mouseLocationX = e.getX();
mouseLocationY = e.getY();
mouseLocation = String.format("%s,%s", mouseLocationX, mouseLocationY);
frame.repaint();
}
}
public boolean madeContact(Ellipse a, Ellipse b) {
//Center of ellipse
int ax = a.getX(), ay = a.getY(), bx = b.getX(), by = b.getY();
//Radii
int arx = a.getRadiusX(), ary = a.getRadiusY();
int brx = b.getRadiusX(), bry = b.getRadiusY();
//Has hit x, y
boolean hitx = Math.abs(ax - bx) < arx+brx;
boolean hity = Math.abs(ay - by) < ary+bry;
return hitx && hity;
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am trying to make a main menu in my java game program and I tried many different ways but all of them failed. Can someone help doing it? I want the simplest. Thank you btw. Here's my source code
Snake.java
public class Snake extends JFrame {
public Snake() {
add(new Board());
setResizable(false);
pack();
setTitle("Snake");
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
JFrame ex = new Snake();
ex.setVisible(true);
}
});
}
}
Board.java
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() {
addKeyListener(new TAdapter());
setBackground(Color.black);
setFocusable(true);
setPreferredSize(new Dimension(B_WIDTH, B_HEIGHT));
loadImages();
initGame();
}
private void loadImages() {
ImageIcon iid = new ImageIcon("dot.png");
ball = iid.getImage();
ImageIcon iia = new ImageIcon("apple.png");
apple = iia.getImage();
ImageIcon iih = new ImageIcon("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. Thank you for playing ";
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;
}
}
}
}
The simplest and more common way is adding a top Menu. As you are using AWT, I strongly recommend you to use MenuBar - java.awt.MenuBar
public class MenuBar
extends MenuComponent
implements MenuContainer, Accessible
In this site you have a complete example
How do I make the player and the world scroll at the same time?
because no matter what i do it always has a small delay...
My point is this: my game is a 2d sidescroller (terraria/minecraft/rpg) game and I need to be able to move the terrain together with the world...
Player.java
package game.test.src;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import javax.swing.ImageIcon;
public class Player {
static final int MOVE_UP = 0, MOVE_DOWN = 1, MOVE_LEFT= 2, MOVE_RIGHT = 3;
private World world;
private Rectangle playerRect;
private Image playerImg;
//Block Variables
private int hoverX, hoverY;
private boolean hovering = false;
protected static int xDirection;
protected static int yDirection;
private Weapon weapon;
public Player(World world){
this.world = world;
playerImg = new ImageIcon("H:/2D game test/Game test 2/src/game/test/src/images/Character.png").getImage();
playerRect = new Rectangle(50, 0, 10, 36);
weapon = new Weapon(weapon.PICKAXE);
}
private static void setXDirection(int d){
xDirection = d;
}
private static void setYDirection(int d){
yDirection = d;
}
public void update()
{
move();
checkForCollision();
}
private void checkForCollision() {
}
private void move()
{
playerRect.x += xDirection;
playerRect.y += yDirection;
gravity();
}
private void gravity()
{
for(int i=0;i<world.arrayNum; i++)
{
if(!world.isSolid[i])
{
setYDirection(1);
}
else if(world.isSolid[i] && playerRect.intersects(world.blocks[i]))
{
setYDirection(0);
}
}
}
//MotionEvents
public void mousePressed(MouseEvent e)
{
}
public void mouseReleased(MouseEvent e)
{
}
public void mouseClicked(MouseEvent e)
{
}
public void mouseMoved(MouseEvent e)
{
int x = e.getX();
int y = e.getY();
int px = playerRect.x;
int py = playerRect.y;
for(int i = 0; i < world.arrayNum; i++)
{
if(weapon.isEquipped(Weapon.PICKAXE) &&
x > world.blocks[i].x && x < world.blocks[i].x + world.blocks[i].width &&
y > world.blocks[i].x && y < world.blocks[i].y + world.blocks[i].height && world.isSolid[i] &&
(world.blocks[i].x + (world.blocks[i].width / 2) ) <= (px + playerRect.width/2) + weapon.WEAPON_RADIUS &&
(world.blocks[i].x + (world.blocks[i].width / 2) ) >= (px + playerRect.width/2) - weapon.WEAPON_RADIUS &&
(world.blocks[i].y + (world.blocks[i].height / 2) ) <= (py + playerRect.height/2) + weapon.WEAPON_RADIUS &&
(world.blocks[i].y + (world.blocks[i].height / 2) ) >= (py + playerRect.height/2) - weapon.WEAPON_RADIUS)
{
hovering = true;
hoverX = world.blocks[i].x;
hoverY = world.blocks[i].y;
break;
}
else
hovering = false;
}
}
public void mouseDragged(MouseEvent e)
{
}
public void mouseEntered(MouseEvent e)
{
}
public void mouseExited(MouseEvent e)
{
}
//Drawing Methods
public void draw(Graphics g)
{
g.drawImage(playerImg, playerRect.x, playerRect.y, null);
if(hovering)
drawBlockOutline(g);
}
private void drawBlockOutline(Graphics g)
{
g.setColor(Color.black);
g.drawRect(hoverX, hoverY, world.blocks[0].width,world.blocks[0].height);
}
private class Weapon
{
public static final int UNARMED = 0;
public static final int PICKAXE = 1;
public static final int GUN = 2;
public int CURRENT_WEAPON;
public int WEAPON_RADIUS;
public Weapon(int w)
{
switch(w)
{
default:
System.out.println("No weapon selected");
break;
case UNARMED:
CURRENT_WEAPON = UNARMED;
WEAPON_RADIUS = 100;
break;
case PICKAXE:
CURRENT_WEAPON = PICKAXE;
WEAPON_RADIUS = 100;
break;
case GUN:
CURRENT_WEAPON = GUN;
WEAPON_RADIUS = 100;
break;
}
}
public void selectWeapon(int w)
{
switch(w)
{
default:
System.out.println("No weapon selected");
break;
case UNARMED:
CURRENT_WEAPON = UNARMED;
WEAPON_RADIUS = 100;
break;
case PICKAXE:
CURRENT_WEAPON = PICKAXE;
WEAPON_RADIUS = 100;
break;
case GUN:
CURRENT_WEAPON = GUN;
WEAPON_RADIUS = 100;
break;
}
}
public boolean isEquipped(int w)
{
if(w == CURRENT_WEAPON)
{
return true;
}
else
return false;
}
}
public void moveMap(){
for(Rectangle r : world.blocks){
r.x += xDirection;
r.y += yDirection;
}
}
public static void stopMoveMap(){
setXDirection(0);
setYDirection(0);
}
private static void setXDirection1(int dir){
xDirection = dir;
}
private static void setYDirection1(int dir){
yDirection = dir;
}
public static void navigatePlayer(int nav){
switch(nav){
default:
System.out.println("default case entered... Doing nothing.");
break;
case MOVE_UP:
setYDirection1(-1);
break;
case MOVE_DOWN:
setYDirection1(1);
break;
case MOVE_LEFT:
setXDirection1(-1);
break;
case MOVE_RIGHT:
setXDirection1(1);
break;
}
}
}
World.java
package game.test.src;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;
import javax.swing.ImageIcon;
public class World {
public Rectangle[] blocks;
public boolean[] isSolid;
public Image[] blockImg;
public final int arrayNum = 500;
//Block Images
public Image BLOCK_GRASS, BLOCK_DIRT, BLOCK_STONE, BLOCK_SKY;
private int x, y, xDirection, yDirection;;
//map navigation
static final int PAN_UP = 0, PAN_DOWN = 1, PAN_LEFT= 2, PAN_RIGHT = 3;
public World(){
BLOCK_GRASS = new ImageIcon("H:/2D game test/Game test 2/src/game/test/src/images/tile_grass.png").getImage();
BLOCK_DIRT = new ImageIcon("H:/2D game test/Game test 2/src/game/test/src/images/tile_dirt.png").getImage();
BLOCK_STONE = new ImageIcon("H:/2D game test/Game test 2/src/game/test/src/images/tile_stone.png").getImage();
BLOCK_SKY = new ImageIcon("H:/2D game test/Game test 2/src/game/test/src/images/tile_sky.png").getImage();
blocks = new Rectangle[500];
blockImg = new Image[500];
isSolid = new boolean[arrayNum];
loadArrays();
}
private void loadArrays(){
for(int i = 0; i < arrayNum; i++){
if(x >= 500){
x = 0;
y += 20;
}
if(i >= 0 && i < 100){
blockImg[i] = BLOCK_SKY;
isSolid[i] = false;
blocks[i] = new Rectangle(x, y, 20, 20);
}
if(i >= 100 && i < 125){
blockImg[i] = BLOCK_GRASS;
isSolid[i] = true;
blocks[i] = new Rectangle(x, y, 20, 20);
}
if(i >= 125 && i < 225){
blockImg[i] = BLOCK_DIRT;
isSolid[i] = true;
blocks[i] = new Rectangle(x, y, 20, 20);
}
if(i >= 225 && i < 500){
blockImg[i] = BLOCK_STONE;
isSolid[i] = true;
blocks[i] = new Rectangle(x, y, 20, 20);
}
x += 20;
}
}
public void draw(Graphics g){
for(int i = 0; i < arrayNum; i++){
g.drawImage(blockImg[i], blocks[i].x, blocks[i].y, null);
}
}
public void moveMap(){
for(Rectangle r : blocks){
r.x += xDirection;
r.y += yDirection;
}
}
public void stopMoveMap(){
setXDirection(0);
setYDirection(0);
}
private void setXDirection(int dir){
xDirection = dir;
}
private void setYDirection(int dir){
yDirection = dir;
}
public void navigateMap(int nav){
switch(nav){
default:
System.out.println("default case entered... Doing nothing.");
break;
case PAN_UP:
setYDirection(-1);
break;
case PAN_DOWN:
setYDirection(1);
break;
case PAN_LEFT:
setXDirection(-1);
break;
case PAN_RIGHT:
setXDirection(1);
break;
}
}
}
GamePanel.java
package game.test.src;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JPanel;
public class GamePanel extends JPanel implements Runnable {
//Double buffering
private Image dbImage;
private Graphics dbg;
//JPanel variables
static final int GWIDTH = 500, GHEIGHT = 400;
static final Dimension gameDim = new Dimension(GWIDTH, GHEIGHT);
//Game variables
private static final int DELAYS_BEFORE_YIELD = 10;
private Thread game;
private volatile boolean running = false;
private long period = 6*1000000; //ms -> nano
//Game Objects
World world;
Player p1;
public GamePanel(){
world = new World();
p1 = new Player(world);
setPreferredSize(gameDim);
setBackground(Color.WHITE);
setFocusable(true);
requestFocus();
//Handle all key inputs from user
addKeyListener(new KeyAdapter(){
#Override
public void keyPressed(KeyEvent e){
if(e.getKeyCode() == KeyEvent.VK_LEFT){
Player.navigatePlayer(Player.MOVE_LEFT);
world.navigateMap(World.PAN_LEFT);
}
if(e.getKeyCode() == KeyEvent.VK_RIGHT){
Player.navigatePlayer(Player.MOVE_RIGHT);
world.navigateMap(World.PAN_RIGHT);
}
if(e.getKeyCode() == KeyEvent.VK_UP){
Player.navigatePlayer(Player.MOVE_UP);
world.navigateMap(World.PAN_UP);
}
if(e.getKeyCode() == KeyEvent.VK_DOWN){
Player.navigatePlayer(Player.MOVE_DOWN);
world.navigateMap(World.PAN_DOWN);
}
}
#Override
public void keyReleased(KeyEvent e){
Player.stopMoveMap();
world.stopMoveMap();
}
#Override
public void keyTyped(KeyEvent e){
}
});
addMouseListener(new MouseAdapter()
{
#Override
public void mousePressed(MouseEvent e)
{
}
#Override
public void mouseReleased(MouseEvent e)
{
}
#Override
public void mouseClicked(MouseEvent e)
{
}
});
addMouseMotionListener(new MouseAdapter()
{
public void mouseMoved(MouseEvent e)
{
p1.mouseMoved(e);
}
public void mouseDragged(MouseEvent e)
{
}
public void mouseEntered(MouseEvent e)
{
}
public void mouseExited(MouseEvent e)
{
}
});
}
public void run(){
long beforeTime, afterTime, diff, sleepTime, overSleepTime = 0;
int delays = 0;
while(running){
beforeTime = System.nanoTime();
gameUpdate();
gameRender();
paintScreen();
afterTime = System.nanoTime();
diff = afterTime - beforeTime;
sleepTime = (period - diff) - overSleepTime;
//if sleepTime is between peiod and 0, then sleep
if(sleepTime < period && sleepTime > 0)
{
try{
Thread.sleep(sleepTime/1000000L);
overSleepTime = 0;
}catch(InterruptedException ex){
Logger.getLogger(GamePanel.class.getName()).log(Level.SEVERE, "EXCEPTION");
}
}
//the diff was greater than the period
else if(diff > period)
{
overSleepTime = diff - period;
}
else if(++delays >= DELAYS_BEFORE_YIELD)
{
Thread.yield();
delays = 0;
overSleepTime = 0;
}
//the loop took less time than expected
else
{
overSleepTime = 0;
}
}
}
private void gameUpdate(){
if(running && game != null){
world.moveMap();
p1.update();
}
}
private void gameRender(){
if(dbImage == null){ // Create the buffer
dbImage = createImage(GWIDTH, GHEIGHT);
if(dbImage == null){
System.err.println("dbImage is still null!");
return;
}else{
dbg = dbImage.getGraphics();
}
}
//Clear the screen
dbg.setColor(Color.WHITE);
dbg.fillRect(0, 0, GWIDTH, GHEIGHT);
//Draw Game elements
draw(dbg);
}
/* Draw all game content in this method */
public void draw(Graphics g){
world.draw(g);
p1.draw(g);
}
private void paintScreen(){
Graphics g;
try{
g = this.getGraphics();
if(dbImage != null && g != null){
g.drawImage(dbImage, 0, 0, null);
}
Toolkit.getDefaultToolkit().sync(); //For some operating systems
g.dispose();
}catch(Exception e){
System.err.println(e);
}
}
public void addNotify(){
super.addNotify();
startGame();
}
private void startGame(){
if(game == null || !running){
game = new Thread(this);
game.start();
running = true;
}
}
public void stopGame(){
if(running){
running = false;
}
}
private void log(String s){
System.out.println(s);
}
}
thanks for the help!