您能帮我解决一个小问题吗,我该如何移动pacman离开左侧,并在右侧输入相同的x位置?
我发现我的阵列弹跳了一下。
我的吃豆人正在阵列中旅行。
感谢您的帮助。
class PmanMove extends JPanel {
private void paintPacman(Graphics2D g) {
g.setColor( Color.yellow );
g.fill(new Arc2D.Double(Xpos*cellSize, Ypos*cellSize, pRadius, pRadius, 45, 220, Arc2D.PIE));
g.setFont(new Font(null, Font.PLAIN, 18));
g.drawString("SCORE "+score, 50, 50);
repaint();
}
private void paintBoard(Graphics2D g) {
for (int i=0;i<area.length; i++) {
for(int j=0; j <area[i].length; j++) {
if (area[i][j]==1){
g.setColor(Color.BLACK);
g.fillRect(i*cellSize,j*cellSize,cellSize,cellSize);}
// g.fillRect(i*cellSize,j*cellSize,cellSize,cellSize);}
if (area[i][j]==2){
g.setColor(Color.YELLOW);
g.fillOval(i*cellSize+cellSize/4,j*cellSize+cellSize/4,cellSize-cellSize/2,cellSize-cellSize/2);}
}
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
paintBoard(g2d);
paintPacman(g2d);
}
public void register() {
setFocusable(true);
this.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if( e.getKeyCode() == e.VK_RIGHT ) {
if(Xpos<(400/cellSize)) {
switch (area[Xpos+1][Ypos]) {
case 4: Xpos+=speed; break;
case 3: Xpos+=speed; break;
case 2: area[Xpos+1][Ypos]=0; Xpos+=speed; score+=5; break;
case 0: Xpos+=speed; break;
}
}
if( Xpos+1 > (400/cellSize)) {
Xpos = 0;
}
}
if( e.getKeyCode() == e.VK_LEFT ) {
if(Xpos>0) {
switch (area[Xpos-1][Ypos]) {
case 4: Xpos-=speed; break;
case 3: Xpos-=speed; break;
case 2: area[Xpos-1][Ypos]=0; Xpos-=speed; score+=5; break;
case 0: Xpos-=speed; break;
}
}
if( Xpos <= 0) {
Xpos = (getWidth()/(cellSize/2));
}
}
if( e.getKeyCode() == e.VK_UP) {
if(Ypos>0) {
switch (area[Xpos][Ypos-1]) {
case 4: Ypos-=speed; break;
case 3: Ypos-=speed; break;
case 2: area[Xpos][Ypos-1]=0; Ypos-=speed; score+=5; break;
case 0: Ypos-=speed; break;
}
}
if( Ypos <=0 ) {
Ypos = (getHeight()/(cellSize/2));
}
}
if(e.getKeyCode() == e.VK_DOWN) {
if(Ypos<400/cellSize) {
switch (area[Xpos][Ypos+1]) {
case 4: Ypos+=speed; break;
case 3: Ypos+=speed; break;
case 2: area[Xpos][Ypos+1]=0; Ypos+=speed; score+=5; break;
case 0: Ypos+=speed; break;
}
}
if( Ypos >= (getHeight()/(cellSize/2))) {
Ypos = 0;
}
}
}
});
requestFocus();
}
public static void main( String args[] ) {
JFrame fr = new JFrame("PmanMove");
fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
fr.setBackground(new Color(107,106,100));
fr.setResizable(false);
PmanMove pman = new PmanMove();
fr.setSize(400,400);
fr.add(pman);
fr.setVisible(true);
}
}
最佳答案
假设您的数组具有N
个元素,并且您位于i
位置,那么向右移动将是:
(i + 1) % N
该
%
称为modulo。如果i+1 = N
,您将获得索引0,从而避免绑定和着陆在左侧的索引ouf。