本文实例为大家分享了C#实现打字游戏的具体代码,供大家参考,具体内容如下
思路:
1、有一个游戏界面,我用panel作为游戏界面
2、开始生成字母
打字游戏的字母是不断生成的,所以用计时器timer来生成字母
所有生成的字母设置tag方便寻找
3、字母下落
字母下落是一个持续的动作,所以也在计时器里做
在计时器里通过foreach遍历panel中的所有控件,同时通过tag找到字母,让字母下降
4、生成子弹
通过获取键盘事件生成子弹
5、子弹与字母相碰
代码:
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
|
private void Form1_Load( object sender, EventArgs e) { this .panel1.BackColor = Color.White; timer1.Start(); timer2.Start(); timer1.Interval = 1000; timer2.Interval = 100; fj.Tag = "feiji" ; fj.Size = new Size(30, 40); fj.BackColor = Color.Black; fj.Text = "飞机" ; fj.TextAlign = ContentAlignment.MiddleCenter; fj.ForeColor = Color.White; fj.Location = new Point(panel1.Width / 2 - fj.Width / 2, panel1.Height - fj.Height); panel1.Controls.Add(fj); } Label fj = new Label(); Random r = new Random(); private void timer1_Tick( object sender, EventArgs e) { Label zm = new Label(); zm.Tag = "zimu" ; zm.Text = (( char )r.Next(97, 123)).ToString(); zm.Font = new Font( "" , r.Next(20, 30)); zm.AutoSize = true ; zm.Location = new Point(r.Next(0, panel1.Width - zm.Width), 0); zm.ForeColor = Color.FromArgb(r.Next(255), r.Next(255), r.Next(255)); panel1.Controls.Add(zm); } private void timer2_Tick( object sender, EventArgs e) { foreach (Control item in panel1.Controls) { if (item.Tag.ToString() == "zimu" ||item.Tag.ToString()== "zzm" ) { item.Top += 5; if (item.Top >= panel1.Height) { item.Dispose(); } } else if (item.Tag.ToString() == "zidan" ) { item.Top -= 9; foreach (Control con in panel1.Controls) { if (con.Tag.ToString() == "zzm" ) { if (con.Top + con.Height >= item.Top) { con.Dispose(); item.Dispose(); SoundPlayer ply = new SoundPlayer(); ply.SoundLocation = ".../.../Sound/MyBomb.wav" ; ply.Play(); } } } } } } private void Form1_KeyPress( object sender, KeyPressEventArgs e) { foreach (Control item in panel1.Controls) { if (item.Tag.ToString() == "zimu" ) { if (item.Text == e.KeyChar.ToString()) { Label zd = new Label(); zd.Tag = "zidan" ; zd.Size = new Size(20, 20); item.Tag = "zzm" ; zd.BackColor = Color.Red; zd.Location = new Point(item.Left + item.Width / 2 - zd.Width / 2, fj.Top - fj.Height); fj.Left = item.Left + item.Width / 2 - fj.Width / 2; panel1.Controls.Add(zd); return ; } } } } |
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/weixin_44022365/article/details/105921537