![]() |
Smaller snake in C#
Now with full initialization. Tomorrow I should have XNA up as well. Then I’ll get to work on a simple tower defense game. Smaller Snake in C#
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 | using System; using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; namespace SnakeCSharp { public partial class SnakeCSharpWindow : Form { private Timer t = new Timer(); private static Random myRnd = new Random(); private Point apple = new Point(myRnd.Next(64-1) * 10, myRnd.Next(48-1) * 10); private Point dir = new Point(0, 10); private LinkedList<Point> snake = new LinkedList<Point>(); //LinkedList doesn't have add... public SnakeCSharpWindow() { this.ClientSize = new System.Drawing.Size(640, 480); this.FormBorderStyle = FormBorderStyle.FixedSingle; this.Name = "SnakeCSharpWindow"; this.Text = "SnakeCSharp"; this.Paint += new PaintEventHandler(SnakeCSharpWindow_Paint); this.KeyDown += new KeyEventHandler(SnakeCSharpWindow_KeyDown); t.Tick += new EventHandler(t_Tick); t.Start(); snake.AddFirst(new Point(10,10)); } void SnakeCSharpWindow_KeyDown(object sender, KeyEventArgs e) //Change direction { if (e.KeyCode == Keys.Left) {dir = new Point (-10,0 );} if (e.KeyCode == Keys.Right) {dir = new Point(10, 0);} if (e.KeyCode == Keys.Up) {dir = new Point(0, -10);} if (e.KeyCode == Keys.Down) {dir = new Point(0, 10);} } void SnakeCSharpWindow_Paint(object sender, PaintEventArgs e) { e.Graphics.FillRectangle(Brushes.Green, apple.X + 2, apple.Y + 2, 5, 5); int i = 0; foreach (Point cur in snake) //Draw snake and check self collision { e.Graphics.FillRectangle(Brushes.Black, cur.X, cur.Y, 10, 10); if (i != 0 && snake.First.Value.X == cur.X && snake.First.Value.Y == cur.Y ) { t.Stop(); } i++; } if (snake.First.Value.X == apple.X && snake.First.Value.Y == apple.Y) //Collision apple { apple = new Point((myRnd.Next(64-1)) * 10, (myRnd.Next(48-1)) * 10); snake.AddLast(snake.Last.Value); } } void t_Tick(object sender, EventArgs e) //Move Snake { snake.AddFirst(new Point(snake.First.Value.X + dir.X, snake.First.Value.Y + dir.Y)); snake.RemoveLast(); this.Refresh(); } } } |




No Comments »
No comments yet.
Leave a comment
You must be logged in to post a comment.