私はスネークの簡単なゲームをプログラムしようとしていますが、食べ物を食べるたびにヘビを一貫して成長させるのに苦労しています. 最初に食べたものはセグメントを正しく追加しますが、2 個以上は追加しません。
問題は各セグメントの位置付けにあると思います。私のコードでは、ヘビが食べ物を食べたときの座標を含む と をリストし、新しい座標をSegmentX
ループでリストします。最初の食べ物が食べられた後、これが失敗する原因は何ですか?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);
}
}
}