C#프로그래밍
2차원 배열을 통한 맵 이동 (워프 히어로)
EasyCastleT
2023. 7. 25. 18:12
벡터(위치 정보 및 인덱스 정보 활용)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LearnDotnet
{
//구조체 : 값형식 -> 스택
//기본생성자 못씀
//상속이 불가, 기본클래스로 못씀
//인터페이스 사용가능
internal struct Vector2
{
public int x;
public int y;
//생성자
public Vector2(int x, int y)
{
this.x = x;
this.y = y;
}
//부모클래스의 virtual 멤버 메서드 재정의
public override string ToString()
{
return $"({this.x},{this.y})";
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LearnDotnet
{
internal class Utils
{
//좌표를 인덱스로
public static Vector2 ConvertPosition2Indices(Vector2 position)
{
return new Vector2(position.y, position.x);
}
//인덱스를 좌표로
public static Vector2 ConvertIndices2Position(Vector2 indices)
{
return new Vector2(indices.y, indices.x);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LearnDotnet
{
internal class Hero
{
//멤버 변수
public Vector2 position; //영웅의 위치
int[,] playerMap; //index 정보 저장
int id; //영웅의 id
string name; //영웅의 이름
//생성자
public Hero()
{
this.id = 100;
this.name = "Zave";
}
public Hero(int id, string name)
{
this.id = id;
this.name = name;
}
//멤버 메서드
//처음 위치 초기화 하는 기능
public void Init(Vector2 position, int[,]playerMap)
{
this.position = position;
this.playerMap = playerMap;
UpdatePlayerMap(this.position);
}
//현재 위치를 출력하는 기능
public void PrintPosition()
{
Console.WriteLine("영웅의 현재 위치:{0}",this.position.ToString());
}
//영웅 움직임
public void WarpHero(Vector2 position)
{
if((position.x>=0 && position.x<=3) && (position.y >=0 && position.y <= 4))
{
Vector2 indices = Utils.ConvertPosition2Indices(this.position);
this.playerMap[indices.x, indices.y] = 0;
this.position = position;
UpdatePlayerMap(this.position);
}
else
{
Console.WriteLine("이동할 수 없는 곳입니다");
}
}
void UpdatePlayerMap(Vector2 pos)
{
Vector2 indices = Utils.ConvertPosition2Indices(pos);
this.playerMap[indices.x, indices.y] = this.id;
}
//플레이어맵 출력
public void PrintPlayerMap()
{
for (int i = 0; i < this.playerMap.GetLength(0); i++)
{
for (int j = 0; j < this.playerMap.GetLength(1); j++)
{
Console.Write("[영웅의 index {0},{1}]:{2} ", i, j, this.playerMap[i, j]);
}
Console.WriteLine();
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LearnDotnet
{
internal class App
{
int[,] map = new int[4, 3];
//생성자
public App()
{
Hero hero = new Hero();
hero.Init(new Vector2(2,3),map); //좌표 2,3 에서 시작
hero.PrintPosition(); //현재 좌표 출력
hero.PrintPlayerMap(); //현재 맵의 index 전부 출력
hero.WarpHero(new Vector2(2,0));
hero.PrintPosition();
hero.PrintPlayerMap();
hero.WarpHero(new Vector2(4, 0));
}
}
}