using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace sankeEatEgg
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
List<Button> list = new List<Button>();
Button btn;
Button btnEgg;
private void Form1_Load(object sender, EventArgs e)
{
for (int i = 0; i < 4; i++)
{
btn = new Button();
btn.Height = 20;
btn.Width = 20;
btn.BackColor = Color.Red;
//蛇的初始位置
btn.Top = 0;
btn.Left = i * 20;
list.Add(btn);
Controls.Add(btn); //添加到窗体上
}
Egg();
}
//设置蛋的初始值
int i;
int j;
public void Egg()
{
btnEgg = new Button();
btnEgg.Height = 20;
btnEgg.Width = 20;
btnEgg.BackColor = Color.Red;
//判断蛋不在蛇身上
for(int s=0;;){
Random ran = new Random();
//蛋的初始位置
i = ran.Next(0,28);
j = ran.Next(0,28);
if ((i * 20 - list[s].Left < 20 && i * 20 - list[s].Left > 0) || (i * 20 - list[s].Top < 20 && i * 20 - list[s].Top > 0))
{
continue;
}
else
{
break;
}
}
btnEgg.Left = i * 20;
btnEgg.Top = j * 20;
Controls.Add(btnEgg);
}
int kv = 0;
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyValue == 68&&kv!=-1)//右
{
kv = 1;
}
if (e.KeyValue == 65 && kv!= 1)//左
{
kv = -1;
}
if (e.KeyValue == 83 && kv!= -3)//下
{
kv = 3;
}
if (e.KeyValue == 87 && kv != 3)//上
{
kv = -3;
}
timer1.Start();
}
//走动
public void move()
{
Button btn = this.list[0];
this.list.Remove(btn);
this.list.Add(btn);
btn.Left = 20*(kv%3) +list[list.Count-2].Left;
btn.Top = 20 * (kv / 3) + list[list.Count - 2].Top;
//蛋吃到后从新部署
if (this.list[list.Count - 1].Top == btnEgg.Top && this.list[list.Count - 1].Left == btnEgg.Left)
{
list.Add(btnEgg);
btnEgg.Left = 20 * (kv % 3) + list[list.Count - 1].Left;
btnEgg.Top = 20 * (kv / 3) + list[list.Count - 1].Top;
Egg();
}
//判断撞墙
if (this.list[list.Count - 1].Left < 0 || this.list[list.Count - 1].Top < 0 || this.list[list.Count - 1].Left+20 >580 || this.list[list.Count -1].Top+20 >=560)
{
timer1.Stop();
MessageBox.Show("撞墙");
}
//判断蛇有没有撞到自己
for (int i = 0; i < list.Count-2; i++)
{
int left=list[i].Left;
int top=list[i].Top;
if (this.list[list.Count - 1].Left == left && list[list.Count - 1].Top == top)
{
timer1.Stop();
MessageBox.Show("撞到自己");
break;
}
}
}
private void timer1_Tick(object sender, EventArgs e)
{
move();
}
}
}