|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- using System;
- using System.Collections.Generic;
- using System.Drawing;
- using System.Windows.Forms;
- namespace 贪吃蛇
- {
- public partial class GameForm : Form
- {
- private Timer timer;
- private List<Point> snake;
- private Point food;
- private string direction;
- private int score;
- public GameForm()
- {
- InitializeComponent();
- InitializeGame();
- }
- private void InitializeGame()
- {
- this.Width = 400;
- this.Height = 400;
- this.Text = "贪吃蛇";
- this.BackColor = Color.Black;
- timer = new Timer();
- timer.Interval = 100;
- timer.Tick += Timer_Tick;
- snake = new List<Point> { new Point(10, 10), new Point(10, 11), new Point(10, 12) };
- direction = "Up";
- score = 0;
- GenerateFood();
- this.KeyDown += GameForm_KeyDown;
- timer.Start();
- }
- private void Timer_Tick(object sender, EventArgs e)
- {
- MoveSnake();
- CheckCollision();
- this.Invalidate();
- }
- private void MoveSnake()
- {
- Point head = snake[0];
- Point newHead = head;
- switch (direction)
- {
- case "Up":
- newHead.Y -= 1;
- break;
- case "Down":
- newHead.Y += 1;
- break;
- case "Left":
- newHead.X -= 1;
- break;
- case "Right":
- newHead.X += 1;
- break;
- }
- snake.Insert(0, newHead);
- if (newHead == food)
- {
- score++;
- GenerateFood();
- }
- else
- {
- snake.RemoveAt(snake.Count - 1);
- }
- }
- private void CheckCollision()
- {
- Point head = snake[0];
- if (head.X < 0 || head.X >= this.Width / 10 || head.Y < 0 || head.Y >= this.Height / 10)
- {
- GameOver();
- }
- for (int i = 1; i < snake.Count; i++)
- {
- if (head == snake[i])
- {
- GameOver();
- }
- }
- }
- private void GenerateFood()
- {
- Random rand = new Random();
- food = new Point(rand.Next(this.Width / 10), rand.Next(this.Height / 10));
- }
- private void GameOver()
- {
- timer.Stop();
- MessageBox.Show("游戏结束!得分:" + score);
- }
- private void GameForm_KeyDown(object sender, KeyEventArgs e)
- {
- switch (e.KeyCode)
- {
- case Keys.W:
- if (direction != "Down") direction = "Up";
- break;
- case Keys.S:
- if (direction != "Up") direction = "Down";
- break;
- case Keys.A:
- if (direction != "Right") direction = "Left";
- break;
- case Keys.D:
- if (direction != "Left") direction = "Right";
- break;
- }
- }
- protected override void OnPaint(PaintEventArgs e)
- {
- base.OnPaint(e);
- Graphics g = e.Graphics;
- foreach (Point p in snake)
- {
- g.FillRectangle(Brushes.Green, p.X * 10, p.Y * 10, 10, 10);
- }
- g.FillRectangle(Brushes.Red, food.X * 10, food.Y * 10, 10, 10);
- }
- }
- }
复制代码 |
|