Here is my maze code i want to add a timer in my game that if he dosent finish the maze in 60 seconds it will show a game over and the game will stop
Main class
package javamazegame;
import javax.swing.*;
public class JavaMazegame {
public JavaMazegame(){
JFrame f = new JFrame();
f.setTitle("MazeGame Version 1.0");
f.setSize(464,485);
f.add(new Board());
f.setLocationRelativeTo(null);
f.setVisible(true);
f.setResizable(false);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new JavaMazegame();
}
}
how to add a time in my maze game
Board Class
package javamazegame;
import java.awt.*;
import java.awt.event.*;
import javax.swing.Timer;
import javax.swing.*;
public class Board extends JPanel implements ActionListener{
private Timer timer;
private Map m;
private Player p;
public boolean win = false ;
private String Message = " ";
private Font font = new Font("Serif",Font.BOLD,48);
public Board(){
m = new Map();
p = new Player();
addKeyListener(new Al());
setFocusable(true);
timer = new Timer(25,this);
timer.start();
System.out.println(timer);
}
public void actionPerformed(ActionEvent e){
if(m.getMap(p.getTileX(),p.getTileY()).equals("f")){
Message = "Winner";
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("g")){
g.drawImage(m.getGrass(), x*32, y*32, null);
}
if(m.getMap(x, y).equals("w")){
g.drawImage(m.getWall(), x*32, y*32, null);
}
}
}
g.drawImage(p.getPlayer(),p.getTileX()* 32, p.getTileY() * 32,null);
}
if(win){
g.setColor(Color.GREEN);
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_W){
if(!m.getMap(p.getTileX(),p.getTileY()-1).equals("w")){
p.move(0,-1);
}
}
if(keycode == KeyEvent.VK_S){
if(!m.getMap(p.getTileX(),p.getTileY()+1).equals("w")){
p.move(0,1);
}
}
if(keycode == KeyEvent.VK_A){
if(!m.getMap(p.getTileX()-1,p.getTileY()).equals("w")){
p.move(-1,0);
}
}
if(keycode == KeyEvent.VK_D){
if(!m.getMap(p.getTileX()+1,p.getTileY()).equals("w")){
p.move(1,0);
}
}
}
public void keyRelased(KeyEvent e){
}
public void keyTyped(KeyEvent e){
}
}
}
Map Class
package javamazegame;
import java.awt.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
public class Map {
private Scanner m;
private String Map[] = new String[14];
private Image grass,
finish,
wall;
public Map(){
ImageIcon img = new ImageIcon("C://Users//Rayjay//Desktop//Assets//road.png");
grass = img.getImage();
img = new ImageIcon("C://Users//Rayjay//Desktop//Assets//wall.png");
wall = img.getImage();
img = new ImageIcon("C://Users//Rayjay//Desktop//Assets//finish.png");
finish = img.getImage();
openFile();
readFile();
closeFile();
}
public Image getGrass(){
return grass;
}
public Image getWall(){
return wall;
}
public Image getFinish(){
return finish;
}
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://Users//Rayjay//Desktop//Assets//Map.txt"));
}
catch(Exception e){
System.out.println("Error Loading Map");
}
}
public void readFile(){
while(m.hasNext()){
for(int i = 0; i < 14; i++){
Map[i] = m.next();
}
}
}
public void closeFile(){
m.close();
}
}
Player class
package javamazegame;
import java.awt.Image ;
import javax.swing.ImageIcon;
player class this my class for player
public class Player {
private int tileX,tileY;
private Image player;
public Player(){
ImageIcon img = new ImageIcon("C://Users//Rayjay//Desktop//Assets//player.png");
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;
}
}
You could use the Timer class. There are several possibilities how you could work with this class. Here is the doc to Timer.
Related
//This is the human class
//I have added runnable method to make it work but the AI is not moving.
import java.awt.Graphics2D;
import java.awt.event.KeyEvent;
import java.util.Random;
import java.awt.Color;
public class Human implements Runnable{
private double position=100000;
private double xa=0;
private int attack=0;
private Game game;
private long time;
private long lastTime;
private long MIN_DELAY;
private int health;
private int combo;
private Random r;
Thread thread;
public void start(){
thread = new Thread (this);
thread.start();
public void stop(){
thread.stop();
}
public void run1(){
Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
while (true)
{
game.move();
if (Game.() < 0){
}
try
{
Thread.sleep (10);
}
catch (InterruptedException ex)
{
break;
}
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
}
}
public Human(Game game){
this.game = game;
MIN_DELAY = 150;
lastTime=0;
health=100;
combo=0;
r = new Random();
}
public Human getPlayer(){
return this;
}
public double getPosition(){
return position;
}
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_LEFT){
xa = -1;
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT){
xa = 1;
}
if(e.getKeyCode()== KeyEvent.VK_Z){
attack = 1;
}
if(e.getKeyCode()== KeyEvent.VK_X){
attack = 2;
}
if(e.getKeyCode()== KeyEvent.VK_C){
attack = 3;
}
}
public String printHealth(){
String st = "Human Health: ";
st = st + Integer.toString(health);
return st;
}
public String printCombo(){
String st = "Combo: ";
st = st + Integer.toString(combo);
return st;
}
public boolean isAlive(){
if(health>0){
return true;
}else{
return false;
}
}
public int attack(){
int dam = 0;
time = System.currentTimeMillis();
if(time-lastTime>MIN_DELAY){
System.out.println("COMBO" + combo);
if(combo<3){
if(attack==1){
System.out.println("Human Punch");
dam = r.nextInt(6-1)+1;;
combo++;
}else if(attack==2){
System.out.println("Human Kick");
dam = r.nextInt(11-5)+5;
combo++;
}else if(attack==3){
System.out.println("Human Uppercut");
dam = r.nextInt(16-10)+10;
combo++;
}
}else{
if(attack == 1){
System.out.println(" SUPER Human PUNCH");
dam = r.nextInt(11-1)+1;
combo = 0;
}else if(attack ==2){
System.out.println(" SUPER Human KICK");
dam = r.nextInt(21-10)+10;
combo = 0;
}else if(attack == 3){
System.out.println(" SUPER Human UPPERCUT");
dam = r.nextInt(31-20)+20;
combo = 0;
}
}
}
lastTime = time;
return dam;
}
public void keyReleased(KeyEvent e) {
xa = 0;
attack = 0;
}
public int getAttack(){
return attack;
}
public void paint(Graphics2D g) {
g.fillRect(position-30, 200, 30, 30);
}
public void move(double opp) {
//if(time-lastTime>mDelay){
if (position + xa > 30 && position + xa < opp-17000)
position = position + xa/500;
//}
}
public int getHealth(){
return health;
}
public void takeHealth(int dam){
health = health - dam;
combo = 0;
}
// private Thread t;
public void run() {
try {
move(game.getAIPosition());
// Let the thread sleep for a while.
Thread.sleep(1000);
} catch (InterruptedException e) {
System.out.println("Human Thread interrupted.");
}
System.out.println("Human Thread exiting.");
}
/*public void start ()
{
System.out.println("Starting Human" );
if (t == null)
{
t = new Thread (this);
t.start ();
}
}*/``
// This is the game class
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.geom.Ellipse2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
#SuppressWarnings("serial")
public class Game extends JPanel{
public Human human = new Human(this);
public AIPlayer ai = new AIPlayer(this);
public Game(){
setPreferredSize(new Dimension(WIDTH, HEIGHT));
setFocusable(true);
requestFocus();
init();
addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
human.keyReleased(e);
}
#Override
public void keyPressed(KeyEvent e) {
human.keyPressed(e);
}
});
setFocusable(true);
}
double x=ai.getPosition();
int z=75; //Enemy Position
int y = 200;
public void move(){
human.move(ai.getPosition());
ai.move((ai.getPosition()-human.getPosition()), human.getHealth(), human.getPosition()); //CAN'T GET THIS TO WORK WITH HUMAN MOVING
System.out.println("Human position: " + human.getPosition());
System.out.println("AI Position: " + ai.getPosition());
System.out.println("Range: " + (ai.getPosition()-human.getPosition()));
}
public void makeSound(){
Random r = new Random();
int x = r.nextInt(10);
if(x==5 || x==6){
ai.makeSound(human.getHealth());
}
}
public double getAIPosition(){
return ai.getPosition();
}
public double getHumanPosition(){
return human.getPosition();
}
public int getHumanHealth(){
return human.getHealth();
}
public double getDistance(){
return (ai.getPosition()-human.getPosition());
}
public void attack(){
int hDec = human.getAttack();
System.out.println("Human Decision: " + hDec);
if(checkDistance(hDec)){
ai.takeHealth(human.attack());
}
human.takeHealth(ai.attack(ai.getPosition()-human.getPosition()));
ai.attack(ai.getPosition()-human.getPosition());
}
public boolean checkDistance(int mve){
double dist = ai.getPosition() - human.getPosition();
if(mve==1 && dist<=25364){
return true;
}else if(mve ==2 && dist<=29040){
return true;
}else if(mve==3 && dist<=20536){
return true;
}else{
return false;
}
}
public void decreaseAnger(){
ai.decreaseAnger();
}
public boolean gameAlive(){
if(ai.isAlive()&&human.isAlive()){
return true;
}else{
return false;
}
}
public void displayDetails(Graphics g){
Font myFont = new Font("Courier New", 1, 17);
g.setColor(Color.YELLOW);
g.setFont(myFont);
g.drawString(human.printHealth(), 10,15);
g.drawString(human.printCombo(), 10, 30);
g.drawString(ai.printHealth(), 550,15);
g.drawString(ai.printCombo(), 550, 30);
g.drawString(ai.printAnger(), 550, 45);
}
public static void main(String[] args) throws Exception {
TODO Auto-generated method stub
JFrame frame = new JFrame("Mini Tekken");
Game game = new Game();
frame.add(game);
frame.setSize(300, 300);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
while (game.gameAlive()) {
game.move();
game.attack();
game.decreaseAnger();
game.repaint();
game.makeSound();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args){
Game game = new Game();
JFrame window = new JFrame("Mini-Tekken");
window.setContentPane(game);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setResizable(false);
window.pack();
window.setLocationRelativeTo(null);
window.setVisible(true);
while(game.gameAlive()){
game.move();
game.attack();
game.decreaseAnger();
game.makeSound();
game.repaint();
}
}
//Dimensions
public static final int WIDTH = 736;
public static final int HEIGHT = 309;
BufferedImage background;
BufferedImage playerOne;
BufferedImage playerTwo;
public void paintComponent(Graphics g){
super.paintComponent(g);
if (background != null) {
g.drawImage(background, 0, 0, null);
}
if(playerOne != null){
g.drawImage(playerOne, ((int)human.getPosition()/500), 200, null);
}
if(playerTwo != null){
g.drawImage(playerTwo, ((int)ai.getPosition()/500), 210, null);
}
displayDetails(g);
}
private void init() {
try {
background = ImageIO.read(getClass().getResourceAsStream("/images/background.jpg"));
playerOne = ImageIO.read(getClass().getResourceAsStream("/images/p1.fw.png"));
playerTwo = ImageIO.read(getClass().getResourceAsStream("/images/p2.fw.png"));
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
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(...)
For a school computer project I decided make a Pac-Man style game in Java (with two other people). None of us have much experience, so we've essentially been teaching ourselves up to this point. We've made quite a bit of progress, but we seem to have reached a standstill at this point.
How can we make the candies disappear when Fatman runs over them? We've tried using repaint, but we can't seem to get things to work properly.
(I have other things I need help on but they are in different questions)
Thank you for your help!
Here is our code so far:
Maze Class:
package Fatman;
import javax.swing.*;
public class Maze {
public static void main(String[] args){
new Maze();
}
public Maze(){
JFrame f = new JFrame();
f.setTitle("Fatman!");
f.add(new Board());
f.setSize(816, 838);
f.setLocationRelativeTo(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Map Class
package Fatman;
import java.awt.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
public class Map {
private Scanner m;
private String Map[] = new String[25];
private Image spaceregcandy,
srcb,
safehouse,
spacebigcandy,
blackspace,
space,
portal1,
portal2,
wall;
public Map(){
ImageIcon img = new ImageIcon("C:\\Users\\Martin\\Desktop\\Fatman Project\\spaceregcandy.png");
spaceregcandy = img.getImage();
//image icon has already been initiated, so it doesn't have to be written again
img = new ImageIcon("C:\\Users\\Martin\\Desktop\\Fatman Project\\spaceregcandyblue.png");
srcb = img.getImage();
img = new ImageIcon("C:\\Users\\Martin\\Desktop\\Fatman Project\\safehouse.png");
safehouse = img.getImage();
img = new ImageIcon("C:\\Users\\Martin\\Desktop\\Fatman Project\\wall232x.png");
wall = img.getImage();
img = new ImageIcon("C:\\Users\\Martin\\Desktop\\Fatman Project\\spacebigcandy.png");
spacebigcandy = img.getImage();
img = new ImageIcon("C:\\Users\\Martin\\Desktop\\Fatman Project\\blackspace.png");
blackspace = img.getImage();
img = new ImageIcon("C:\\Users\\Martin\\Desktop\\Fatman Project\\space.png");
space = img.getImage();
img = new ImageIcon("C:\\Users\\Martin\\Desktop\\Fatman Project\\portal1.png");
portal1 = img.getImage();
img = new ImageIcon("C:\\Users\\Martin\\Desktop\\Fatman Project\\portal2.png");
portal2 = img.getImage();
openFile();
readFile();
closeFile();
}
public Image getSpaceregcandy(){
return spaceregcandy;
}
public Image getSrcb(){
return srcb;
}
public Image getSafehouse(){
return safehouse;
}
public Image getWall(){
return wall;
}
public Image getSpacebigcandy(){
return spacebigcandy;
}
public Image getBlackspace(){
return blackspace;
}
public Image getSpace(){
return space;
}
public Image getPortal1(){
return portal1;
}
public Image getPortal2(){
return portal2;
}
public String getMap(int x, int y){
String index = Map[y].substring(x, x + 1);
return index;
//in y position, if y = 2, goes to second row (substring gets x position)
}
public void openFile(){
try{
m = new Scanner(new File("C:\\Users\\Martin\\Desktop\\Fatman Project\\map3.txt"));
}catch(Exception e){
System.out.println("error loading map");
}
}
public void readFile(){
while(m.hasNext()){
for(int i = 0; i < 25; i++){
Map[i] = m.next();
}
}
}
public void closeFile(){
m.close();
}
}
Board Class
package Fatman;
import java.awt.*;
import java.awt.event.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.*;
public class Board extends JPanel implements ActionListener{
/**
*
*/
private static final long serialVersionUID = 1L;
private Timer timer;
private Image player;
private Map m;
private Player p;
public Board(){
m = new Map();
p = new Player();
addKeyListener(new Al());
setFocusable(true);
timer = new Timer(1, this);
timer.start();
}
public void actionPerformed(ActionEvent e){
repaint();
}
public void paint(Graphics g){
super.paint(g);
for(int y = 0; y < 25; y++){
for(int x = 0; x <25; x++){
if(m.getMap(x, y).equals("o")){
g.drawImage(m.getSpaceregcandy(), x *32, y *32, null);
}
if(m.getMap(x, y).equals("O")){
g.drawImage(m.getSrcb(), x *32, y *32, null);
}
if(m.getMap(x, y).equals("x")){
g.drawImage(m.getWall(), x *32, y *32, null);
}
if(m.getMap(x, y).equals("H")){
g.drawImage(m.getSafehouse(), x *32, y *32, null);
}
if(m.getMap(x, y).equals("C")){
g.drawImage(m.getSpacebigcandy(), x *32, y *32, null);
}
if(m.getMap(x, y).equals("b")){
g.drawImage(m.getBlackspace(), x *32, y *32, null);
}
if(m.getMap(x, y).equals("s")){
g.drawImage(m.getSpace(), x *32, y *32, null);
}
if(m.getMap(x, y).equals("p")){
g.drawImage(m.getPortal1(), x *32, y *32, null);
}
if(m.getMap(x, y).equals("P")){
g.drawImage(m.getPortal2(), x *32, y *32, null);
}
}
}
g.drawImage(p.getPlayer(), p.getTileX() * 32, p.getTileY() * 32, null);
}
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("x")){
if(!m.getMap(p.getTileX(), p.getTileY() -1).equals("b")){
}
p.move(0, -1);
System.out.println(m.getMap(p.getTileX(), p.getTileY()));
}
}
if(keycode == KeyEvent.VK_DOWN){
if(!m.getMap(p.getTileX(), p.getTileY() +1).equals("x")){
if(!m.getMap(p.getTileX(), p.getTileY() +1).equals("b")){
p.move(0, 1);
System.out.println(m.getMap(p.getTileX(), p.getTileY()));
}
}
}
if(keycode == KeyEvent.VK_LEFT){
if(!m.getMap(p.getTileX() - 1, p.getTileY()).equals("x")){
if(!m.getMap(p.getTileX() - 1, p.getTileY()).equals("b")){
p.move(-1, 0);
System.out.println(m.getMap(p.getTileX(), p.getTileY()));
}
}
}
if(keycode == KeyEvent.VK_RIGHT){
if(!m.getMap(p.getTileX() + 1, p.getTileY()).equals("x")){
if(!m.getMap(p.getTileX() + 1, p.getTileY()).equals("b")){
p.move(1, 0);
System.out.println(m.getMap(p.getTileX(), p.getTileY()));
}
}
}
}
public void keyReleased(KeyEvent e){
}
public void keyTyped(KeyEvent e){
}
}
}
Player Class
package Fatman;
import java.awt.Image;
import javax.swing.ImageIcon;
public class Player {
private int tileX, tileY;
private int dx, dy;
private Image player;
public Player(){
ImageIcon img = new ImageIcon("C:\\Users\\Martin\\Desktop\\Fatman Project\\FATMANsimplified32xbrown.png");
player = img.getImage();
tileX = 12;
tileY = 18;
}
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;
}
}
Any ideas?
well i don't think you could be two thirds of a 3 man group, unless you ate one of your members, but on saying that....
Your question is more suited to https://gamedev.stackexchange.com/ as its more of a game development question in my opinion.
However.what you could do, is set the candies position offscreen (for example: candy.x = -100;)
on saying that though, where is your game loop?
public void startGame(){
} public void stopGame(){
} public void update(){ //forces graphics and user input to update the
games state }
also consider going to www.java-gaming.org they have awesome tutorials to help you out.
Nothing in Player.move() is eating dots. You have to update the value of variable Map.Map[] to keep track of what it's supposed to represent. Otherwise this code is just empty words/symbols that hack at doing one instruction from the programmer at a time but don't use the power of a programming language to let the computer do work according to the conditions it meets.
This my code for the simple maze game. Its being compiled and class file of MazeGame.java and Board.java are being created but not of Player.java and Map.java. The code is being compiled error free but its not running. Please help me out.
//MazeGame.java
package mygame;
import javax.swing.*;
public class MazeGame {
public static void main(String[] args) {
new MazeGame();
}
public MazeGame() {
JFrame f= new JFrame();
f.setTitle("Maze Game");
f.setSize(450,450);
f.setLocationRelativeTo(null);
f.add(new Board());
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
//Board.java
package mygame;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.awt.*;
public class Board extends JPanel implements ActionListener {
private Timer timer;
private Map m;
private Player p;
private boolean win=false;
private String Message="";
private Font font = new Font("Comic Sans",Font.BOLD,50);
public Board() {
m = new Map();
p = new Player();
addKeyListener(new Al());
setFocusable(true);
timer = new Timer(25,this);
timer.start();
}
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("g")) {
g.drawImage(m.getGrass(),x*32,y*32,null);
}
if(m.getMap(x,y).equals("w")) {
g.drawImage(m.getWall(),x*32,y*32,null);
}
}
}
g.drawImage(p.getPlayer(),p.getTileX()*32,p.getTileY()*32,null);
}
if(win)
{
g.setColor(Color.BLUE);
g.setFont(font);
g.drawString(Message,100,300);
}
}
public class Al extends KeyAdapter {
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if((keyCode==KeyEvent.VK_W) || (keyCode==KeyEvent.VK_UP)) {
if(!(m.getMap(p.getTileX(),p.getTileY()-1).equals("w"))) {
p.move(0,-1);
}
}
if((keyCode==KeyEvent.VK_S) || (keyCode==KeyEvent.VK_DOWN)) {
if(!(m.getMap(p.getTileX(),p.getTileY()+1).equals("w"))) {
p.move(0,1);
}
}
if((keyCode==KeyEvent.VK_A) || (keyCode==KeyEvent.VK_LEFT)) {
if(!(m.getMap(p.getTileX(),p.getTileY()-1).equals("w"))) {
p.move(-1,0);
}
}
if((keyCode==KeyEvent.VK_D) || (keyCode==KeyEvent.VK_RIGHT)) {
if(!(m.getMap(p.getTileX(),p.getTileY()-1).equals("w"))) {
p.move(1,0);
}
}
}
}
public void actionPerformed(ActionEvent e) {
if(m.getMap(p.getTileX(),p.getTileY()).equals("f")) {
Message = "WINNER!!!";
win = true;
}
repaint();
}
}
//Map.java
package mygame;
import java.util.*;
import java.io.*;
import java.awt.*;
import java.awt.*;
public class Map {
private Scanner s;
private String Map[] = new String[14];
private Image grass,wall,finish;
public Map() {
ImageIcon img = new ImageIcon("G://sonali_java//mygame//grass.png");
grass = img.getImage();
img = new ImageIcon("G://sonali_java//mygame//wall.png");
wall = img.getImage();
img = new ImageIcon("G://sonali_java//mygame//finish.png");
finish = img.getImage();
openFile();
readFile();
closeFile();
}
public String getMap(int x,int y) {
String index = Map[y].substring(x,x+1);
return index;
}
public Image getGrass() {
return grass;
}
public Image getWall() {
return wall;
}
public Image getFinish() {
return finish;
}
public void openFile() {
try {
s= new Scanner(new File("G://sonali_java//mygame//Map.txt"));
}
catch(Exception e) {
System.out.println("Error Loading File!!!!");
}
}
public void readFile() {
while(s.hasNext()) {
for(int i=0; i<14; i++) {
Map[i] = s.next();
}
}
}
public void closeFile() {
s.close();
}
}
//Player.java
package mygame;
import java.awt.*;
public class Player {
private int tileX,tileY;
private Image player;
public Player() {
tileX=1;
tileY=1;
ImageIcon img = new ImageIcon("G://sonali_java//mygane//object.png");
player = img.getImage();
}
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;
}
}
I dont want to be mad but you are defining different folder locations
in some places "G://sonali_java//mygane//object.png", check "mygaNe"
in some places "G://sonali_java//mygame//Map.txt", check "mygaMe"
Are you sure while loading it does not throw a NullPointerException ?
Are you aware that you can, place code like
public void draw(Graphics g){
g.drawImage(playerImg, getX(), getY(), null);
}
in your player class, thus leaving the player class with drawing the player and simply calling the players draw method inside your Board paint method? This can also be done for drawing the map. Remember to call the draw methods in the paint method.
ALSO, THIS
ImageIcon img = new ImageIcon("G://sonali_java//mygane//object.png");
check your directory location
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.