swing - Java snake game -



swing - Java snake game -

well starting off must admit there countless snake questions out there, though every programmer if newbie or expert writes code differently decided open 1 case,

import java.awt.color; import java.awt.graphics; import java.awt.event.keyadapter; import java.awt.event.keyevent; import javax.swing.jframe; public class game1 extends jframe { float x; float y; int[][] tilekati = new int[30][30]; int keycode; int body; boolean right = true; boolean left = false; boolean = false; boolean downwards = false; boolean running = false; public class al extends keyadapter{ public void keypressed(keyevent e){ keycode = e.getkeycode(); if((keycode == e.vk_left) && (!right)){ left=true; down=false; up=false; running=true; } if((keycode == e.vk_right) && (!left)){ right=true; down=false; up=false; running=true; } if((keycode == e.vk_up) && (!down)){ up=true; left=false; right=false; running=true; } if((keycode == e.vk_down) && (!up)){ down=true; left=false; right=false; running=true; } } public void keyreleased(keyevent e){ } } public game1(){ addkeylistener(new al()); settitle("snake"); setsize(960,960); setresizable(false); setvisible(true); setdefaultcloseoperation(exit_on_close); x=0; y=0; for(int x=0;x<30;x++){ for(int y=0;y<30;y++){ tilekati[x][y] = 0; } } } public void paint(graphics g) { state(); if(running==true) { if(x<0) { x=30; } if(x>30) { x=0; } if(y<0) { y=30; } if(y>30) { y=0; } } tilekati[(int)x][(int)y] = 1; for(int x=0;x<30;x++) { for(int y=0;y<30;y++) { if(tilekati[x][y] == 0) { g.setcolor(color.black); g.drawrect(x*32, y*32, 32, 32); } if(tilekati[x][y]== 1) { g.setcolor(color.cyan); g.fillrect(x*32, y*32, 32, 32); } } } repaint(); } public void move(){ if(right){ x+= 0.01; } if(left){ x-=0.01; } if(up){ y-=0.01; } if(down){ y+=0.01; }} public void state(){ if(running){ move(); } repaint(); } public static void main(string[] args){ new game1(); } }

so question follows, want start painting tiles , clearing rest of "map" when snake exceed 3 tiles (x or y), can create 3 tile snake running through map think can figure out rest, in advance.

edit:no more broken code..

you utilize stack or linkedlist this. every move of snakes head add together position (x,y) start of list , remove lastly element if there more elements in list snake length.

and while painting first paint background , lists elements snake.

java swing paint keylistener repaint

Comments

Popular posts from this blog

php - Android app custom user registration and login with cookie using facebook sdk -

django - Access session in user model .save() -

php - .htaccess Multiple Rewrite Rules / Prioritizing -