我已经决定是时候将我的编程带到下一步了:制作游戏。到目前为止,我已经能够对所有内容进行编码,也许不得不谷歌一些我不太熟悉的东西,但我觉得它应该可以工作。正在绘制图形,所有这些都很好,很漂亮,但是当涉及到关键听众时,这就是问题所在。我创建了一个实现 Key Listener 的内部类,然后将其添加到 Board 构造函数中。我想你只需要看看代码,但它很长而且有点乱。这是我第一次这样做,所以有些东西可能是不必要的,我可能只是忘记了一些非常明显的东西。
主类:
import javax.swing.*;
public class Game extends JFrame{
public static void main(String[] args){
new Game();
}
public Game(){
add(new Board());
setTitle("Hi mom");
setSize(555,330);
setResizable(false);
setLocationRelativeTo(null);
setDefaultCloseOperation(3);
setVisible(true);
}
}
板级:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Board extends JPanel implements ActionListener {
Image background;
Player p;
int k;
boolean moving;
public Board() {
setFocusable(true);
Timer timer = new Timer(25, this);
timer.start();
ImageIcon img = new ImageIcon(getClass().getResource("images/map.png"));
background = img.getImage();
addKeyListener(new Kl());
p = new Player();
}
public void paint(Graphics g) {
g.drawImage(background, 0, 0, null);
g.drawImage(p.getPlayer(), p.setX(30), p.setY(187), null);
}
public void actionPerformed(ActionEvent e) {
if (k == 'W' && moving == true) {
p.move(0,-5);
}
if (k == 'S' && moving == true) {
p.move(0,5);
}
if (k == 'D' && moving == true) {
p.move(5,0);
}
if (k == 'A' && moving == true) {
p.move(-5,0);
}
repaint();
}
public class Kl implements KeyListener {
public void keyPressed(KeyEvent e) {
k = e.getKeyCode();
moving = true;
}
public void keyReleased(KeyEvent e) {
moving = false;
}
public void keyTyped(KeyEvent e) {
}
}
}
玩家等级:
import javax.swing.*;
import java.awt.*;
public class Player{
int x, y;
Image player;
public Player(){
ImageIcon img = new ImageIcon(getClass().getResource("images/player.png"));
player = img.getImage();
}
public Image getPlayer(){
return player;
}
public void move(int x, int y){
this.x += x;
}
public int setX(int x){
this.x = x;
return x;
}
public int setY(int y){
this.y = y;
return y;
}
}