Java-Gaming.org Hi !
Featured games (83)
games approved by the League of Dukes
Games in Showcase (539)
Games in Android Showcase (132)
games submitted by our members
Games in WIP (603)
games currently in development
News: Read the Java Gaming Resources, or peek at the official Java tutorials
 
    Home     Help   Search   Login   Register   
Pages: [1]
  ignore  |  Print  
  Kevglass TileMaze please help...  (Read 2308 times)
0 Members and 1 Guest are viewing this topic.
Offline 9T96T9

Senior Newbie





« Posted 2007-03-05 02:16:05 »

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


Please i really nid help!!! Thnx!!!
Offline Kova

Senior Devvie





« Reply #1 - Posted 2007-03-05 18:47:06 »

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:
1  
  try { Thread.sleep(100); } catch (Exception e) {}

I doubt that this is Kev's, catching exception and doing nothing...
Offline darkprophet

Senior Devvie




Go Go Gadget Arms


« Reply #2 - Posted 2007-03-05 19:30:00 »

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

Friends don't let friends make MMORPGs.

Blog | Volatile-Engine
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline Mr_Light

Senior Devvie


Medals: 1


shiny.


« Reply #3 - Posted 2007-03-05 20:38:04 »

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

It's harder to read code than to write it. - it's even harder to write readable code.

The gospel of brother Riven: "The guarantee that all bugs are in *your* code is worth gold." Amen brother a-m-e-n.
Offline erikd

JGO Ninja


Medals: 16
Projects: 4
Exp: 14 years


Maximumisness


« Reply #4 - Posted 2007-03-05 21:08:04 »

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

you're nitpicking now  Smiley

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

Offline Kova

Senior Devvie





« Reply #5 - Posted 2007-03-05 23:38:16 »

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.
Offline 9T96T9

Senior Newbie





« Reply #6 - Posted 2007-03-06 02:26:06 »

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();     
   }
Offline kevglass

« JGO Spiffy Duke »


Medals: 212
Projects: 24
Exp: 18 years


Coder, Trainee Pixel Artist, Game Reviewer


« Reply #7 - Posted 2007-03-06 08:20:56 »

Quote
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...

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 Smiley (apart from telling him to stay away from my code).

1  
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:

1  
2  
3  
4  
5  
  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:

1  
2  
3  
4  
5  
6  
7  
8  
9  
10  
11  
12  
13  
  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

Offline 9T96T9

Senior Newbie





« Reply #8 - Posted 2007-03-08 08:35:36 »

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
Offline 9T96T9

Senior Newbie





« Reply #9 - Posted 2007-03-08 14:33:17 »

 This two doesn't work after i call it from my MainMenu class....



Quote
      this.addKeyListener(board);
quote]container.addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent e) {
            System.exit(0);
         }
      });[/quote]



Any suggestions or links for an alternative in making GUI?Huh
Games published by our own members! Check 'em out!
Legends of Yore - The Casual Retro Roguelike
Offline Kova

Senior Devvie





« Reply #10 - Posted 2007-03-08 15:44:12 »

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

1  
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?
Offline ryanm

Senior Devvie


Projects: 1
Exp: 15 years


Used to be bleb


« Reply #11 - Posted 2007-03-08 15:56:32 »

Your keyboard-reading problems sound like they could be focus-related. Try adding a call to
1  
 board.requestFocusInWindow()
Offline 9T96T9

Senior Newbie





« Reply #12 - Posted 2007-03-09 05:26:10 »

Thnx Kova and bleb, I'll try what you'd said...!!! i get no exception!!!
Offline Kova

Senior Devvie





« Reply #13 - Posted 2007-03-09 08:18:05 »

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.
Pages: [1]
  ignore  |  Print  
 
 
You cannot reply to this message, because it is very, very old.

 

Add your game by posting it in the WIP section,
or publish it in Showcase.

The first screenshot will be displayed as a thumbnail.

rwatson462 (30 views)
2014-12-15 09:26:44

Mr.CodeIt (23 views)
2014-12-14 19:50:38

BurntPizza (50 views)
2014-12-09 22:41:13

BurntPizza (84 views)
2014-12-08 04:46:31

JscottyBieshaar (45 views)
2014-12-05 12:39:02

SHC (59 views)
2014-12-03 16:27:13

CopyableCougar4 (57 views)
2014-11-29 21:32:03

toopeicgaming1999 (123 views)
2014-11-26 15:22:04

toopeicgaming1999 (113 views)
2014-11-26 15:20:36

toopeicgaming1999 (32 views)
2014-11-26 15:20:08
Resources for WIP games
by kpars
2014-12-18 10:26:14

Understanding relations between setOrigin, setScale and setPosition in libGdx
by mbabuskov
2014-10-09 22:35:00

Definite guide to supporting multiple device resolutions on Android (2014)
by mbabuskov
2014-10-02 22:36:02

List of Learning Resources
by Longor1996
2014-08-16 10:40:00

List of Learning Resources
by SilverTiger
2014-08-05 19:33:27

Resources for WIP games
by CogWheelz
2014-08-01 16:20:17

Resources for WIP games
by CogWheelz
2014-08-01 16:19:50

List of Learning Resources
by SilverTiger
2014-07-31 16:29:50
java-gaming.org is not responsible for the content posted by its members, including references to external websites, and other references that may or may not have a relation with our primarily gaming and game production oriented community. inquiries and complaints can be sent via email to the info‑account of the company managing the website of java‑gaming.org
Powered by MySQL Powered by PHP Powered by SMF 1.1.18 | SMF © 2013, Simple Machines | Managed by Enhanced Four Valid XHTML 1.0! Valid CSS!