Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.awt.Color;
- import java.awt.Graphics;
- import javax.swing.*;
- public class Snake extends JApplet implements Runnable{
- int x1 = 1, y1 = 0, x2 = 1, y2 = 0, x3 = 1, y3 = 0, x4 = 1, y4 = 0, x5 = 1, y5 = 0;
- boolean goRight = true, goDown = false, goLeft = false, goUp = false;
- public void init() {
- // TODO Auto-generated method stub
- super.init();
- x2 = x1 + 20;
- x3 = x2 + 20;
- x4 = x3 + 20;
- x5 = x4 + 20;
- Thread nitka = new Thread(this);
- nitka.start();
- }
- public void paint(Graphics g) {
- super.paintComponents(g);
- //Go right
- if(y5 <= 0) {
- y5 = 0;
- x5 += 5;
- }
- if(y4 <= 0) {
- y4 = 0;
- x4 += 5;
- }
- if(y3 <= 0) {
- y3 = 0;
- x3 += 5;
- }
- if(y2 <= 0) {
- y2 = 0;
- x2 += 5;
- }
- if(y1 <= 0) {
- y1 = 0;
- x1 += 5;
- }
- //Go down
- if(x5 >= getWidth() - 20) {
- x5 = getWidth() - 20;
- y5 += 5;
- }
- if(x4 >= getWidth() - 20) {
- x4 = getWidth() - 20;
- y4 += 5;
- }
- if(x3 >= getWidth() - 20) {
- x3 = getWidth() - 20;
- y3 += 5;
- }
- if(x2 >= getWidth() - 20) {
- x2 = getWidth() - 20;
- y2 += 5;
- }
- if(x1 >= getWidth() - 20) {
- x1 = getWidth() - 20;
- y1 += 5;
- }
- //Go left
- if(y5 >= getHeight() - 20) {
- y5 = getWidth() - 20;
- x5 -= 5;
- }
- if(y4 >= getWidth() - 20) {
- y4 = getWidth() - 20;
- x4 -= 5;
- }
- if(y3 >= getWidth() - 20) {
- y3 = getWidth() - 20;
- x3 -= 5;
- }
- if(y2 >= getWidth() - 20) {
- y2 = getWidth() - 20;
- x2 -= 5;
- }
- if(y1 >= getWidth() - 20) {
- y1 = getWidth() - 20;
- x1 -= 5;
- }
- //Go up
- if(x5 <= 0) {
- x5 = 0;
- y5 -= 5;
- }
- if(x4 <= 0) {
- x4 = 0;
- y4 -= 5;
- }
- if(x3 <= 0) {
- x3 = 0;
- y3 -= 5;
- }
- if(x2 <= 0) {
- x2 = 0;
- y2 -= 5;
- }
- if(x1 <= 0) {
- x1 = 0;
- y1 -= 5;
- }
- g.setColor(Color.blue);
- g.fillRect(x1, y1, 20, 20);
- g.fillRect(x2, y2, 20, 20);
- g.fillRect(x3, y3, 20, 20);
- g.fillRect(x4, y4, 20, 20);
- g.fillRect(x5, y5, 20, 20);
- }
- public void run() {
- // TODO Auto-generated method stub
- while(true){
- repaint();
- try {
- Thread.sleep(50);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement