[C#] 貪食X
前言
呱呱有一位同事叫吱吱,
吱吱非常的愛吃香蕉,
吱吱由於要吃大量的香蕉常常導致月底沒錢,
所以呱呱為了讓吱吱可以吃飽飽,
決定寫一個香蕉吃到飽的程式給吱吱!
(直接複製之前的文章 爽啦)
事前準備
目標是做個類似貪食蛇的東西,
其實沒什麼好準備的,
真的要說的話,
只需要開發者腦袋有洞吧!
實作
這次做的東西照舊是不難(呱呱也寫不出很難的程式),
想當然爾,
本呱又不想設計畫面了,
所以再次使用Console專案開發,
流程是這樣的,
1. 遊戲的難度是可抽換調整的
public interface ILevel
{
int MapWidth { get; set; }
int MapHeight { get; set; }
int DefaultSpeed { get; set; }
int LengthLimit { get; set; }
}
2. 動物也是可抽換調整的
public interface IAnimal
{
string Tag { get; set; }
int[] LocationX { get; set; }
int[] LocationY { get; set; }
int Length { get; set; }
EDirection Direction { get; set; }
}
3. 被吃的東西也是可以抽換調整的
public interface IFruit
{
string Tag { get; set; }
int Score { get; set; }
int LocationX { get; set; }
int LocationY { get; set; }
}
4. 遊戲開始後實作該介面
Level = new Level()
{
MapWidth = 20,
MapHeight = 20,
DefaultSpeed = 50,
LengthLimit = 20
};
Animal = new Monkey()
{
LocationX = new int[Level.LengthLimit],
LocationY = new int[Level.LengthLimit],
Length = 1,
Direction = EDirection.Down
};
Fruit = new Banana(10, 18);
5. 增加監聽鍵盤事件 觸發改變動物前進方向
var key = Console.ReadKey(true).Key;
switch (key)
{
case ConsoleKey.UpArrow:
if (Animal.Direction != EDirection.Down)
Animal.Direction = EDirection.Up;
break;
case ConsoleKey.DownArrow:
if (Animal.Direction != EDirection.Up)
Animal.Direction = EDirection.Down;
break;
case ConsoleKey.LeftArrow:
if (Animal.Direction != EDirection.Right)
Animal.Direction = EDirection.Left;
break;
case ConsoleKey.RightArrow:
if (Animal.Direction != EDirection.Left)
Animal.Direction = EDirection.Right;
break;
}
6. 增加動物前進事件 判斷位置與動物與水果的觸碰條件
var previousX = int.Parse(Animal.LocationX[0].ToString());
var previousY = int.Parse(Animal.LocationY[0].ToString());
for (int i = Animal.Length - 1; i >= 1; i--)
{
Animal.LocationX[i] = Animal.LocationX[i - 1];
Animal.LocationY[i] = Animal.LocationY[i - 1];
}
switch (Animal.Direction)
{
case EDirection.Up:
Animal.LocationY[0]--;
break;
case EDirection.Down:
Animal.LocationY[0]++;
break;
case EDirection.Left:
Animal.LocationX[0]--;
break;
case EDirection.Right:
Animal.LocationX[0]++;
break;
}
if (Animal.LocationX[0] == Fruit.LocationX && Animal.LocationY[0] == Fruit.LocationY)
{
var rnd = new Random();
Fruit.LocationX = rnd.Next(1, Level.MapWidth - 1);
Fruit.LocationY = rnd.Next(1, Level.MapWidth - 1);
Animal.LocationX[Animal.Length] = previousX;
Animal.LocationY[Animal.Length] = previousY;
Animal.Length++;
}
7. 於是程式完成 吱吱終於可以吃香蕉吃到飽了
結語
畫面閃爍到本呱覺得自己快瞎了
最後附上本呱的原始碼