C#프로그래밍
2차원 배열 응용, 맵 만들기
EasyCastleT
2023. 7. 25. 16:47
벡터
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 string nickName;
public Vector2 position;
int[,] playerMap;
int id;
//생성자
public Hero(int id, string nickName)
{
this.id = id;
this.nickName = nickName;
Console.WriteLine(this.nickName);
}
public void Init(int [,] playerMap,Vector2 position)
{
this.playerMap = playerMap;
this.position = position; //초기 위치 설정
this.UpdatePlayerMap();
// Console.WriteLine(this.position.ToString());
}
//위치를 출력
public void PrintPosition()
{
Console.WriteLine("좌표: {0}",this.position.ToString());
}
//위치를 변경하는 메서드
public void UpdatePosition(Vector2 targetPosition)
{
this.position = targetPosition;
}
//위치가 바뀔때마다 playerMap을 업데이트
void UpdatePlayerMap()
{
Vector2 indices = Utils.ConvertPosition2Indices(this.position);
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("[{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[,] playerMap= new int[3,3];
//생성자
public App()
{
Hero hero = new Hero(100,"Zave");
hero.Init(playerMap, new Vector2(1, 2)); //초기 위치 정보 및 플레이어맵 초기화
hero.PrintPosition();
hero.PrintPlayerMap();
}
}
}