I'm trying to make a turn-based snake thingy, but I just can't get it to work properly. I think something might be wrong with the run() method, because it only loops once if the if() statement doesn't activate. If I put repaint() after the if() statement, everything will work. But I was just wondering why the loop doesn't loop if I don't. Any ideas? :)
My code:
public class Class extends Applet implements KeyListener, Runnable {
private static final long serialVersionUID = 1L;
int p = 5;
int x[] = new int[p];
int y[] = new int [p];
int e;
int n;
public Class() {
for (int i = 0; i < p; i++) {
x[i] = 10 + i;
y[i] = 10;
}
e = x[0];
n = y[0];
addKeyListener(this);
new Thread(this).start();
}
public static void main(String[] args) {
new Class();
}
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_UP) {
y[0]--;
}
if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
x[0]++;
}
if (e.getKeyCode() == KeyEvent.VK_DOWN) {
y[0]++;
}
if (e.getKeyCode() == KeyEvent.VK_LEFT) {
x[0]--;
}
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}
public void run() {
while (true) {
if (x[0] != 10 || y[0] != 10) {
for (int i = p - 1; i > 1; i--) {
x[i] = x[i-1];
y[i] = y[i-1];
}
x[1] = e;
y[1] = n;
e = x[0];
n = y[0];
repaint();
}
}
}
public void paint(Graphics g) {
for (int i = 0; i < p; i++) {
g.drawString(x[0] + ", " + y[0], 10, 10);
g.fillRect(x[i] * 10, y[i] * 10, 10, 10);
}
}
}
Please explain everything in a very simple way as I'm not very good at programming (yet). Good advice is also much appreciated. :)
Aucun commentaire:
Enregistrer un commentaire