class Snake:PictureBox
{
public int x;
public int y;
public int z;
public Snake(int x,int y, int z)
{
this.x = x;
this.y = y;
this.z = z;
Width = 10;
Height = 10;
Top = x * 10 + 30;
Left = y * 10 + 30;
switch (z)
{
case 1: BackColor = Color.Blue; break;
case 2: BackColor = Color.Red; break;
case 3: BackColor = Color.Green; break;
}
}
public void move(string t)
{
switch(t)
{
case "Up": x--;break;
case "Right":y++;break;
case "Down":x++;break;
case "Left":y--;break;
}
Top = x * 10 + 30;
Left = y * 10 + 30;
}
public void change(int x, int y)
{
this.x = x;
this.y = y;
Top = x * 10 + 30;
Left = y * 10 + 30;
}
}
public partial class Form1 : Form
{
Snake food;
Snake[] s=new Snake[21];
int leng=3;
string d="Right";
void SnakeMove(string t)
{
for (int i = leng-1; i >0; i--)
{
s[i].change(s[i - 1].x, s[i - 1].y);
}
s[0].move(t);
}
public Form1()
{
InitializeComponent();
}
private void newToolStripMenuItem_Click(object sender, EventArgs e)
{
timer1.Enabled = true;
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
d = e.KeyCode.ToString();
}
int score = 0;
private void timer1_Tick(object sender, EventArgs e)
{
SnakeMove(d);
bool ok = false;
for (int i = 1; i < leng; i++)
{ if (s[0].x == s[i].x && s[0].y == s[i].y) ok = true; }
if (ok)
{
timer1.Enabled = false;
MessageBox.Show("Та хожигдлоо");
}
if (food.x == s[0].x && food.y == s[0].y)
{
score++;
label1.Text = "Таны оноо: " + score.ToString();
leng++;
s[leng-1]= food;
int food_x, food_y;
Random rd = new Random();
food_x = rd.Next(14);
food_y = rd.Next(14);
food = new Snake(food_x, food_y, 1);
food.Parent = this;
}
if (s[0].x >= 15) s[0].x = 0;
if (s[0].x <= 0) s[0].x = 15;
if (s[0].y <= 0) s[0].y = 15;
if (s[0].y >= 15) s[0].y = 0;
}
private void Form1_Load(object sender, EventArgs e)
{
for (int i = leng-1; i >=0; i--)
{
s[i] = new Snake(3, i+1, 1);
s[i].Parent = this;
}
int food_x, food_y;
Random rd = new Random();
food_x = rd.Next(10);
food_y = rd.Next(10);
food = new Snake(food_x,food_y,1);
food.Parent = this;
}
}
No comments :
Post a Comment