我的程序正在制作蛇游戏,蛇正在上下移动,不会左右移动
package snake2;
import java.awt.BorderLayout;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Label;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JOptionPane;
public class Snake extends Frame implements MouseListener{
@Override
public void mouseClicked(MouseEvent e) {
if (e.getX()>x[0])
{
incx=1;
incy=0;
}
if (e.getX()<x[0])
{
incx=-1;
incy=0;
}
if( e.getY()>y[0])
{
incx=0;
incy=1;
}
if(e.getY()<y[0])
{
incx=0;
incy=-1;
}
}
@Override
public void mousePressed(MouseEvent e) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void mouseReleased(MouseEvent e) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void mouseEntered(MouseEvent e) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void mouseExited(MouseEvent e) {
throw new UnsupportedOperationException("Not supported yet.");
}
int incx=1,incy=0;
int[] x = new int[300];
int[] y = new int [300];
int len=5;
public Label l;
public Snake()
{
setSize(500, 500);
setVisible(true);
this.addMouseListener(this);
l = new Label("snake lenght ="+ len);
add(l,BorderLayout.SOUTH);
x[0]=100;
y[0]=100;
}
public static void main(String[] args)
{
Snake s = new Snake();
move m = new move();
m.ptr=s;
m.start();
}
public void paint(Graphics g)
{
for(int i=0 ; i<=len;i++)
g.fillRect(x[i], y[i], 10, 10);
}
public void shift()
{
for (int z=len;z>0;z--)
{
x[z]=x[z-1];
y[z]=y[z-1];
}
}
}
class move extends Thread
{
Snake ptr;
int count=0;
public void run()
{
for (;;)
{
ptr.shift();
count++;
ptr.x[0]=ptr.x[0]+ptr.incx*10;
ptr.y[0]=ptr.y[0]+ptr.incy*10;
ptr.repaint();
try{sleep(150);}catch(Exception a){}
if(count%5==0){
ptr.len++;}
ptr. l.setText("snake lenght ="+ ptr.len);
for (int z = ptr.len; z > 0; z--) {
if ((z > 4) && (ptr.x[0] == ptr.x[z]) && (ptr.y[0] == ptr.y[z])) {
JOptionPane.showConfirmDialog(null, "You lost");
}
}
if (ptr.y[0] >500) {
JOptionPane.showConfirmDialog(null, "You lost");
}
if (ptr.y[0] < 0) {
JOptionPane.showConfirmDialog(null, "You lost");
}
if (ptr.x[0] > 500) {
JOptionPane.showConfirmDialog(null, "You lost");
}
if (ptr.x[0] < 0) {
JOptionPane.showConfirmDialog(null, "You lost");
}
}
}
}
我的程序中的问题是它跳过前2个IF语句,它只是跳过X,如果我用Y改变X它跳过Y并做X并开始左右移动并停止上下移动。 / p>
答案 0 :(得分:7)
您需要检查如下,因为如果y轴已更改,那么您将重置x
中所做的更改,鼠标可以同时沿x轴和y轴
if (e.getX()>x[0])
{
incx=1;
} else if (e.getX()<x[0])
{
incx=-1;
}
if( e.getY()>y[0])
{
incy=1;
} else if(e.getY()<y[0])
{
incy=-1;
}