142 lines
3.4 KiB
C#
142 lines
3.4 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace Snake
|
|
{
|
|
public class Game
|
|
{
|
|
Worm worm;
|
|
private Directions _direction = Directions.Down;
|
|
Random random = new Random();
|
|
Map map;
|
|
Form1 form;
|
|
|
|
int mapSize = 20;
|
|
|
|
public Game(Form1 form)
|
|
{
|
|
this.form = form;
|
|
}
|
|
|
|
public void Start()
|
|
{
|
|
Cell startCell = new Cell(10, 10, CellTypes.Snake);
|
|
map = new Map(mapSize, mapSize);
|
|
map.SetCell(startCell);
|
|
worm = new Worm(startCell);
|
|
SpawnApple();
|
|
}
|
|
|
|
public void UpdateInput(Directions direction)
|
|
{
|
|
if (_direction == Directions.Down && direction == Directions.Up) return;
|
|
if (_direction == Directions.Up && direction == Directions.Down) return;
|
|
if (_direction == Directions.Left && direction == Directions.Right) return;
|
|
if (_direction == Directions.Right && direction == Directions.Left) return;
|
|
|
|
_direction = direction;
|
|
}
|
|
|
|
public Cell GetNextCell()
|
|
{
|
|
int x = worm.Body[0].X;
|
|
int y = worm.Body[0].Y;
|
|
|
|
if (_direction == Directions.Up)
|
|
{
|
|
return map.Cells[x, y + 1];
|
|
}
|
|
|
|
if (_direction == Directions.Left)
|
|
{
|
|
return map.Cells[x - 1, y];
|
|
}
|
|
|
|
if (_direction == Directions.Down)
|
|
{
|
|
return map.Cells[x, y - 1];
|
|
}
|
|
|
|
// Right
|
|
return map.Cells[x + 1, y];
|
|
}
|
|
|
|
public bool IsNextPosOutOfBounds()
|
|
{
|
|
int x = worm.Body[0].X;
|
|
int y = worm.Body[0].Y;
|
|
|
|
if (_direction == Directions.Up)
|
|
if (y + 1 >= mapSize) return true;
|
|
|
|
if (_direction == Directions.Left)
|
|
if (x - 1 < 0) return true;
|
|
|
|
if (_direction == Directions.Down)
|
|
if (y - 1 < 0) return true;
|
|
|
|
if (_direction == Directions.Right)
|
|
if (x + 1 >= mapSize) return true;
|
|
|
|
return false;
|
|
}
|
|
|
|
public void SpawnApple()
|
|
{
|
|
int x = random.Next(mapSize);
|
|
int y = random.Next(mapSize);
|
|
|
|
Cell cell = map.Cells[x, y];
|
|
|
|
if (cell.Type == CellTypes.None)
|
|
{
|
|
cell.Type = CellTypes.Food;
|
|
return;
|
|
}
|
|
|
|
SpawnApple();
|
|
}
|
|
|
|
public void Update()
|
|
{
|
|
if (IsNextPosOutOfBounds())
|
|
{
|
|
Die();
|
|
return;
|
|
}
|
|
|
|
int x = worm.Body[0].X;
|
|
int y = worm.Body[0].Y;
|
|
|
|
Cell snakeCell = map.Cells[x, y];
|
|
Cell nextCell = GetNextCell();
|
|
|
|
if (nextCell.Type == CellTypes.Snake)
|
|
{
|
|
Die();
|
|
return;
|
|
}
|
|
|
|
if (nextCell.Type == CellTypes.Food)
|
|
{
|
|
worm.Eat(ref nextCell);
|
|
SpawnApple();
|
|
}
|
|
|
|
map.SwapCells(snakeCell, nextCell);
|
|
worm.Move(x, y, map);
|
|
|
|
map.Render(form.gamearea.CreateGraphics());
|
|
form.Invalidate();
|
|
}
|
|
|
|
public void Die()
|
|
{
|
|
form.timer.Enabled = false;
|
|
}
|
|
}
|
|
}
|