java实现 swing模仿金山打字 案例源码
代码:
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
|
<font
size= "3" >import
Java.awt.Color; import
java.awt.Font; import
java.awt.Graphics; import
java.awt.Image; import
java.awt.Toolkit; import
java.io.File; import
java.io.IOException; import
java.util.Random; import
javax.imageio.ImageIO; public class Main
{ public char c;
//苹果上的字母 public int x
= 60, y = 0; //
敌人出现的坐标 public final
int XSPEED=5,YSPEED=2;
//苹果xy方向移动的速度 public int center;
//初始中心值 public boolean
turnleft = true ;
//是否向左移动 public boolean
alive = true ;
//是否活着 public Random
ran = new Random();
//随机数的种子 public TypeFrame
tf= null ;
//所属的框架 public Image
appleimg = null ;
//苹果的图片 public Image
bg = Toolkit.getDefaultToolkit().getImage( "bg.jpg" );
//背景图片 public Main(TypeFrame
tf) { this .tf=tf; x
= randomlocation(); //得到随机合格的随机x坐标 y=ran.nextInt(20);
//得到随机的y坐标 if (ran.nextInt(2)==0){ turnleft= true ; } else { turnleft= false ; } center
= x; //设置初始中心值为x c=randomchar();
//得到随机的字母值 try { appleimg
= ImageIO.read( new File( "apple.gif" ));
//苹果的图片 }
catch (IOException
e) { //
TODO Auto-generated catch block e.printStackTrace(); } } public void draw(Graphics
g) { Color
color = g.getColor(); //得到上下文颜色 g.setColor(Color.red);
//设置上下文颜色 g.setFont( new Font( "Dialog" ,
4, 40)); //设置字体 if (alive)
{ g.drawImage(appleimg,
x, y, null );
//绘制苹果图片 g.drawString(c+
"" ,
x + 20, y + 60); //绘制苹果字母 } g.setColor(color);
//将上下文颜色设置回去 } public int randomlocation(){
//产生苹果的随机横坐标的函数 int x1=ran.nextInt(TypeFrame.GAME_WIDTH
- 40); for ( int i
= 0; i < tf.apples.size(); i++) { if (Math.abs(x1-tf.apples. get (i).x)<60){ return randomlocation(); } } return x1; } public char randomchar(){
//产生不与存在的苹果字母相同的字母的方法 char ch=( char )( 'a' +ran.nextInt(26)); for ( int i
= 0; i < tf.apples.size(); i++) { if (ch==tf.apples. get (i).c) return randomchar(); } return ch; } } </font> |