我正在写一个小型自上而下的游戏,玩家通过一个二维阵列移动,由箭头键控制。
我一定看过关键绑定的每个教程,但是我无法获得更新主要'floor'对象的键绑定。救命!对不起文本的墙,但我认为这三个文件的上下文是有帮助的。谢谢!
编辑:SSCCE
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package palace.hero;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SSCCE
{
public static void main(String[] args)
{
JPanel gridPanel = new JPanel();
int xCoord = 0;
int yCoord = 0;
//Key Bindings
gridPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_W, 0), "up");
gridPanel.getActionMap().put("up", new SSCCEKA(xCoord, yCoord, "up"));
gridPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_S, 0), "down");
gridPanel.getActionMap().put("down", new SSCCEKA(xCoord, yCoord, "down"));
gridPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_A, 0), "left");
gridPanel.getActionMap().put("left", new SSCCEKA(xCoord, yCoord, "left"));
gridPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_D, 0), "right");
gridPanel.getActionMap().put("right", new SSCCEKA(xCoord, yCoord, "right"));
//Window
JFrame window = new JFrame("Window");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
int windowHeight = 1125;
int windowWidth = 900;
window.setPreferredSize(new Dimension(windowHeight, windowWidth));
window.add(gridPanel);
window.pack();
window.setVisible(true);
gridPanel.requestFocusInWindow();
}
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package palace.hero;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class SSCCEKA extends AbstractAction
{
String direction;
int x = 0;
int y = 0;
public SSCCEKA(int x, int y, String direction)
{
this.x = x;
this.y = y;
}
@Override
public void actionPerformed(ActionEvent ae)
{
if(direction.toLowerCase().equals("up"))
{
x++;
}
if(direction.toLowerCase().equals("down"))
{
x--;
}
if(direction.toLowerCase().equals("left"))
{
y--;
}
if(direction.toLowerCase().equals("right"))
{
y++;
}
}
}
答案 0 :(得分:3)
当你创建像游戏一样复杂的东西时,你应该使用model / view / controller pattern。
所以,让我们创建一个模型类。
public class GameModel {
private int xCoordinate;
private int yCoordinate;
public int getxCoordinate() {
return xCoordinate;
}
public void setxCoordinate(int xCoordinate) {
this.xCoordinate = xCoordinate;
}
public int getyCoordinate() {
return yCoordinate;
}
public void setyCoordinate(int yCoordinate) {
this.yCoordinate = yCoordinate;
}
}
您可以通过构造函数将GameModel类传递给您的SSCCEKA类。
请记住,只有控制器类可以修改游戏模型。