Notice
Recent Posts
Recent Comments
Link
스토리지
[3.19] 2048 게임 (1차원) 본문
using System;
using System.Collections.Generic;
namespace Study08
{
//게임을 구동하는 클래스
public class GameLauncher
{
public struct Position
{
public int row;
public Position(int row)
{
this.row = row;
}
}
private int[] arrPlate; //판
public GameLauncher()
{
}
//초기화
public void Init()
{
Console.WriteLine("초기화 합니다.");
CreatePlate();
}
//새로운 판을 생성
public void CreatePlate()
{
this.arrPlate = new int[4];
CreateBlock();
Print();
}
//빈 자리 중 한 칸에 랜덤하게 2 또는 4가 나온다
public void CreateBlock()
{
Random r = new Random();
int row;
do
{
if (!CheckZero())
{
Print();
Console.WriteLine("빈칸 없음");
EndGame();
}
row = r.Next(0, 4);
} while (arrPlate[row] != 0);
arrPlate[row] = (r.Next(1, 101) <= 50 ? 2 : 4);
}
//게임 시작
public void StartGame()
{
while (true)
{
ConsoleKeyInfo keyInfo = Console.ReadKey();
Console.WriteLine();
Console.Clear();
if (keyInfo.Key == ConsoleKey.LeftArrow)
{
for (int i = 1; i < arrPlate.Length; i++)
{
int pos = 0;
if (arrPlate[i] != 0)
{
pos = i;
while (pos > 0 && arrPlate[pos - 1] == 0)
{
Swap(new Position(pos--), new Position(pos));
}
}
if (pos > 0 && pos < arrPlate.Length && arrPlate[pos - 1] == arrPlate[pos])
{
arrPlate[pos - 1] *= 2;
arrPlate[pos] = 0;
}
}
CreateBlock();
Print();
}
else if (keyInfo.Key == ConsoleKey.RightArrow)
{
for (int i = arrPlate.Length - 2; i >= 0; i--)
{
int pos = 0;
if (arrPlate[i] != 0)
{
pos = i;
while (pos < arrPlate.Length - 1 && arrPlate[pos + 1] == 0)
{
Swap(new Position(pos++), new Position(pos));
}
}
if (pos > 0 && pos < arrPlate.Length - 1 && arrPlate[pos + 1] == arrPlate[pos])
{
arrPlate[pos + 1] *= 2;
arrPlate[pos] = 0;
}
}
CreateBlock();
Print();
}
else if (keyInfo.Key == ConsoleKey.Escape)
{
this.EndGame();
}
}
}
//게임 종료
public void EndGame()
{
Console.WriteLine("게임종료");
System.Diagnostics.Process.GetCurrentProcess().Kill();
}
private void Swap(Position a, Position b)
{
int tmp = arrPlate[b.row];
arrPlate[b.row] = arrPlate[a.row];
arrPlate[a.row] = tmp;
}
private void Print()
{
for (int i = 0; i < arrPlate.Length; i++)
{
Console.Write("{0} ", arrPlate[i]);
}
Console.WriteLine();
}
private bool CheckZero()
{
foreach (var i in arrPlate)
{
if (i == 0)
return true;
}
return false;
}
}
}
'Unity > 수업내용(C#)' 카테고리의 다른 글
[3.22] delegate 대리자 (0) | 2021.03.22 |
---|---|
[3.19] Partial 클래스 (분할 클래스) (0) | 2021.03.19 |
[3.18] 2차원 배열 연습 5 - 2차원 배열을 이용한 좌표 이동 (0) | 2021.03.18 |
[3.18] 2차원 배열 연습 4 - Isometric View (0) | 2021.03.18 |
[3.18] 2차원 배열 연습 3 (0) | 2021.03.18 |
Comments