我正在编写我的pacman,已经有pacman移动,从txt加载地图,以及与墙壁碰撞。当pacman在点场上时,下一步是点擦除器。我需要任何建议如何做,我试图通过与背景颜色相同的点来擦除它,但它不起作用。这是代码
board.java
public class Board extends JPanel implements ActionListener {
private Timer timer;
private Map m;
private Player p;
public Board(){
m = new Map();
p = new Player();
addKeyListener(new Klawa());
setBackground(Color.BLACK);
setFocusable(true);
timer = new Timer(25, this);
timer.start();
}
@Override
public void paint(Graphics g){
super.paint(g);
for(int x=0; x<14; x++){
for(int y=0; y<14; y++){
if(m.getMap(x,y).equals("s")){
g.drawImage(m.getWall(),x *32,y *32, this);
}
if(m.getMap(x,y).equals("k")){
g.drawImage(m.getDot(),x *32,y *32, this);
}
}
}
g.drawImage(p.getPlayer(),p.getTileX()* 32 ,p.getTileY() * 32,null);
}
public void erase(Graphics g){
super.paint(g);
if(m.getMap(p.getTileX(),p.getTileY()).equals("k")){
g.drawImage(m.getErase(),p.getTileX(),p.getTileY(), this);
}
}
public class Klawa extends KeyAdapter {
@Override
public void keyPressed(KeyEvent e){
int keycode = e.getKeyCode();
if (keycode == KeyEvent.VK_W){
if(!m.getMap(p.getTileX(),p.getTileY() - 1).equals("s")){
p.move(0, -1);
}
}
if (keycode == KeyEvent.VK_S){
if(!m.getMap(p.getTileX(),p.getTileY() + 1).equals("s")){
p.move(0, 1);
}
}
if (keycode == KeyEvent.VK_A){
if(!m.getMap(p.getTileX() - 1,p.getTileY()).equals("s")){
p.move(-1, 0);
}
}
if (keycode == KeyEvent.VK_D){
if(!m.getMap(p.getTileX() + 1,p.getTileY() ).equals("s")){
p.move(1, 0);
}
}
}
public void keyRelased(KeyEvent e){
}
@Override
public void keyTyped(KeyEvent e){
}
}
@Override
public void actionPerformed(ActionEvent e) {
repaint();
}
}
map.java
public class Map {
private Scanner m;
private String Map[] = new String[16];
private Image wall, dot, erase;
public Map(){
wall = new ImageIcon("C:\\Users\\Kotek\\Desktop\\pacman\\sciana.png").getImage();
dot = new ImageIcon("C:\\Users\\Kotek\\Desktop\\pacman\\kropka.png").getImage();
erase = new ImageIcon("C:\\Users\\Kotek\\Desktop\\pacman\\wymaz.png").getImage();
openFile();
readFile();
closeFile();
}
public Image getWall(){
return wall;
}
public Image getDot(){
return dot;
}
public Image getErase(){
return erase;
}
public String getMap(int x, int y){
String index = Map[y].substring(x, x+1);
return index;
}
public void openFile(){
try{
m = new Scanner(new File("C:\\Users\\Kotek\\Desktop\\pacman\\mapa.txt"));
}catch(FileNotFoundException e){
System.out.println("Blad podczas ladowania mapy");
}
}
public void readFile(){
while(m.hasNext()){
for(int i=0; i<14; i++){
Map[i] = m.next();
}
}
}
public void closeFile(){
m.close();
}
}
答案 0 :(得分:2)
在你的类Map中你应该实现方法
public void setMap(int x, int y, String value ){
//remove the "k" from the string
}
在erase()方法中,只需清理模型的单元格并调用repaint()