2015-5-1 16:30:51 点击: 作者:蒲旭
如果有兴趣的请仔细阅读下面的代码。注意其中代码段的顺序,思考一下,程序运行后蛇身不会跟着蛇头走,蛇身是动态生成的.还有看一下在此程序中写入List<Label> list=new List<Label>();有没有用?
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Threading; namespace Snake { public partial class Snake : Form { public Snake() { InitializeComponent(); } int xold , yold;//记录蛇头的初始位置 String direction = "a";//默认移动方向 int snakeBody = 4;//蛇身长度 int snakeX;//蛇身初始的x轴坐标 int snakeY;//蛇身初始的y轴坐标 List<Label> list=new List<Label>(); /// <summary> /// 移动蛇头 /// </summary> public void MoveHead() { while (true) { xold = lblSnakeHead.Left; yold = lblSnakeHead.Top; switch (direction) { case "w": lblSnakeHead.Top -= 10; snakeY -= 10; if (lblSnakeHead.Top<=10) { lblSnakeHead.Top = 590; } break; case "s": lblSnakeHead.Top += 10; snakeY += 10; if (lblSnakeHead.Top>=590) { lblSnakeHead.Top = 10; } break; case "a": lblSnakeHead.Left -= 10; snakeX -= 10; if (lblSnakeHead.Left <= 10) { lblSnakeHead.Left = 790; } break; case "d": lblSnakeHead.Left += 10; snakeX += 10; if (lblSnakeHead.Left >= 790) { lblSnakeHead.Left = 10; } break; } MoveBody(); Thread.Sleep(100); } } private void Snake_Load(object sender, EventArgs e) { Control.CheckForIllegalCrossThreadCalls = false; Thread thread = new Thread(new ThreadStart(MoveHead)); thread.Start(); AddBody(); } private void Snake_KeyDown(object sender, KeyEventArgs e) { //MessageBox.Show(e.KeyCode.ToString()); direction = e.KeyCode.ToString().ToLower(); } /// <summary> /// 生成蛇身 /// </summary> private void AddBody() { snakeX = lblSnakeHead.Left; snakeY = lblSnakeHead.Top; for (int i = 1; i < snakeBody; i++) { Label lbl = new Label(); lbl.Size = new System.Drawing.Size(10,10); lbl.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; lbl.Location = new System.Drawing.Point(snakeX+10*i, snakeY); lbl.Name = i.ToString(); lbl.BackColor=Color.DarkMagenta; this.Controls.Add(lbl); } } /// <summary> /// 移动蛇身 /// </summary> private void MoveBody() { int x, y;//用来接收除蛇头外的其余lbl移动前的坐标 for (int i = 1; i < list.Count; i++) { x = list[i].Left; y = list[i].Top; list[i].Left = xold; list[i].Top = yold; xold = x; yold = y; } } } }