این بازی اسنیک هست .... برنامش کامل اجرا میشه... انشالله مفید باشه... درپناه خدا.
کد:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
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));
InitializeComponent();
}
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);
}
//-------- wall collision --------
if (snake.First.Value.X > this.Size.Width) snake.First.Value = new Point(1, snake.First.Value.Y);
if (snake.First.Value.X < 1) snake.First.Value = new Point(this.Size.Width, snake.First.Value.Y);
if (snake.First.Value.Y > this.Size.Height) snake.First.Value = new Point(snake.First.Value.X, 1);
if (snake.First.Value.Y < 1) snake.First.Value = new Point(snake.First.Value.X, this.Size.Height);
}
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();
}
}
}
موضوعات مشابه:
علاقه مندی ها (Bookmarks)