카테고리 없음

본캠프 7일차_TIL

티-히히 2024. 9. 20. 20:23

오버로딩
동일한 메서드 이름을 가지고 있지만 매개변수의 타입이나 순서에 따라 매서드를 정의하는 것.

public class Calculator
{
    public int Add(int a, int b)
    {
        return a + b;
    }

    public int Add(int a, int b, int c)
    {
        return a + b + c;
    }
}

Calculator calc = new Calculator();
int result1 = calc.Add(2, 3);         // 5
int result2 = calc.Add(2, 3, 4);      // 9





오버라이딩

부모 클래스에서 정의된 매서드를 자식클래스가 재정의하는 것.

매서드 이름, 매개변수, 반환타입이 동일해야함.

{
    public virtual void Draw()
    {
        Console.WriteLine("Drawing a shape.");
    }
}

public class Circle : Shape
{
    public override void Draw()
    {
        Console.WriteLine("Drawing a circle.");
    }
}

public class Rectangle : Shape
{
    public override void Draw()
    {
        Console.WriteLine("Drawing a rectangle.");
    }
}

Shape shape1 = new Circle();
Shape shape2 = new Rectangle();

shape1.Draw();  // Drawing a circle.
shape2.Draw();  // Drawing a rectangle. 



 

 

 

스네이크게임만들기

 

1. 문제점

사실 게임 구조에대해서 아무것도 파악이 되지않은 상태라 아무것도 못하는 상태입니다.

 

2. 시도해본 것

먼저 생성해야하는 객체부터 생각해봤습니다

먹이

그 이후로 생각나는게 없었습니다


3. 해결 방법

풀이를 먼저보고 그 풀이를 해석한 다음

직접 코드를 쳐보기로 했습니다

더보기

1. 변수 지정하기

int gameSpeed = 100;
int foodCount = 0;

속도를 조정하기위한 변수와

먹은 음식의 수 변수를 지정해줍니다 

 

 

2. 벽 그리기

 DrawWalls()
 
 static void DrawWalls()
{
    // 상하 벽 그리기
    for (int i = 0; i < 80; i++)
    {
        Console.SetCursorPosition(i, 0);
        Console.Write("#");
        Console.SetCursorPosition(i, 20);
        Console.Write("#");
    }

    // 좌우 벽 그리기
    for (int i = 0; i < 20; i++)
    {
        Console.SetCursorPosition(0, i);
        Console.Write("#");
        Console.SetCursorPosition(80, i);
        Console.Write("#");
    }
}

 

Console.SetCursorPosition() 은 텍스트를 출력하되 x와y값을 받아 출력할 수 있는 메서드입니다.

Console.SetCursorPosition(int left, int top);

이 함수를 이용해 벽을 그려줍니다

 

 

 3. 뱀의 초기위치와 방향 설정하기

Point p = new Point(4, 5, '*');
Snake snake = new Snake(p, 4, Direction.RIGHT);
snake.Draw();
public class Point
{
    public int x { get; set; }
    public int y { get; set; }
    public char sym { get; set; }

    // Point 클래스 생성자
    public Point(int _x, int _y, char _sym)
    {
        x = _x;
        y = _y;
        sym = _sym;
    }

Point 클래스를 이용해 객체를 생성해줍니다.

인자값은 4, 5 '*'를 받아줍니다

 

여기서 궁금한점.

 public int x { get; set; }
 public int y { get; set; }
 public char sym { get; set; }

 

 이 부분은 굳이 { get; set; }을 쓰지 않고도 코드가 돌아가는데에 문제가 없습니다.

하지만 왜? 쓰는 것 일까요

 

캡슐화를 통해 값 제어를 할 수 있기 때문입니다

지금은 아무런 조건문이 붙지 않았지만

추후에 필요할 시 조건문을 넣어 제어할 수 있게 만들어둔 겁니다.

public int X
    {
        get { return _x; } // 값을 읽음
        set
        {
            if (value >= 0) // 값이 0 이상인 경우에만 설정
                _x = value;
            else
                Console.WriteLine("X는 음수일 수 없습니다.");
        }
    }

 

이런 코드는 확장성유지보수성  보안성을 확보할 수 있습니다.

 

4.알게 된 것

주말에도 공부해야할 것 같습니다.