Hi, I'm trying to create a snake game, but I can't make the body/tail to follow correctly at the back of the snake's head.
Honestly, I don't know what to do here..
here's my code
import java.awt.*; import javax.swing.*; import java.awt.event.*; import java.awt.event.ActionEvent; import java.util.Random; public class snake extends JPanel implements ActionListener,KeyListener{ static JFrame frame = new JFrame(); static int x = 150,y=150,x1=x-10,y1=y,eposx=200,eposy=120,n=0; static int slength = 3; boolean right = true,left=true,up=true,down=true,rmove=true,lmove=false,umove=false,dmove=false; Timer tmr = new Timer(50,this); Random rdm = new Random(); public snake(){ setLayout(null); this.requestFocus(); addKeyListener(this); setFocusable(true); setFocusTraversalKeysEnabled(false); } public void actionPerformed(ActionEvent e){ if(e.getSource()==tmr){ if(right==true&&lmove==false){ x=x+5; System.out.println("X = " + x + " Y = " + y); } if(left==true&&rmove==false){ x=x-5; System.out.println("X = " + x + " Y = " + y); } if(up==true&&dmove==false){ y=y-5; System.out.println("X = " + x + " Y = " + y); } if(down==true&&umove==false){ y=y+5; System.out.println("X = " + x + " Y = " + y); } } if(x>=280){ x=0; } else if(x<=00){ x=280; } else if(y<=00){ y=260; } else if(y>=260){ y=0; } if(x==eposx&&y==eposy){ eposx=(rdm.nextInt(20)*10+10); eposy=(rdm.nextInt(20)*10+10); } repaint(); } public void paintComponent(Graphics g){ g.setColor(Color.WHITE); g.fillRect(0,0,100000,10000000); g.setColor(Color.BLACK); g.fillOval(x,y,10,10); g.setColor(Color.GREEN); g.fillOval(x1,y1,10,10); g.setColor(Color.RED); g.fillRect(eposx,eposy,10,10); } public void keyPressed(KeyEvent e){ tmr.start(); int c = e.getKeyCode(); if(c==KeyEvent.VK_RIGHT&&rmove==true){ right=true; left=false; up=false; down=false; umove=true; dmove=true; lmove=false; rmove=false; } if(c==KeyEvent.VK_LEFT&&lmove==true){ right=false; left=true; up=false; down=false; rmove=false; lmove=true; umove=true; dmove=true; } if(c==KeyEvent.VK_UP&&umove==true){ right=false; left=false; up=true; down=false; umove=true; dmove=false; lmove=true; rmove=true; } if(c==KeyEvent.VK_DOWN&&dmove==true){ right=false; left=false; up=false; down=true; umove=false; dmove=true; lmove=true; rmove=true; } repaint(); } public void keyTyped(KeyEvent e){} public void keyReleased(KeyEvent e){} public static void main(String[]args){ snake obj = new snake(); frame.setSize(300,300); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); frame.add(obj); } }
What should I add?