使用带有键绑定的hashmap,控制游戏角色

时间:2014-12-27 14:28:23

标签: java nullpointerexception hashmap key-bindings pacman

我正在努力用Java编写一个简单的pacman游戏,但是在尝试实现主角移动控制的某些机制时我陷入了停顿。在几次尝试失败之后,我决定遵循这个解决方案:< How Do I Use KeyEventDispatcher>在将它应用到我的项目后,我仍然没有任何动作。似乎pacman的坐标根本没有变化。 示例答案代码可以正常工作。

我没有在下面的示例代码中包含类Map,因为它所做的只是读取用于绘制迷宫的地图txt文件,但它工作正常。

如果有人帮助过我,我将非常感激。

PacmanMaze.java

    import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.HashMap;

import javax.swing.*;

@SuppressWarnings("serial")
public class PacmanMaze extends JPanel   {
private HashMap<Direction, Boolean> directionMap;
private Map m;

private Timer t;

 private Pacman pac;

 enum Direction {//specifying possible moves here

        UP(KeyEvent.VK_UP, 0, -1), DOWN(KeyEvent.VK_DOWN, 0, 1),
        LEFT(KeyEvent.VK_LEFT, -1, 0), RIGHT(KeyEvent.VK_RIGHT, 1, 0);
        private int keyCode;
        private int xDirection;
        private int yDirection;

        private Direction(int keyCode, int xDirection, int yDirection) {
            this.keyCode = keyCode;
            this.xDirection = xDirection;
            this.yDirection = yDirection;
        }

        public int getKeyCode() {
            return keyCode;
        }

        public int getXDirection() {
            return xDirection;
        }

        public int getYDirection() {
            return yDirection;
        }
    }

public PacmanMaze()  {
    setFocusable(true);
   // requestFocus();
    directionMap = new HashMap<Direction, Boolean>();
    m=new Map();
    pac=new Pacman();
     for (Direction direction : Direction.values()) {
            directionMap.put(direction, false);
        }
    setKeyBindings();
    t=new Timer(25,new TimerListener());
    t.start();


}
public void setKeyBindings()
{
    InputMap inMap= getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
    ActionMap actMap= getActionMap();
    for (final Direction direction : Direction.values()) {
        KeyStroke pressed = KeyStroke.getKeyStroke(direction.getKeyCode(), 0, false);
        KeyStroke released = KeyStroke.getKeyStroke(direction.getKeyCode(), 0, true);
        inMap.put(pressed, direction.toString() + "pressed");
        inMap.put(released, direction.toString() + "released");
        actMap.put(direction.toString() + "pressed", new AbstractAction() {

            private static final long serialVersionUID = 1L;

            @Override
            public void actionPerformed(ActionEvent e) {
                directionMap.put(direction, true);
            }
        });
        actMap.put(direction.toString() + "released", new AbstractAction() {

            private static final long serialVersionUID = 1L;

            @Override
            public void actionPerformed(ActionEvent e) {
                directionMap.put(direction, false);
            }
        });
    }

}
/**
 * funkcja rysująca planszę gry na podstawie wczytanej wcześniej tablicy
 * @param g -element grafiki
 */
public void paintComponent(Graphics g){
    super.paintComponent(g);
    //here the map is being drawn based on the input txt file with elements location (works properly)
    Dimension d=this.getSize();
    int szer= d.width;
     int wys= d.height;
     int cellWidth=szer/28;
     int cellHeight=wys/31;
    for(int y=0; y<31;++y)
    {
        for (int x=0; x<28; ++x){
            //wall
            if(m.getMap(x, y).equals("W"))
            {
                g.setColor(Color.PINK);
                g.fillRect(x*cellWidth, y*cellHeight, cellWidth,cellHeight);
            }
            //ghosts were supposed to be here
            else if(m.getMap(x,y).equals("G"))
            {
                g.setColor(Color.WHITE);
                g.fillRect(x*cellWidth, y*cellHeight, cellWidth,cellHeight);
            }
            //pacman's initial position
            else if(m.getMap(x,y).equals("P"))
            {
                pac.setc(x, y);

                //g.drawImage(pac.getPacman(),x*cellWidth,y*cellHeight, cellWidth, cellHeight, null);
            }
            //permitted area for pacman's movement
            else{
                g.setColor(Color.WHITE);
                g.fillRect(x*cellWidth, y*cellHeight, cellWidth,cellHeight);
                //g.drawImage(m.getMelem(), x*30,y*30,null);
            }
        }

    }
g.drawImage(pac.getPacman(),pac.getcX()*cellWidth, pac.getcY()*cellHeight, cellWidth, cellHeight, null);


}

private class TimerListener implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent e) {
        boolean moved = false;
        for (Direction direction : Direction.values()) {
            if (directionMap.get(direction)) {
                pac.makeMove(direction.getXDirection(),direction.getYDirection());
                moved = true;
            }
        }
        if (moved) {


            repaint(); 
            //repaint();
        }
    }
}

}

Pacman.java

import java.awt.Image;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
public class Pacman {
private Image pacpac;
private int cX;//coordinates
private int cY;

    public Pacman() {
        try {
            pacpac=ImageIO.read(new File("pac.jpg"));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // TODO Auto-generated constructor stub
    }

public Image getPacman()
{
    return pacpac;
}

public int getcY(){
    return cY;
}

public int getcX(){
    return cX;
}
public void setc(int nx, int ny){
    cX=nx;
    cY=ny;
}
//changing coordinates when pacman moved
public void makeMove(int x, int y)
{
this.cX+=x;
this.cY+=y;
}
}

Gamemode.java - 启动游戏视图

import java.awt.*;

import javax.swing.JFrame;
/**
 * Launching game
 *
 */

public class Gamemode extends JFrame {
    public Gamemode() 
    {
        super("Board");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setPreferredSize(new Dimension(640,480));
            PacmanMaze maze = new PacmanMaze();
            add(maze);
        setLocationRelativeTo(null);
        pack();

        }

    public static void main(String[] args) {


        EventQueue.invokeLater(new Runnable() {
            public void run() {
                Gamemode window=new Gamemode();
                window.setVisible(true);
            }

        });

        }
}

0 个答案:

没有答案