分类：电脑/网络-互联网
问题：用C#编写一个贪吃蛇的程序， 
回答：using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.IO; namespace WindowsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } BufferedGraphics BufferedGraphicsA = null; BufferedGraphics BufferedGraphicsB = null; private void Form1_Load(object sender, EventArgs e) { BufferedGraphicsContext context = BufferedGraphicsManager.Current; BufferedGraphicsA = context.Allocate(this.CreateGraphics(), this.ClientRectangle); BufferedGraphicsB = context.Allocate(BufferedGraphicsA.Graphics, this.ClientRectangle); Pen pen = new Pen(Brushes.Blue,3); for(int i = 0;i < 400;i += 20) { BufferedGraphicsB.Graphics.DrawLine(pen, new Point(0, i), new Point(400, i)); BufferedGraphicsB.Graphics.DrawLine(pen, new Point(i, 0), new Point(i, 400)); } BufferedGraphicsB.Render(); food = this.GetPoint(random); BufferedGraphicsA.Graphics.FillRectangle(Brushes.Yellow, new Rectangle(food, new Size(20, 20))); BufferedGraphicsA.Render(); Point p = this.GetPoint(random); PointList.Add(p); } List<Point> PointList = new List<Point>(); Point food = Point.Empty; Random random = new Random(DateTime.Now.Millisecond); Keys key = Keys.Left; private void timer1_Tick(object sender, EventArgs e) { if (PointList.Count > 0) { Point first = PointList[0]; switch (key) { case Keys.Left: first.X -= 20; break; case Keys.Right: first.X += 20; break; case Keys.Up: first.Y -= 20; break; case Keys.Down: first.Y += 20; break; } if (PointList.IndexOf(first, 0) >= 0) { this.timer1.Enabled = false; MessageBox.Show("结束"); } BufferedGraphicsB.Render(); BufferedGraphicsA.Graphics.FillRectangle(Brushes.Yellow, new Rectangle(food, new Size(20, 20))); PointList.Insert(0, first); if (food != first) PointList.RemoveAt(PointList.Count - 1); else { food = this.GetPoint(random); BufferedGraphicsA.Graphics.FillRectangle(Brushes.Yellow, new Rectangle(food, new Size(20, 20))); } foreach(Point p in PointList) BufferedGraphicsA.Graphics.FillRectangle(Brushes.Red,new Rectangle(p,new Size(20,20))); BufferedGraphicsA.Render(); } } private void Form1_KeyDown(object sender, KeyEventArgs e) { key = e.KeyData; } private Point GetPoint(Random random) { int x = (random.Next(400) / 20) * 20; int y = (random.Next(400) / 20) * 20; return new Point(x, y); } private void Form1_Paint(object sender, PaintEventArgs e) { BufferedGraphicsA.Render(); } } }