我正在尝试编写一个简单的 Snake 游戏,但在吃完每一块食物后,我无法让蛇持续生长。吃掉的第一个正确添加了一个片段,但 2+ 个片段没有。
我认为问题在于每个细分市场的定位。在我的代码中,我列出了SegmentX
and SegmentY
,其中包含蛇在吃一块食物时的坐标,并且我在一个foreach
循环中列出了新坐标。吃完第一块食物后,什么会导致失败?
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 Zmijice
{
enum SnakeControl
{
Right,Left,Up,Down,Stop
}
public partial class Zmijice : Form
{
private int snakeX;
private int snakeY;
private int newX;
private int newY;
private int foodX;
private int foodY;
private const int height=20;
private const int width=20;
private List<int> SegmentX = new List<int>();
private List<int> SegmentY = new List<int>();
Random rnd = new Random();
private SnakeControl Position;
public Zmijice()
{
InitializeComponent();
RandomFoodPosition();
RandomSnakePosition();
Position = SnakeControl.Stop;
}
public void RandomFoodPosition()
{
foodX = rnd.Next(1, 20) * 20;
foodY = rnd.Next(1, 20) * 20;
}
public void RandomSnakePosition()
{
snakeX = rnd.Next(1, 20) * 20;
snakeY = rnd.Next(1, 20) * 20;
}
private void Tajmer_Tick(object sender, EventArgs e)
{
if (Position == SnakeControl.Stop)
{
}
else if (Position == SnakeControl.Right)
{
snakeX += 20;
}
else if (Position == SnakeControl.Left)
{
snakeX -= 20;
}
else if (Position == SnakeControl.Up)
{
snakeY -= 20;
}
else if (Position == SnakeControl.Down)
{
snakeY += 20;
}
Invalidate();
}
private void Zmijice_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Down)
{
Position = SnakeControl.Down;
}
else if (e.KeyCode == Keys.Up)
{
Position = SnakeControl.Up;
}
else if (e.KeyCode == Keys.Right)
{
Position = SnakeControl.Right;
}
else if (e.KeyCode == Keys.Left)
{
Position = SnakeControl.Left;
}
}
private void Zmijice_Paint(object sender, PaintEventArgs e)
{
//if snake eaten food
//int counter = 0;
if (snakeX==foodX && snakeY==foodY)
{
//new food position
foodX = rnd.Next(1, 20);
foodX = foodX * 20;
foodY = rnd.Next(1, 20);
foodY = foodY * 20;
//counter++;
//grow up snake
SegmentX.Add(snakeX);
SegmentY.Add(snakeY);
//movement for new snake part
if (Position == SnakeControl.Left)
{
newX = snakeX+20;
newY = snakeY;
}
if (Position == SnakeControl.Right)
{
newX = snakeX-20;
newY = snakeY;
}
if (Position == SnakeControl.Up)
{
newX = snakeX;
newY = snakeY+20;
}
if (Position == SnakeControl.Down)
{
newX = snakeX;
newY = snakeY-20;
}
}
//render snake parts
foreach (int k in SegmentX)
{
foreach (int l in SegmentY)
{
e.Graphics.FillRectangle(Brushes.Orange, newX, newY, width, height);
}
}
//new position is equal old position
newX = snakeX;
newY = snakeY;
e.Graphics.FillRectangle(Brushes.DarkRed, snakeX, snakeY, width, height);
e.Graphics.FillRectangle(Brushes.Aqua, foodX, foodY, width, height);
}
}
}