강의

멘토링

로드맵

Inflearn brand logo image

인프런 커뮤니티 질문&답변

이강토님의 프로필 이미지
이강토

작성한 질문수

[C#과 유니티로 만드는 MMORPG 게임 개발 시리즈] Part2: 자료구조와 알고리즘

오른손 법칙

콘솔창에 격자가 안나옴 미로 생성 X

해결된 질문

작성

·

83

0

미로 생성 25*25 격자가 콘솔창에 출력 되지 않고 있습니다..

1.Board 코드
*****************************************************************************
using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

namespace C__알고리즘_6_플레이어_이동

{

class Board

{

const char CIRCLE = '\u25cf';

public TileType[,] Tile { get; private set; } //배열

public int Size { get; private set; }

public int DestY { get; private set; }

public int DestX { get; private set; }

Player _player;

public enum TileType

{

Empty,

Wall,

}

public void Initialize(int size, Player player)

{

if (size % 2 == 0)

return;

_player = player;

Tile = new TileType[size, size];

Size = size;

DestY = Size - 2;

DestX = Size - 2;

GenerateBySideWinder();

}

public void GenerateBySideWinder()

{

// 일단 길을 다 막아버리는 작업

for (int y = 0; y < Size; y++)

{

for (int x = 0; x < Size; x++)

if (x % 2 == 0 || y % 2 == 0)

Tile[y, x] = TileType.Wall;

else

Tile[y, x] = TileType.Empty;

}

// 랜덤으로 우측 혹은 아래로 길을 뚫는 작업

// Binary Tree Algorithm

Random rand = new Random();

for (int y = 0; y < Size; y++)

{

int count = 1;

for (int x = 0; x < Size; x++)

{

if (x % 2 == 0 || y % 2 == 0)

continue;

if (y == Size - 2 && x == Size - 2)

continue;

if (y == Size - 2)

{

Tile[y, x + 1] = TileType.Empty;

continue;

}

if (x == Size - 2)

{

Tile[y + 1, x] = TileType.Empty;

continue;

}

if (rand.Next(0, 2) == 0)

{

Tile[y, x + 1] = TileType.Empty;

count++;

}

else

{

int ramdomIndex = rand.Next(0, count);

Tile[y + 1, x - ramdomIndex * 2] = TileType.Empty;

count = 1;

}

}

}

}

public void Render()

{

ConsoleColor prevColor = Console.ForegroundColor;

for (int y = 0; y < Size; y++)

{

for (int x = 0; x < Size; x++)

{

// 플레이어 좌표를 갖고 와서, 그 좌표랑 현재 y, x가 일치하면 플레이어 전용 색상으로 표시

if (y == player.PosY && x == player.PosX)

Console.ForegroundColor = ConsoleColor.Blue;

else if(y == DestY && x == DestX)

Console.ForegroundColor = ConsoleColor.Yellow;

else

Console.ForegroundColor = GetTileColor(Tile[y, x]);

Console.Write(CIRCLE);

}

Console.WriteLine();

}

Console.ForegroundColor = prevColor;

}

ConsoleColor GetTileColor(TileType type)

{

switch (type)

{

case TileType.Empty:

return ConsoleColor.Green;

case TileType.Wall:

return ConsoleColor.Red;

default:

return ConsoleColor.Green;

}

}

}

}
*****************************************************************************
2. Player 코드
using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

namespace C__알고리즘_6_플레이어_이동

{

class Pos

{

public Pos(int y, int x) { Y = y; X = x; }

public int Y;

public int X;

}

class Player

{

public int PosY { get; private set; }

public int PosX { get; private set; }

Random _random = new Random();

Board _board;

enum Dir

{

Up = 0,

Left = 1,

Down = 2,

Right = 3

}

int _dir = (int)Dir.Up;

List<Pos> _points = new List<Pos>();

public void Initialize(int posY, int posX, Board board)

{

PosY = posY;

PosX = posX;

_board = board;

// 현재 바라보고 있는 방향을 기준으로, 좌표 변화를 나타낸다.

int[] frontY = new int[] { -1, 0, 1, 0 };

int[] frontX = new int[] { 0, -1, 0, 1 };

int[] rightY = new int[] { 0, -1, 0, 1 };

int[] rightX = new int[] { 1, 0, -1, 0 };

_points.Add(new Pos(PosY, PosX));

// 목적지 도착하기 전에는 계속 실행

while (PosY != board.DestY || posX != board.DestX)

{

// 1. 현재 바라보는 방향을 기준으로 오른쪽으로 갈 수 있는지 확인.

if (_board.Tile[PosY + rightY[_dir], PosX + rightX[_dir]] == Board.TileType.Empty)

{

// 오른쪽 방향으로 90도 회전

dir = (dir - 1 + 4) % 4;

// 앞으로 한 보 전진.

PosY = PosY + frontY[_dir];

PosX = PosX + frontX[_dir];

_points.Add(new Pos(PosY, PosX));

}

// 2. 현재 바라보는 방향을 기준으로 전진 할 수 있는지 확인.

else if (_board.Tile[PosY + frontY[_dir], PosX + frontX[_dir]] == Board.TileType.Empty)

{

// 앞으로 한 보 전진

PosY = PosY + frontY[_dir];

PosX = PosX + frontX[_dir];

_points.Add(new Pos(PosY, PosX));

}

else

{

//왼쪽 방향으로 90도 회전

dir = (dir + 1 + 4) % 4;

}

}

}

const int Move_TICK = 10;

int _sumTick = 0;

int _lastIndex = 0;

public void Update(int deltaTick)

{

if (_lastIndex >= _points.Count)

return;

_sumTick += deltaTick;

if(_sumTick >= Move_TICK)

{

_sumTick = 0;

PosY = points[lastIndex].Y;

PosX = points[lastIndex].X;

_lastIndex++;

}

}

}

}

*****************************************************************************
3. Progarm 코드
namespace C__알고리즘_6_플레이어_이동

{

internal class Program

{

static void Main(string[] args)

{

Board board = new Board();

Player player = new Player();

board.Initialize(25, player);

player.Initialize(1, 1, board);

Console.CursorVisible = false;

const int WAIT_TICK = 1000 / 30;

int lastTick = 0;

while (true)

{

#region 프레임 관리

int currentTick = Environment.TickCount & Int32.MaxValue;

// FPS 프레임 (60프레임 O 30프레임 이하 X)

// 만약에 경과한 시간이 1/30초보다 작다면

if (currentTick - lastTick < WAIT_TICK)

continue;

int deltaTick = currentTick - lastTick;

lastTick = currentTick;

#endregion

// 입력

// 로직

player.Update(deltaTick);

// 렌더링

Console.SetCursorPosition(0, 0);

board.Render();

}

}

}

}

답변 1

0

안녕하세요, 인프런 AI 인턴입니다. 이강토님 질문에 대한 답을 드리기 위해 비슷한 상황에서의 기존 답변을 찾아보았습니다.

질문하신 내용은 콘솔 창에 미로 격자가 출력되지 않는 문제에 관련된 것으로 보입니다. 이와 관련하여 이전에 비슷한 문제를 겪은 수강생들의 질문을 참고하였습니다.

기존 유사 질문과 답변

  1. 콘솔 창에 텍스트가 제대로 출력되지 않는 문제는 주로 콘솔의 기본 설정이나 코드의 순서와 관련이 있습니다. 예를 들어, 이 케이스에서는 콘솔 창 폰트를 변경하거나, 콘솔 창의 크기를 적절히 조정하기를 권장했습니다.
  2. 플레이어의 위치나 맵이 올바르게 렌더링되지 않는 경우, 코드의 프레임 관리 로직이나 변수 초기화 부분에서 실수가 있을 수 있습니다. 관련 참고: 플레이어 이동 문제.

해결을 위한 권장 사항

  • 콘솔 창 설정 확인: 콘솔 창의 글꼴을 변경해보세요. 특정 글꼴이 아니라면 유니코드 문자 등이 올바르게 렌더링되지 않을 수 있습니다.
  • 프레임 관리 점검: 프레임 관리 로직에서 deltaTick과 관련하여 누락된 진행이 없도록 코드를 검토하세요. 정확한 간격으로 보드가 렌더링되고 있는지 확인합니다.
  • 변수 및 코드 로직 확인: 코드상의 오타(예: _ dir 대신 _dir)나 논리적 순서에 문제가 없는지 확인하세요.
  • 콘솔 초기화: loop 안에서 Console.Clear()와 같은 코드를 사용하여 매 프레임 시작 시 콘솔 창을 초기화하는 방법도 고려해 보세요.
// 예시로, 매 프레임마다 콘솔을 지우고 새로 출력
Console.Clear();
Console.SetCursorPosition(0, 0);
board.Render();

위 해결 방안을 참고하여 문제를 해결해보시기 바랍니다.

저는 질문자님의 이해를 돕고자 지식공유자님의 기존 답변을 참고하여 유사한 답변 링크를 추천해드리고 있습니다. 현재 베타 기능으로 답변이 만족스럽지 않을 수 있는 점 양해 부탁드립니다. 🙏 추가적으로 궁금한 점이 있으시면, 이어서 질문해 주세요. 곧 지식공유자께서 답변해 주실 것입니다.

이강토님의 프로필 이미지
이강토

작성한 질문수

질문하기