|
发表于 2025-4-4 15:14:33
|
显示全部楼层
- 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()
- {
- // ...(其他初始化代码保持不变)
- snake = new List<Point> { new Point(10, 10), new Point(10, 11), new Point(10, 12) }; // 修正:明确泛型
- // ...(其他代码保持不变)
- }
- private void MoveSnake()
- {
- Point head = snake[0]; // 修正:访问列表第一个元素
- // ...(剩余代码保持不变)
- }
- private void CheckCollision()
- {
- Point head = snake[0]; // 修正:访问列表第一个元素
- // 修正碰撞检测逻辑
- for (int i = 1; i < snake.Count; i++)
- {
- if (head.Equals(snake[i])) // 修正:比较坐标而非引用
- {
- GameOver();
- }
- }
- }
- private void GenerateFood()
- {
- Random rand = new Random();
- do {
- food = new Point(rand.Next(this.ClientSize.Width / 10),
- rand.Next(this.ClientSize.Height / 10));
- } while (snake.Contains(food)); // 新增:确保食物不在蛇身上
- }
- }
- }
复制代码
主要修正点:
- 泛型集合声明:将 List snake 改为 List<Point>
- 蛇头获取方式:使用 snake[0] 代替直接使用列表
- 碰撞检测:使用 Equals() 比较坐标值而非引用
- 食物生成:增加循环检测确保食物不会出现在蛇身上
- 使用 ClientSize 代替 Width/Height 获取有效绘图区域
仍可改进的方面:
- 添加游戏重启功能
- 增加难度等级(速度随分数提升)
- 添加音效和更丰富的UI
遇到具体运行问题可以贴出错误信息,我会继续帮你分析~
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |
|