Kevglass TileMaze please help...

[quote]I’m working on a maze game from kevglass tutorial… Now, i came working to the Main menu… My problem is when i click my Start button to access the game class it loads the game but the game was distorted and the keyboard doesn’t work… Please my code for MainMenu and Game class…

MainMenu class
import java.awt.;
import javax.swing.
;
import java.awt.event.;
import java.lang.
;

public class MainMenu extends JFrame implements ActionListener {
private JButton b1, b2, b3;
private JLabel label1;

public MainMenu() {
    super("Maze Game");
 
    Container contentPane = getContentPane();
    contentPane.setLayout(null);
    b1 = new JButton("Start Game");
    b1.setActionCommand("start");
    contentPane.add(b1);

    b2 = new JButton("Help");
    b2.setActionCommand("help");
    contentPane.add(b2);

    b3 = new JButton("Exit");
    b3.setActionCommand("exit");
    contentPane.add(b3);

    ImageIcon icon = new ImageIcon("background.jpg");
    label1 = new JLabel(icon);
    contentPane.add(label1);
                                          
    Insets insets = contentPane.getInsets();
    label1.setBounds(0, 0, 640, 480);

    b1.setBounds(15 + insets.left, 5 + insets.top,   105, 22);
    b2.setBounds(15 + insets.left, 35 + insets.top,  105, 22);
    b3.setBounds(15 + insets.left, 65 + insets.top,  105, 22);
                                                                                    
    b1.addActionListener(this);
    b2.addActionListener(this);
    b3.addActionListener(this);
    
    setSize(640,480);  
    show();

}

public void actionPerformed(ActionEvent e)
{

    if (e.getActionCommand() == "start")
    {
      Game game=new Game();
      game.gameLoop();
    }

    if (e.getActionCommand() == "help")
    {	
    	//
    }

    if (e.getActionCommand() == "exit")
    {
       System.exit(0);
    }
   
}


public static void main(String args[])
{
	MainMenu mainmenu=new MainMenu();

    mainmenu.addWindowListener(new WindowAdapter(){
           public void windowClosing(WindowEvent e)
           {
               System.exit(0);
           }
        }
    );
 }

}

Game Class
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.event.*;
import java.awt.image.BufferStrategy;
import java.util.ArrayList;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.Font;
import java.util.Random;
import java.applet.AudioClip;
import java.net.URL;
import java.net.MalformedURLException;

public class Game extends Canvas {

private BufferStrategy strategy;
private ArrayList entities = new ArrayList();
private Hero albert;
private AlienEntity zomb1;
private AlienEntity zomb2;
private String message = "";
public boolean waitingForKeyPress = true;
private Keyb board;
private Map map;
private int fontSize = 30;	
        
public Game()  {
	JFrame container = new JFrame("CSCI15");
	JPanel panel = (JPanel) container.getContentPane();
	board = new Keyb();
	panel.setPreferredSize(new Dimension(800,600));
	panel.setLayout(null);
	setBounds(0,0,800,600);
	panel.add(this);
	setIgnoreRepaint(true);
	container.pack();
	container.setResizable(false);
	container.setVisible(true);
	container.addWindowListener(new WindowAdapter() {
		public void windowClosing(WindowEvent e) {
			System.exit(0);
		}
	});

	this.addKeyListener(board);
	requestFocus();
	createBufferStrategy(2);
	strategy = getBufferStrategy();

	initEntities();		
}

public void startGame() {
	
	//startLoadingSounds();
	entities.clear();	
	initEntities();
	board.left = false;
	board.right = false;
	board.up = false;
	board.down = false;
	
	
}

public void initEntities() {
	map = new Map();
	albert = new Hero(this,"res/hero_down.gif", map, 5, 5);
	entities.add(albert);
zomb1 = new AlienEntity(this,"res/zombie1.gif",map,15,14);
	entities.add(zomb1);

zomb2 = new AlienEntity(this,"res/zombie1.gif",map,24,1);
	entities.add(zomb2);

//loopClip = soundList.getClip(chosenFile);

}



public void gameLoop() {
	boolean gameRunning = true;	
	while (gameRunning) {
	    Graphics2D g = (Graphics2D) strategy.getDrawGraphics();
	    g.setColor(Color.black);
	    g.fillRect(0,0,800,600);
		    for (int p=0;p<entities.size();p++) 
		    {
			    for (int s=p+1;s<entities.size();s++)
			     {
				    Entity me = (Entity) entities.get(s);
				    Entity him = (Entity) entities.get(p);
				    if (me.collidesWith(him))
				     {
				        me.collidedWith(him);
				        him.collidedWith(me);
				     }
			     }
		    }


	    map.paint(g);
	    albert.paint(g);
	    zomb1.paint(g);
	    zomb2.paint(g);
	    g.dispose();
	    strategy.show();	
	    try { Thread.sleep(100); } catch (Exception e) {}
	    logicHero();
	    logicAlien();
    }       
}


public void logicHero() {

	int dx = 0;
	int dy = 0;

	if (board.left) {
		dx -= 1;
	}

	if (board.right) {
		dx += 1;
	}
	if (board.up) {
		dy -= 1;
	}
	if (board.down) {
		dy += 1;
	}

	if ((dx != 0) || (dy != 0)) {
		albert.move(dx,dy);
	}
}


public void logicAlien() {

	Random randomNumbers = new Random();
	int dx;
	int dy;

// dx = ( randomNumbers.nextInt( 3 ) - 1);
// dy = ( randomNumbers.nextInt( 3 ) - 1);
// dx = ( randomNumbers.nextInt( 300 / 100 ) - 1);
// dy = ( randomNumbers.nextInt( 300 / 100 ) - 1);
dx = ( randomNumbers.nextInt( 30/10)-1);
dy = ( randomNumbers.nextInt( 30/10 )-1);
zomb1.moveZ1(dx,dy);
zomb2.moveZ1(dx,dy);
}

public void notifyDeath() {
	//code here	}

public void notifyWon() {
	//code here	}	

}
[/quote]
Please i really nid help!!! Thnx!!!

posting a bounch of code is a bad sign… you don’t even know where to look. Well you probably have tutorial source for that chapter (don’t actually know, never seen it, maybe it even doesn’t have chapters) and you can compare it to your code then. If you don’t succeed, go back to last chapter where your stuff works and start over with more understanding.

one more thing:


  try { Thread.sleep(100); } catch (Exception e) {}

I doubt that this is Kev’s, catching exception and doing nothing…

Thats common practice for InterruptedException on sleep if your doing a game loop. What else are you supposed to do with it?!

You dont exactly want to end the game simply because the OS decided to interrupt the thread due to schedualing…

then you still want to put in a comment with /* we are not gonna do anything with this because . */

you’re nitpicking now :slight_smile:

Doing nothing with an InterruptedException in this case is so common and logical that I’d rather not waste any space on useless comments,but maybe that’s just me…

I’m for commenting at least if not logging it every time. Furthermore this is a tutorial for people new to games (and java probably) so it’s better to teach them that they never do this or they will do it automaticly every time, everywhere.

I think the problem is in my Game Class… because I already have a JFrame in my MainFrame class. So, when i call Game Class from my MainFrame class the drawing became distorted and the controls for the entity also doesn’t… Maybe converting my Game class into a JPanel will work… But the problem is Game class extends Canvas… Is it possible to place a Canvas over a JPanel???

I don’t understand this lines:::

JPanel panel = (JPanel) container.getContentPane();
setIgnoreRepaint(true);
requestFocus();
createBufferStrategy(2);
strategy = getBufferStrategy();

public Game() {
JFrame container = new JFrame(“CSCI15”);
JPanel panel = (JPanel) container.getContentPane(); // I don’t know what this exactly do…
board = new Keyb();
panel.setPreferredSize(new Dimension(800,600));
panel.setLayout(null);
setBounds(0,0,800,600);
panel.add(this);
setIgnoreRepaint(true); – What’s this for???
container.pack();
container.setResizable(false);
container.setVisible(true);
container.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});

  this.addKeyListener(board);
  requestFocus();
  createBufferStrategy(2);
  strategy = getBufferStrategy();

  initEntities();      

}

Totally agree. I think this is very much a special case that should be shown as such.

However, maybe we could try and help the Op :slight_smile: (apart from telling him to stay away from my code).


setIgnoreRepaint(true); 

Is to tell AWT/Swing not to automatically repaint your panel because you’ll be doing the repainting yourself using buffered strategy.

I think in your original code this:


  if (e.getActionCommand() == "start")
        {
          Game game=new Game();
          game.gameLoop();
        }

Is blocking the AWT event thread (that which delivered you your actionPerformed event) by calling the game loop directly. You might try this:


  if (e.getActionCommand() == "start")
        {
          setVisible(false);
          dispose();

          Thread t = new Thread() {
                   public void run() {
                           Game game=new Game();
                           game.gameLoop();
                   }
           }
           t.start();
        }

Which would start the game in a new thread allow the AWT event thread to return and let events etc happen. Not sure why this would screw up rendering tho - since the Game is running in a completely different frame. I’ve added the setVisible() and dispose() stuff to hide your game menu when the game starts - that “might” help.

The solution I expect would work better would be to not use AWT/Swing for game menu, instead rendering the menu using the buffer strategy in the main Game class, introducing game states etc. However, that’d probably require another tutorial and I’m just out of time atm.

Kev

Now, i got one more problem… When i enter into the game class out from my mainmenu class, the game itself somehow lose the focus of keyboard… The keyboard which controls my entity doesn’t work…

Other entities like those zombies were working but only the main character that doesn’t who needs keyboard inputs…

Please tell me what can be the possible cause…

Thnx

This two doesn’t work after i call it from my MainMenu class…

[quote] this.addKeyListener(board);
[/quote]
quote]container.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
[/quote]
Any suggestions or links for an alternative in making GUI???

your MainMenu extends JFrame… (is a JFrame)
instead of using window listener, for exiting when you shutdown your JFrame window you can write:


setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

…and I don’t know why .addWindowListener(…) doesn’t work, code is fine. Same thing for addKeyListener(), what exceptions do you get?

Your keyboard-reading problems sound like they could be focus-related. Try adding a call to

 board.requestFocusInWindow()

Thnx Kova and bleb, I’ll try what you’d said…!!! i get no exception!!!

if you get no exception, then how do you know those line of code doesn’t work?? I thought you had problems compiling… anyway then it’s definitely focus problem, on component that has keylistener you need to call requestfocus(). Your JPanel or whatever you use as a container probably steals focus from JFrame.