Can't subtract 1 from bank - java

PS: the links you have to take out the () from http because I don't have enough rep points or something.
Board:
package game;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Board extends JPanel implements ActionListener {
Turn_Ticker turn = new Turn_Ticker();
Bank bank = new Bank();
Image Background;
Timer timer;
String time="";
public Board() {
setFocusable(true);
ImageIcon icon = new ImageIcon("res/Level1.png"); // calls image for background
Background = icon.getImage(); // sets variable background to icon image
timer = new Timer(5,this); // sets how fast page refreshes
timer.start();
}
public void actionPerformed(ActionEvent event) { // Refreshes page according to timer
repaint();
}
public void paint(Graphics paint) { // paints on frame
super.paint(paint);
Graphics2D p = (Graphics2D) paint;
turn.getTick();
bank.subBank();
p.drawImage(Background, 0, 0, null);
p.drawString(bank.getBank()+"",125,70);
p.drawString(bank.getEnemy_Bank()+"",125,115);
p.drawString(turn.getSecond()+" Second(s) Turn: "+turn.getTurn(), 120, 200);
if(turn.getTick())
p.drawString("Ticker = true", 500,500);/*
if(turn.getNum()==0)
p.drawString("Number = 0", 500,550);
if(turn.getNum()==0&&turn.getTick()){
bank.subBank();
p.drawString("Both are =", 500, 600);
}*/
//System.out.println("X: "+mouse.getX()+" Y: "+mouse.getY());
}
}
Turn_Ticker:
package game;
public class Turn_Ticker {
long before,after,difference;
boolean checkTime=true;
int seconds=0;
boolean ticker=false;
int turn=1;
int num=0;
public Turn_Ticker(){
if (checkTime == true)
before=System.currentTimeMillis();
checkTime=false;
}
public int getSecond() {
after=System.currentTimeMillis();
difference= after-before;
if(difference >= 1000) {
before=System.currentTimeMillis();
if(seconds<=0) {
seconds=30;
ticker=true;
num=0;
}
else {
seconds-=1;
num=1;
ticker=false;
}
}
return seconds;
}
public boolean getTick() {
if(ticker&&num==0) {
turn++;
}
return ticker;
}
public int getNum(){
return num;
}
public int getTurn() {
return turn;
}
public boolean getTickVar(){
return ticker;
}
}
Bank:
package game;
public class Bank {
Turn_Ticker turn = new Turn_Ticker();
int bank=5, enemy_Bank=5;
int baseRein=3, reinforcements,num=0;
public Bank(){
if(turn.getTick()==false)
num=0;
}
public int getBank(){
return bank;
}
public int getEnemy_Bank(){
return enemy_Bank;
}
public void subBank(){
if(turn.getNum()==0&&turn.getTick())
bank--;
}
public void subEn_Bank(){
enemy_Bank-=1;
}
}
Frame:
package game;
import javax.swing.*;
import java.awt.Font;
public class Frame {
public Frame() {
JFrame frame = new JFrame();
frame.add(new Board());
frame.setTitle("WSMD");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(1024,768);
frame.setVisible(true);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setLocationRelativeTo(null);
}
public static void main(String[] args){
new Frame();
}
}
My problem is that I can not, for the life of me, figure out why it won't subtract -1(bank.subBank()) from the bank. I've printed out the code and went through it step by step.

Related

Java drawing moving rectangles in loop

I need to draw in AWT/Swing rectangles that are moving from frame to frame.
I have a Playground class
public Playground(int sizeX, int sizeY)
{
frame = new JFrame();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
panel = new JPanel();
panel.setSize(sizeX, sizeY);
panel.setDoubleBuffered(true);
panel.setVisible(true);
frame.add(panel);
frame.pack();
frame.setSize(sizeX, sizeY);
}
public void refresh()
{
panel.repaint();
}
public Graphics getGraphics()
{
return panel.getGraphics();
}
This is the class in which objects should be drawn:
public class Star {
private static int size = 10;
private int posX;
private int posY;
public Star(int posX, int posY)
{
this.posX = posX;
this.posY = posY;
}
public void paint(Graphics g)
{
g.fillRect(posX, posY, size, size);
}
public int getPosX() {
return posX;
}
public int getPosY() {
return posY;
}
}
This is the main method:
public static void main(String[] args) {
Playground playground = new Playground(400, 400);
Star star = new Star(100, 100);
Star star2 = new Star(125, 125);
while(1 == 1)
{
playground.refresh();
star.paint(playground.getGraphics());
star2.paint(playground.getGraphics());
}
}
The objects are drawn but are flickering, how can I stop it from flickering?
Edit: I solved the flickering for one element, by changing the refresh method to:
public void refresh()
{
panel.getGraphics().clearRect(0,0, panel.getWidth(), panel.getHeight());
}
Unfortunately only one Element is not flickering all others are still flickering.
The following is a one-file mcve that demonstrates moving (rotating for simplicity) a rectangle by custom painting.
One-file meaning that you can copy-paste the entire code into one file (AnimateRectangle.java) and execute it.
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class AnimateRectangle {
private JFrame frame;
public AnimateRectangle(Model model){
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new MyJPanel(model);
panel.setDoubleBuffered(true);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
void refresh() {
frame.repaint();
}
public static void main(String[] args) throws InterruptedException {
Controller controller = new Controller(400, 400);
while (true) {
Thread.sleep(1000);
SwingUtilities.invokeLater(()->controller.animate());
}
}
}
//"wires" gui and model
class Controller{
private Model model;
private AnimateRectangle view;
Controller(int sizeX, int sizeY){
model = new Model(sizeX, sizeY);
view = new AnimateRectangle(model);
}
void animate() {
int newAngle = (model.getAngle() < 360 ) ? model.getAngle()+1 : 0 ;
model.setAngle(newAngle);
view.refresh();
}
}
//represents the inforamtion the GUI needs
class Model{
int sizeX, sizeY, angle = 0;
public Model(int sizeX, int sizeY) {
this.sizeX = sizeX;
this.sizeY = sizeY;
}
int getSizeX() { return sizeX; }
int getSizeY() {return sizeY;}
int getAngle() {return angle;}
//degrees
void setAngle(int angle) { this.angle = angle; }
}
//a JPanel with custom paint component
class MyJPanel extends JPanel {
private Model model;
public MyJPanel(Model model) {
this.model = model;
setPreferredSize(new Dimension(model.getSizeX(), model.getSizeY()));
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
g2d.setColor(Color.RED);
int sizeX = model.getSizeX(), sizeY = model.getSizeY();
g2d.rotate(Math.toRadians(model.getAngle()), sizeX /2, sizeY/2);
g2d.fillRect(sizeX/4, sizeY/4, sizeX/2, sizeY/2);
}
}
A better option (see camickr comment) is to animate using swing Timer. To do so, remove animate() method, and replace it with :
void animateWithTimer(){
new Timer(1000,new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
int newAngle = (model.getAngle() < 360 ) ? model.getAngle()+1 : 0 ;
model.setAngle(newAngle);
view.refresh();
}
}).start();
}
and change main to use it :
public static void main(String[] args) throws InterruptedException {
Controller controller = new Controller(400, 400);
controller.animateWithTimer();
}

Cannot use MouseEvents in main

What I'm trying to do
Making a Pong game where the Y axis gets the value from my cursor according to the application
What did I tried
private void pallet() {
ycur=(int)MouseInfo.getPointerInfo().getLocation().getY();
}
This way I get the Y value according to my monitor instead of the application.
I also tried to use the MouseEvent.getY(), but I get the error when trying to call this method from the main.
private void pallet() {
ycur=(int)MouseInfo.getPointerInfo().getLocation().getY();
}
This is how my code looks like, I think the problem lies in how I'm using my main and methods but I'm not sure.
public class MyFirst extends JPanel {
public int x = 500, y = 300, border = 30;
public boolean goingDown = true;
public int ycur, cursor;
public void moveBall() {
x++;
if (goingDown == true) {
y++;
} else if (goingDown == false) {
y--;
}
if (y == getHeight() - border) {
goingDown = false;
} else if (y == 0) {
goingDown = true;
}
}
#Override
public void paint(Graphics g) {
super.paint(g);
g.fillOval(x, y, 30, 30);
g.fillRect(30, ycur, 15, 100);
}
public static void main(String[] args) throws InterruptedException {
JFrame frame = new JFrame("Pong");
frame.pack();
frame.setSize(1000, 600);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
MyFirst game = new MyFirst();
frame.add(game);
while (true) {
game.pallet(e);
game.moveBall();
game.repaint();
Thread.sleep(10);
}
}
public void pallet(MouseEvent e) {
ycur=e.getY();
}
}
Problems with your code:
As already mentioned, you're fighting against Swing's event-driven architecture. Instead of a while true loop, use listeners, including a MouseMotionListener ot track the changes in the mouse location, and an ActionListener tied to a Swing Timer to move the ball.
Avoid using Thread.sleep(...) in Swing GUI's except with great care as this can put the entire application to sleep.
Avoid putting too much logic within the main method. This method should be short, should create the key objects, connect them, set the program in motion and that's it.
Paint with the paintComponent method, not the paint method. It results in smoother animation with its double buffering.
For example:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.*;
#SuppressWarnings("serial")
public class MoveBallTest extends JPanel{
private static final int PREF_W = 1000;
private static final int PREF_H = 600;
private static final int TIMER_DELAY = 12;
private static final int SPRITE_WIDTH = 30;
private static final Color OVAL_SPRITE_COLOR = Color.RED;
private static final Color RECT_SPRITE_COLOR = Color.BLUE;
private static final int DELTAY_Y = 1;
private boolean goingDown = true;
private Timer timer = new Timer(TIMER_DELAY, this::timerActionPerformed);
private int ovalSpriteY;
private int rectSpriteY;
public MoveBallTest() {
timer.start();
MyMouse myMouse = new MyMouse();
addMouseMotionListener(myMouse);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(OVAL_SPRITE_COLOR);
g.fillOval(SPRITE_WIDTH, ovalSpriteY, SPRITE_WIDTH, SPRITE_WIDTH);
g.setColor(RECT_SPRITE_COLOR);
g.fillRect(SPRITE_WIDTH, rectSpriteY, SPRITE_WIDTH / 2, SPRITE_WIDTH * 3);
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return new Dimension(PREF_W, PREF_H);
}
public void timerActionPerformed(ActionEvent e) {
if (ovalSpriteY <= 0) {
goingDown = true;
} else if (ovalSpriteY >= getHeight() - SPRITE_WIDTH) {
goingDown = false;
}
ovalSpriteY += goingDown ? DELTAY_Y : -DELTAY_Y;
repaint();
}
private class MyMouse extends MouseAdapter {
#Override
public void mouseMoved(MouseEvent e) {
rectSpriteY = e.getY();
}
}
private static void createAndShowGui() {
JFrame frame = new JFrame("MoveBallTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new MoveBallTest());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}

Mouse Handler in Separate Class not Working

I am writing a Crazy Eights game and trying to have mouse control added in. I just starting writing it but I can't verify if it's working or not. I've added System.out.println() to the pressed and released event calls but no output happens. I just need to get it working and be able to see an output of some kind for debugging. I've also tried to use another example on stackoverflow to help me out but I'm still having issues. The below code is what I'm working with. Let me know if you need to see another class.
Thanks
MouseControl.java
package crazyeightscountdown.CoreClasses;
import java.awt.Canvas;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class MouseControl extends MouseAdapter {
public Canvas canvas;
public MouseControl (Canvas c){
this.canvas = c;
}
#Override
public void mouseReleased (MouseEvent e){
System.out.println("Mouse Released.\n");
}
#Override
public void mousePressed (MouseEvent e){
System.out.println("Mouse Pressed.\n");
}
#Override
public void mouseClicked (MouseEvent e){
}
#Override
public void mouseEntered (MouseEvent e){
}
#Override
public void mouseExited (MouseEvent e){
}
}//class
Game.java
package crazyeightscountdown;
import static com.sun.java.accessibility.util.AWTEventMonitor.addMouseListener;
import static crazyeightscountdown.CoreClasses.Constants.CARDPICX;
import crazyeightscountdown.CoreClasses.Deck;
import crazyeightscountdown.CoreClasses.MouseControl;
import crazyeightscountdown.CoreClasses.Player;
import java.awt.Graphics;
import java.awt.image.BufferStrategy;
//Sets up parameters for the game window
public class Game implements Runnable {
private Display display;
public int width, height;
public Game(String title, int width, int height) {
this.width = width;
this.height = height;
display = new Display(title, width, height);
StartGame();
}
//create the game decks
//Deck maindeck = new Deck();
public Deck faceupdeck = new Deck();
public Deck facedowndeck = new Deck();
Deck tempdeck = new Deck();
public int deckindex = 0;
public Player playerone = new Player();
public Player playertwo = new Player();
private BufferStrategy bs;
private Graphics g;
private boolean running = false;
private Thread thread;
public void StartGame() {
//setup mouse
addMouseListener (new MouseControl(display.getCanvas()));
//set players
playerone.SetPlayer(1);
playertwo.SetPlayer(2);
//set values to main deck
facedowndeck = facedowndeck.SetDeck(facedowndeck);
//shuffle the deck
facedowndeck = facedowndeck.ShuffleDeck(facedowndeck);
//hand out first deal
FirstDeal();
}
public void FirstDeal() {
int playerindex = 1;
deckindex = 1;
//deal each player 8 cards to start
for (int h = 0; h < 8; h++) {
playerone.hand.card[playerindex] = facedowndeck.card[deckindex];
facedowndeck.card[deckindex].present = false;
playerone.hand.card[playerindex].present = true;
deckindex++;
playertwo.hand.card[playerindex] = facedowndeck.card[deckindex];
facedowndeck.card[deckindex].present = false;
playerone.hand.card[playerindex].present = true;
deckindex++;
playerindex++;
//facedowndeck.Truncate(facedowndeck);
}
//put card face up
faceupdeck.card[1] = facedowndeck.card[deckindex];
deckindex++;
}
private void render() {
bs = display.getCanvas().getBufferStrategy();
if (bs == null) {
display.getCanvas().createBufferStrategy(3);
return;
}
g = bs.getDrawGraphics();
//Clear Screen
g.clearRect(0, 0, width, height);
/******* START DRAWING HERE **********/
//draw player1 deck
for (int f = 1; f < 9; f++) {
g.drawImage(playerone.hand.card[f].pic, (CARDPICX * (f - 1)) + (f * 5), 5, null);
g.drawImage(playertwo.hand.card[f].pic, (CARDPICX * (f - 1)) + (f * 5), 450, null);
}
g.drawImage(faceupdeck.card[1].pic,400, 200, null);
/*********** END DRAWING HERE ***********/
bs.show();
g.dispose();
}
private void tick() {
}
public void run() {
//init();
while (running) {
tick();
render();
}
stop();
}
public synchronized void start() {
if (running) {
return;
}
running = true;
thread = new Thread(this);
thread.start();
}
public synchronized void stop() {
if (!running) {
return;
}
running = false;
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}//class
Display.java
package crazyeightscountdown;
import java.awt.Canvas;
import java.awt.Dimension;
import javax.swing.JFrame;
//display parameters for the window
public class Display {
public JFrame frame;
public Canvas canvas;
public String title;
public int width, height;
public Display(String title, int width, int height){
this.title = title;
this.width = width;
this.height = height;
createDisplay();
}
private void createDisplay(){
frame = new JFrame(title);
frame.setSize(width, height);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
canvas = new Canvas();
canvas.setPreferredSize(new Dimension(width, height));
canvas.setMaximumSize(new Dimension(width, height));
canvas.setMinimumSize(new Dimension(width, height));
frame.add(canvas);
frame.pack();
}
public Canvas getCanvas(){
return canvas;
}
}
You have to add the MouseListener to a component: frame.addMouseListener(...)

paintComponent using old instances

I'm making a dice rolling program in java using swing. I've got 4 classes:
Die
public class Die{
private int faceValue;
public Die(){
System.out.println("Creating new Dice Object");
setValue(roll());
}
public int roll() {
int val = (int) (6 * Math.random() + 1);
setValue(val);
return val;
}
public int getValue() {
return faceValue;
}
public void setValue(int spots) {
faceValue = spots;
}
}
DieFace
public class DieFace {
private int spotDiam,wOffset,hOffset,w,h;
public int faceValue;
public DieFace(){
Die die = new Die();
this.faceValue = die.getValue();
}
public void draw(Graphics g, int paneWidth, int paneHeight){
//draw information
}
}
DieFaceComponent
public class DieFaceComponent extends JComponent{
private static final long serialVersionUID = 1L;
DieFace face;
public DieFaceComponent(){
face = new DieFace();
System.out.println("DIEFACE" + face.faceValue);
repaint();
}
public void paintComponent(Graphics g){
revalidate();
face.draw(g,super.getWidth(),super.getHeight());
}
}
DieFaceViewer
public class DieFaceViewer{
static DieFaceComponent component;
static JFrame frame = new JFrame(); // Create a new JFrame object
public static void main(String[] args){
final int FRAME_WIDTH = 500;
final int FRAME_HEIGHT = 500;
frame.setSize(FRAME_WIDTH, FRAME_HEIGHT); // Set initial size
frame.setTitle("Dice Simulator Version 1.0"); // Set title
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Set default close operation
component = new DieFaceComponent(); // Create a new DieFaceComponent object
frame.setLayout(new BorderLayout());
JButton btnRoll = new JButton("Roll!");
btnRoll.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
component = new DieFaceComponent();
}
});
frame.add(component, BorderLayout.CENTER); // Add DieFaceComponent object to frame
frame.add(btnRoll, BorderLayout.SOUTH);
frame.setVisible(true); // Set frame to visible
}
}
My problem is that even though a new Die, DieFace and DieFaceComponent object is created every time I press my btnRoll, the value used to draw the component stays the same as the initial instance. Is there something I've done wrong? Thanks in advance
You create a new instance of DieFaceComponent in your ActionListener but do nothing with it, it's never added to anything, so it's never visible. A better solution would allow you to trigger a change to DieFaceComponent, which triggered a change to DieFace which triggered a change to Die and have the whole thing just repaint itself, for example...
public class Die {
private int faceValue;
public Die() {
System.out.println("Creating new Dice Object");
//setValue(roll());
roll(); // Roll sets the value any way :P
}
public int roll() {
int val = (int) (6 * Math.random() + 1);
setValue(val);
return val;
}
public int getValue() {
return faceValue;
}
public void setValue(int spots) {
faceValue = spots;
}
}
public class DieFace {
private int spotDiam, wOffset, hOffset, w, h;
//public int faceValue;
private Die die;
public DieFace() {
die = new Die();
//Die die = new Die();
// This is pointless, as you should simply as die for it's value
// when ever you need it...
//this.faceValue = die.getValue();
}
public void roll() {
die.roll();
}
public void draw(Graphics g, int paneWidth, int paneHeight) {
//draw information
}
}
public class DieFaceComponent extends JComponent {
private static final long serialVersionUID = 1L;
DieFace face;
public DieFaceComponent() {
face = new DieFace();
//System.out.println("DIEFACE" + face.faceValue);
// Pointless, as you've probably not actually been added to anything
// that could actuallyt paint you anyway...
//repaint();
}
public void roll() {
face.roll();
repaint();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
//revalidate();
face.draw(g, super.getWidth(), super.getHeight());
}
}
Now, you can call roll on DieFaceComponent, which will call roll on DieFace which will call roll on Die, which will update the actual value. DieFaceComponent will then schedule a repaint to ensure that it's update on the screen.
And then you could use it something like...
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class DiceRoller {
public static void main(String[] args) {
new DiceRoller();
}
public DiceRoller() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new DiePane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class DiePane extends JPanel {
public DiePane() {
setLayout(new BorderLayout());
DieFaceComponent component = new DieFaceComponent();
JButton roll = new JButton("Roll");
roll.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
component.roll();
}
});
add(component);
add(roll, BorderLayout.SOUTH);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
}
Now, a better solution would be to have Die as your primary entry point, allowing it to generate notifications to interested parties and having them update themselves
Maybe something like...
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class DiceRoller {
public static void main(String[] args) {
new DiceRoller();
}
public DiceRoller() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new DiePane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class DiePane extends JPanel {
public DiePane() {
setLayout(new BorderLayout());
Die die = new Die();
DieFaceComponent component = new DieFaceComponent(die);
JButton roll = new JButton("Roll");
roll.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
die.roll();
}
});
add(component);
add(roll, BorderLayout.SOUTH);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.dispose();
}
}
public class Die {
private PropertyChangeSupport propertyChangeSupport;
private int faceValue;
public Die() {
propertyChangeSupport = new PropertyChangeSupport(this);
System.out.println("Creating new Dice Object");
//setValue(roll());
roll(); // Roll sets the value any way :P
}
public int roll() {
int val = (int) (6 * Math.random() + 1);
setValue(val);
return val;
}
public int getValue() {
return faceValue;
}
public void setValue(int spots) {
int old = faceValue;
faceValue = spots;
propertyChangeSupport.firePropertyChange("value", old, faceValue);
}
public void addPropertyChangeListener(PropertyChangeListener listener) {
propertyChangeSupport.addPropertyChangeListener(listener);
}
public void removePropertyChangeListener(PropertyChangeListener listener) {
propertyChangeSupport.addPropertyChangeListener(listener);
}
}
public class DieFace {
private int spotDiam, wOffset, hOffset, w, h;
private Die die;
public DieFace(Die die) {
this.die = die
}
public void draw(Graphics g, int paneWidth, int paneHeight) {
//draw information
}
}
public class DieFaceComponent extends JComponent {
private static final long serialVersionUID = 1L;
private DieFace face;
public DieFaceComponent(Die die) {
face = new DieFace(die);
die.addPropertyChangeListener(new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent evt) {
repaint();
}
});
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
//revalidate();
face.draw(g, super.getWidth(), super.getHeight());
}
}
}
This is a simple example of an Observer Pattern, where the Die is the generator of information, to which every body else is interested in knowing when it changes. It's also a variant of the model-view-controller paradigm

How can i add time limitation in a Maze Game using java

I am making a maze game in Java. I have made a maze board, A start point and a end point. When I reach the end point then it exit and show a winning message. But I can not add a time limitation. Suppose player have to reach the end point with 30 seconds otherwise he lose the game. Please help me.
Here is my code i have done so far.......
Maze.java
package Maze;
import javax.swing.JFrame;
public class Maze {
public static void main(String args[])
{
new Maze();
}
public Maze()
{
JFrame f= new JFrame();
f.setTitle("Maze Game");
f.add(new Board());
f.setSize(460,480);
f.setLocationRelativeTo(f);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Board.java
package Maze;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
// #SuppressWarnings("serial")
#SuppressWarnings("serial")
public class Board extends JPanel implements ActionListener
{
private Timer timer;
private Map m;
private Player p;
private boolean win=false;
long startTime = System.currentTimeMillis();
long elapsedTime;
//private String Message="";
//private Font font=new Font("Serif",Font.BOLD,50);
public Board()
{
long elapsedTime = System.currentTimeMillis() - startTime;
elapsedTime=elapsedTime/1000;
m= new Map();
p= new Player();
addKeyListener(new Al());
setFocusable(true);
timer=new Timer(25, this);
timer.start();
}
public void actionPerformed(ActionEvent e)
{
if(m.getMap(p.getTileX(), p.getTileY()).equals("f"))
{
//Message="WINNER";
win=true;
}
if(elapsedTime>=5)
win=true;
repaint();
}
public void paint(Graphics g)
{
super.paint(g);
if(!win)
{
for(int y=0;y<14;y++)
{
for(int x=0;x<14;x++)
{
if(m.getMap(x,y).equals("f"))
g.drawImage(m.getFinish(), x*32, y*32, null);
if(m.getMap(x, y).equals("w"))
g.drawImage(m.getWall(), x*32, y*32, null);
if(m.getMap(x, y).equals("g"))
g.drawImage(m.getGrass(), x*32, y*32, null);
}
}
g.drawImage(p.getPlayer(), p.getTileX()*32, p.getTileY()*32,null);
}
if(win)
{
g.drawImage(m.getWinn(), 32, 32, null);
// g.setColor(Color.ORANGE);
//g.setFont(font);
//g.drawString(Message, 150, 200);
}
}
public class Al extends KeyAdapter{
public void keyPressed(KeyEvent e){
int keycode= e.getKeyCode();
if(keycode==KeyEvent.VK_UP ){
if(!m.getMap(p.getTileX(),p.getTileY()-1).equals("w")){
p.move( 0, -1);
}
}
if(keycode==KeyEvent.VK_DOWN ){
if(!m.getMap(p.getTileX(),p.getTileY()+1).equals("w")){
p.move( 0, 1);
}
}
if(keycode==KeyEvent.VK_LEFT ){
if(!m.getMap(p.getTileX()-1,p.getTileY()).equals("w")){
p.move( -1, 0);
}
}
if(keycode==KeyEvent.VK_RIGHT ){
if(!m.getMap(p.getTileX()+1,p.getTileY()).equals("w")){
p.move( 1, 0 );
}
}
}
/* public void keyRealeased(KeyEvent e){
}
public void keyTyped(KeyEvent e){
}*/
}
}
Map.java
package Maze;
import java.awt.*;
import java.io.*;
import java.util.*;
import javax.swing.ImageIcon;
public class Map {
private Scanner m;
private String Map[]=new String[14];
private Image grass,wall,finish,winn;
public Map(){
ImageIcon img = new ImageIcon("C://project//7.jpg");
grass = img.getImage();
img = new ImageIcon("C://project//2.jpg");
wall = img.getImage();
img=new ImageIcon("C://project//hell.gif");
finish=img.getImage();
img=new ImageIcon("C://project//12.jpg");
winn=img.getImage();
openfile();
readfile();
closefile();
}
public Image getGrass()
{
return grass;
}
public Image getWall()
{
return wall;
}
public Image getFinish()
{
return finish;
}
public Image getWinn()
{
return winn;
}
public String getMap(int x, int y){
String index=Map[y].substring(x, x+1);
return index;
}
public void openfile(){
try {
m = new Scanner(new File("C://project//Map.txt"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
System.out.println("Error loading file.");
}
}
public void readfile(){
while(m.hasNext()){
for(int i=0;i<14;i++){
Map[i]=m.next();
}
}
}
public void closefile(){
m.close();
}
}
Player.java
package Maze;
import java.awt.Image;
import javax.swing.ImageIcon;
public class Player {
private int tilex,tiley;
private Image player;
public Player(){
ImageIcon img=new ImageIcon("C://project//5990.gif");
player=img.getImage();
tilex=1;
tiley=1;
}
public Image getPlayer(){
return player;
}
public int getTileX(){
return tilex;
}
public int getTileY(){
return tiley;
}
public void move(int dx, int dy ){
tilex += dx;
tiley += dy;
}
}
and here is the .txt file
Map.txt
wwwwwwwwwwwwww
wggggggwgggggw
wggwwggwgwwggw
wwgggwwwggwggw
wgwgggggggwwgw
wgggwggwwwgggw
wgggwgggwggwww
wggwggwwwggggw
wgwwgggggwwggw
wgggggwwwgwggw
wggwggggwgwwgw
wwwwgwwwwggwgw
wggggwgfgggggw
wwwwwwwwwwwwww
You can do a work around ,Add a timer class which will execute at x seconds and keep on calculating the total seconds in a variable and when the limit is crossed you can stop your program.

Categories

Resources