ヘビの表現
Snakeゲームの作成は非常に簡単です。最初に必要なのは、蛇の体を表す方法です。あなたのヘビがブロックまたはタイルで構成されていると考える場合、あなたの体は単にこれらのブロック座標のリストになります。
あなたの場合、コンソールアプリケーションを実行する場合、これらはそれぞれコンソール上のキャラクターになり、位置はコンソール出力の1行または1行に対応します。だからあなたはこれから始めます:
// List of 2D coordinates that make up the body of the snake
List<Point>() body = new List<Point>();
この時点では、リストは空なので、ヘビには体がありません。長さ5のヘビが必要で、頭が位置(5,2)から始まり、下に向かって成長するとします。たとえば、ゲームの開始時にこれらの位置をリストに追加します。
// Initialize the snake with 5 blocks starting downwards from (5,2)
for(int i=0; i<5; ++i)
{
body.Add(new Point(5, 2 + i));
}
ヘビのレンダリング
レンダリングの場合は、ボディリストの各位置にキャラクターを描くだけです。たとえば、上記の例は次のように描くことができます。
...................
...................
.....O............. -- y = 2
.....#.............
.....#.............
.....#.............
.....V.............
...................
|
x = 5
キャラクターの頭(リストの最初の要素)と尻尾(リストの最後の要素)に異なる文字を選択し、隣接するブロックの位置に応じて方向を変えることで、さらに複雑になります。しかし、初心者にとっては、すべてを#
何かとしてレンダリングするだけです。
たとえば、次のような背景を含む2D char配列で開始できます。
// Array with map characters
char[,] render = new char[width, height];
// Fill with background
for(x=0; x<width; ++x)
for(y=0; y<height; ++y)
render[x,y] = '.';
そして、蛇の体を反復して配列に描画します。
// Render snake
foreach(Point point in body)
render[point.X, point.Y] = '#';
最後に、配列をもう一度繰り返して、各文字をコンソールに書き込みます。各行の最後に改行が入ります。
// Render to console
for(y=0; y<height; ++y)
{
for(x=0; x<width; ++x)
{
Console.Write(render[x,y]);
}
Console.WriteLine();
}
ヘビの移動
最後に、動き。最初に必要なことはDirection
、蛇が動いているのを追跡することです。これは単純な列挙型にすることができます。
// Enum to store the direction the snake is moving
enum Direction { Left, Right, Up, Down }
そして、リストから最後のブロックを削除し、それを正面に正しい方向に追加するだけで、ヘビを動かす行為を行うことができます。つまり、次のようなものです。
// Remove tail from body
body.RemoveAt(body.Count - 1);
// Get head position
Point next = body[0];
// Calculate where the head should be next based on the snake's direction
if(direction == Direction.Left)
next = new Point(next.X-1, next.Y);
if(direction == Direction.Right)
next = new Point(next.X+1, next.Y);
if(direction == Direction.Up)
next = new Point(next.X, next.Y-1);
if(direction == Direction.Down)
next = new Point(next.X, next.Y+1);
// Insert new head into the snake's body
body.Insert(0, next);