-
Notifications
You must be signed in to change notification settings - Fork 0
/
snake_2.java
94 lines (76 loc) · 1.7 KB
/
snake_2.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/*<applet code="snake_2" width=1910 height=920 ></applet>*/
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.*;
import java.awt.event.*;
public class snake_2 extends Applet implements Runnable,KeyListener
{
int x,y,r,px,py;
char pos = 'w';
Thread t;
public void init()
{
x = getWidth()/2;
px =x*2;
y = getHeight()/2;
py =y*2;
r=30;
addKeyListener(this);
t=new Thread(this);
t.start();
this.setBackground(Color.BLUE);
}
public void paint(Graphics g)
{
g.setColor(Color.blue);
g.fillOval(x,y,r,r);
}
public void run()
{
while( true)
{
try
{
while(pos == 'w') // For go in upwards direction..... y>((py*3)/7)
{
this.setBackground(Color.ORANGE);
y=y-2;
repaint();
Thread.sleep(10);
}
while(pos == 'a') // To go in left direction..... x>((px*3)/7)
{
this.setBackground(Color.YELLOW);
x=x-2;
repaint();
Thread.sleep(10);
}
while(pos == 's') // To go in down direction...... y<((py*4)/7)
{
this.setBackground(Color.RED);
y=y+2;
repaint();
Thread.sleep(10);
}
while(pos == 'd') // To go in right direction ....... x<((px*4)/7)
{
this.setBackground(Color.GREEN);
x=x+2;
repaint();
Thread.sleep(10);
}
}
catch(Exception e)
{
System.out.println("ERROR");
}
}
}
public void keyPressed(KeyEvent ke) { }
public void keyReleased(KeyEvent ke) { }
public void keyTyped(KeyEvent ke)
{
pos = ke.getKeyChar();
}
}