PlayGame.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Study05
{
    public class PlayGame
    {
        private int[] board;
        private Random random = new Random();

        // 생성자
        public PlayGame()
        {
            this.board = new int[4];
        }

        public void CreateNewBlock()
        {
            int index = -1;
            while (true)
            {
                index = this.GetRandomIndex();
                if (this.board[index] == 0)
                {
                    this.board[index] = this.InitStartNumber();
                    break;
                }
            }
            this.PrintBlock();
        }

        public void StartMoveLeft()
        {
            int num = -1;
            int index = -1;
            for (int i = 0; i < this.board.Length; i++)
            {
                num = this.board[i];

                if (num != 0)
                {
                    index = i;
                }
            }
            for (int i = 0; i < this.board.Length; i++)
            {
                this.MoveLeft();
            }
        }

        public void MoveLeft()
        {
            for (int i = 0; i < this.board.Length; i++)
            {
                int num = this.board[i];
                if (num != 0)
                {
                    if (i == 0) return;
                    this.board[i - 1] = num;
                    this.board[i] = 0;
                }
            }
            this.PrintBlock();
        }

        public void StartGame()
        {
            this.CreateInitBlock();
            this.PrintBlock();
        }

        public void CreateInitBlock()
        {
            int index = this.GetRandomIndex();
            int num = this.InitStartNumber();
            this.board[index] = num;
        }

        public int InitStartNumber()
        {
            int initNum = this.random.Next(1, 3) * 2;
            return initNum;
        }

        public int GetRandomIndex()
        {
            int index = this.random.Next(0, 4);
            return index;
        }

        public void PrintBlock()
        {
            for (int i = 0; i < this.board.Length; i++)
            {
                Console.Write("{0} ", this.board[i]);
            }
            Console.WriteLine();
        }
    }
}

2. App.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Study05
{
    public class App
    {

        // 생성자
        public App()
        {
            PlayGame game = new PlayGame();
            game.StartGame();
            game.StartMoveLeft();
            game.CreateNewBlock();
        }
    }
}

+ Recent posts