import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class snakeGame extends Applet implements Runnable, KeyListener{
private snake snk = new snake();
private Thread thread;
private Graphics gfx;
private Image img;
private boolean game = true;
public void init(){
setBackground(Color.black);
this.setSize(new Dimension(800,800));
this.addKeyListener(this);
img = createImage(800, 800);
gfx = img.getGraphics();
thread = new Thread();
thread.start();
}
public void paint(Graphics g){
//g.setColor(Color.white);
//g.fillRect(snk.getX(), snk.getY(), 10, 10);
snk.draw(g);
}
public void update(Graphics g){
paint(g);
}
public void repaint(Graphics g){
paint(g);
}
public void run(){
while(game){
//snk.move();
if(snk.getDiry() == -1){
snk.y -= 10;
}
if(snk.getDiry() == 1){
snk.y += 10;
}
if(snk.getDirx() == -1){
snk.x -= 10;
}
if(snk.getDirx() == 1){
snk.x += 10;
}
repaint();
try{
Thread.sleep(200);
}
catch(InterruptedException e){
e.printStackTrace();
}
}
}
public void keyPressed(KeyEvent e){
if (e.getKeyCode() == KeyEvent.VK_UP){
snk.setDirx(0);
snk.setDiry(-1);
System.out.println("UP");
}
else if (e.getKeyCode() == KeyEvent.VK_DOWN){
snk.setDirx(0);
snk.setDiry(1);
System.out.println("DOWN");
}
else if (e.getKeyCode() == KeyEvent.VK_LEFT){
snk.setDirx(-1);
snk.setDiry(0);
System.out.println("LEFT");
}
else if (e.getKeyCode() == KeyEvent.VK_RIGHT){
snk.setDirx(1);
snk.setDiry(0);
System.out.println("RIGHT");
}
else{
System.out.println("Wrong key pressed");
}
}
public void keyReleased(KeyEvent e){
}
public void keyTyped(KeyEvent e){
}
}
This is the code for the snakeGame class. There is one other file named "snake.java" which contains accessors and mutators for the variables and defination of draw function. This is the snake.java
import java.awt.*;
public class snake {
public int x, y;
private int dirx, diry;
public snake(){
this.x = 400;
this.y = 400;
this.dirx = 0;
this.diry = 1;
}
public void draw(Graphics g){
g.setColor(Color.white);
g.fillRect(getX(), getY(), 20, 20);
}
public int getX(){
return x;
}
public int getY(){
return y;
}
public int getDirx(){
return dirx;
}
public int getDiry(){
return diry;
}
public void setDirx(int dirx){
this.dirx = dirx;
}
public void setDiry(int diry){
this.diry = diry;
}
}
The snake won't show up in the applet window. Please help me see what is wrong in the code and how it can be made better. I am new with coding and StackOverflow so please forgive me if I have made some stupid mistake.
Thanks in advance