using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CSightVisualizer : MonoBehaviour
{
public float radius = 3;
private void OnDrawGizmos()
{
GizmosExtensions.DrawWireArc(this.transform.position, this.transform.forward, 360, radius);
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UIElements;
public class Capsule : MonoBehaviour
{
public float speed = 5f;
void Start()
{
}
void Update()
{
Move();
}
private void Move()
{
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(h, 0, v);
this.transform.Translate(movement * speed * Time.deltaTime);
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Sphere : MonoBehaviour
{
public float radius = 3f; // 원의 반지름
public float rotationSpeed = 30f; // 캡슐의 회전 속도 (각도/초)
private Transform capsuleTransform; // 부모 오브젝트인 캡슐의 Transform
private void Start()
{
// 부모 오브젝트인 캡슐의 Transform 가져오기
capsuleTransform = transform.parent;
}
private void Update()
{
if (capsuleTransform != null)
{
// 현재 시간에 따른 회전 각도 계산
float rotationAngle = Time.time * rotationSpeed;
// 원 주위를 도는 위치 계산
float x = Mathf.Cos(rotationAngle) * radius;
float z = Mathf.Sin(rotationAngle) * radius;
// 부모 오브젝트의 위치를 기준으로 위치 설정
transform.position = capsuleTransform.position + new Vector3(x, 0f, z);
}
}
}
using UnityEngine;
public class Sphere : MonoBehaviour
{
public float radius = 3f; // 원의 반지름
public float rotationSpeed = 30f; // 캡슐의 회전 속도 (각도/초)
private Transform capsuleTransform; // 부모 오브젝트인 캡슐의 Transform
private void Start()
{
// 부모 오브젝트인 캡슐의 Transform 가져오기
capsuleTransform = transform.parent;
}
private void Update()
{
if (capsuleTransform != null)
{
// 캡슐의 회전 각도 계산
float rotationAngle = Time.time * rotationSpeed;
// 쿼터니언으로 캡슐의 회전을 설정
Quaternion rotation = Quaternion.Euler(0f, rotationAngle, 0f);
// 캡슐의 회전을 기반으로 원 주위를 도는 위치 계산
Vector3 positionOffset = rotation * (Vector3.forward * radius);
// 부모 오브젝트의 위치를 기준으로 위치 설정
transform.position = capsuleTransform.position + positionOffset;
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
public float speed = 1f;
public Rigidbody playerRigidbody;
public GameObject bulletPrefab;
void Update()
{
PlayerMove();
}
private void PlayerMove()
{
float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(h, 0, v) * speed;
transform.Translate(movement * Time.deltaTime);
}
private void OnTriggerEnter(Collider other)
{
// 충돌한 오브젝트가 총알인지 확인
if (other.CompareTag("Bullet"))
{
// 플레이어를 파괴
Destroy(gameObject);
Debug.Log("Game over");
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : MonoBehaviour
{
[SerializeField] GameObject player;
[SerializeField] public GameObject bulletPrefab;
private float spawnInterval = 3f; // 총알 생성 간격
private Vector3 spawnPosition; // 총알이 생성될 위치
void Start()
{
spawnPosition = this.gameObject.transform.position; // 총알이 생성될 위치 초기화
StartCoroutine(SpawnBullet()); // 코루틴 시작
}
IEnumerator SpawnBullet()
{
while (player != null)
{
// 총알 생성
Instantiate(bulletPrefab, spawnPosition, Quaternion.identity);
// 일정한 간격 기다리기
yield return new WaitForSeconds(spawnInterval);
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Bullet : MonoBehaviour
{
public float speed = 2f;
public GameObject player;
void Start()
{
player = GameObject.FindGameObjectWithTag("Player");
// Rigidbody 컴포넌트 가져오기
Rigidbody bullets = GetComponent<Rigidbody>();
Vector3 direction = (player.transform.position - transform.position).normalized;
transform.forward = direction;
// 총알의 이동 방향 설정 및 속도 적용
bullets.velocity = transform.forward * speed;
// 5초 후에 총알 파괴
Destroy(gameObject, 4.5f);
}
private void OnTriggerEnter(Collider other)
{
// 충돌한 오브젝트가 총알인지 확인
if (other.CompareTag("Player"))
{
Destroy(gameObject);
}
if (other.CompareTag("Wall"))
{
Destroy(gameObject);
}
}
}
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.SearchService;
public class coTest : MonoBehaviour
{
void Start()
{
//StartCoroutine(this.Sol1());
//StartCoroutine(this.Sol2());
}
void Update()
{
}
//1. 주어진 시간(예: 5초) 동안 특정 작업을 반복 실행하고 그 후에 작업을 중지하는 코루틴을 작성하세요.
//IEnumerator Sol1()
//{
// Debug.LogFormat("시작"); // 처음에 0초 출력
// yield return new WaitForSeconds(1); // 1초 대기
// for (int i = 1; i <= 5; i++)
// {
// Debug.LogFormat("{0}초 경과", i);
// yield return new WaitForSeconds(1); // 각 반복마다 1초씩 대기
// }
// Debug.Log("정지");
//}
//2. 리스트에 있는 항목을 하나씩 출력하고 각 항목을 출력한 후에 잠시 대기하는 코루틴을 만들어보세요.
//IEnumerator Sol2()
//{
// string[] items = { "cap", "clothes", "pants", "shoes" };
// foreach (string item in items)
// {
// Debug.Log(item);
// yield return new WaitForSeconds(1);
// }
// Debug.Log("모든 아이템 출력 완료");
//}
//3.플레이어가 특정 키를 누를 때까지 게임을 일시 중지하고, 그 키를 누르면 다시 게임을 계속하는 코루틴을 작성하세요.
}
using System.Collections;
using UnityEngine;
public class GameLogic : MonoBehaviour
{
private bool gamePaused = false;
void Start()
{
StartCoroutine(GameLoop());
}
//3. 플레이어가 특정 키를 누를 때까지 게임을 일시 중지하고, 그 키를 누르면 다시 게임을 계속하는 코루틴을 작성하세요.
IEnumerator GameLoop()
{
while (true)
{
if (!gamePaused)
{
// 게임이 진행 중인 경우 여기에 원하는 게임 로직을 추가
Debug.Log("게임 진행 중");
}
// 플레이어가 스페이스바를 누르면 일시 중지 상태를 변경
if (Input.GetKeyDown(KeyCode.Space))
{
gamePaused = !gamePaused;
if (gamePaused)
{
Debug.Log("게임 일시 중지");
Time.timeScale = 0f; // 게임 시간 정지
}
else
{
Debug.Log("게임 재개");
Time.timeScale = 1f; // 게임 시간 재개
}
}
yield return null;
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Tank : MonoBehaviour
{
public enum Mode
{
TankMode,
SiegeMode
}
void Start()
{
}
void Update()
{
if (Input.GetMouseButtonDown(1))
{
Vector3 mousePosScreen = Input.mousePosition;
Debug.Log(mousePosScreen); // 캔버스의 크기는 좌측하단 0*0 부터 1920 * 1080이지만 추가로 월드좌표가찍힘
}
}
}
이렇게 하면 Local position의 좌표가 찍히는데 이를 월드좌표로 바꿔줄 것이다.
월드 좌표로 바꾸어 보았다.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Tank : MonoBehaviour
{
public enum Mode
{
TankMode,
SiegeMode
}
void Start()
{
}
void Update()
{
if (Input.GetMouseButtonDown(1))
{
Vector3 mousePosScreen = Input.mousePosition;
//Debug.Log(mousePosScreen); // 캔버스의 크기는 좌측하단 0*0 부터 1920 * 1080이지만 추가로 월드좌표가찍힘
Vector2 mousePosWorld = Camera.main.ScreenToWorldPoint(mousePosScreen);
Debug.Log(mousePosWorld); // (0.00, 1,00)
}
}
}
좌하단 -> 중앙 -> 오른쪽위 순으로 나온 좌표이고
탱크의 위치는 0,0,0 으로 초기화
카메라는 탱크의 위치에 따라가게 Ctrl + Shift + F로 지정하였다.
탱크를 클릭한 위치로 이동하게 하였다.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Tank : MonoBehaviour
{
public float Speed = 3f;
public enum Mode
{
TankMode,
SiegeMode
}
void Start()
{
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Vector3 mousePosScreen = Input.mousePosition;
//Debug.Log(mousePosScreen); // 캔버스의 크기는 좌측하단 0*0 부터 1920 * 1080이지만 추가로 월드좌표가찍힘
Vector2 mousePosWorld = Camera.main.ScreenToWorldPoint(mousePosScreen);
Debug.Log(mousePosWorld); // (0.00, 1,00)
}
if (Input.GetMouseButton(1))
{
Vector3 mousePosScreen = Input.mousePosition;
Vector2 mousePosWorld = Camera.main.ScreenToWorldPoint(mousePosScreen);
this.transform.position = Vector3.MoveTowards(this.transform.position, mousePosWorld, Speed * Time.deltaTime);
}
}
}
this.transform.position: 현재 객체(탱크)의 위치를 나타냅니다.
mousePosWorld: 마우스의 현재 위치를 나타냅니다.
Speed * Time.deltaTime: 탱크가 이동할 속도를 결정합니다. Time.deltaTime은 이전 프레임부터 현재 프레임까지의 경과 시간을 나타내며, 이를 사용하여 프레임 레이트에 관계없이 일정한 속도로 이동할 수 있습니다.
스타크래프트 마우스를 클릭하고 있어야 되는 것이 아닌 한번 누르면 이동해야 하고 중간에 경로를 변경할 수 있어야 한다.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Tank : MonoBehaviour
{
public float Speed = 3f;
public Vector3 targetPosition = Vector3.zero; // 클릭한 위치를 저장할 변수
void Update()
{
if (Input.GetMouseButtonDown(1)) // 오른쪽 마우스 버튼을 클릭했을 때
{
// 마우스 클릭한 위치를 저장
Vector3 mousePosScreen = Input.mousePosition;
targetPosition = Camera.main.ScreenToWorldPoint(mousePosScreen);
//targetPosition.z = 0f; // 2D 게임에서 z 축 값은 0으로 고정
Debug.Log("New target position: " + targetPosition);
}
// 탱크가 저장된 위치로 이동
if (targetPosition != Vector3.zero)
{
transform.position = Vector3.MoveTowards(transform.position, targetPosition, Speed * Time.deltaTime);
// 탱크가 목표 위치에 도달하면 저장된 위치 초기화
if (this.transform.position == targetPosition)
{
targetPosition = Vector3.zero;
}
}
}
}
타켓(클릭된)좌표의 벡터를 0으로 초기화 => Vector3.zero
이동좌표를 정할 때
나중에 코드가 길어지면 업데이트에서 처리할일이 많아서 느려질 수 있으므로 코루틴을 사용했다.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Tank : MonoBehaviour
{
public float Speed = 3f;
public Vector3 targetPosition = Vector3.zero; // 클릭한 위치를 저장할 변수
private void Start()
{
}
void Update()
{
if (Input.GetMouseButtonDown(1)) // 오른쪽 마우스 버튼을 클릭했을 때
{
StartCoroutine(CoMove()); // 코루틴을 실행합니다.
}
}
IEnumerator CoMove()
{
// 마우스 클릭한 위치를 저장
Vector3 mousePosScreen = Input.mousePosition;
targetPosition = Camera.main.ScreenToWorldPoint(mousePosScreen);
//targetPosition.z = 0f; // 2D 게임에서 z 축 값은 0으로 고정
Debug.Log("New target position: " + targetPosition);
// 탱크가 저장된 위치로 이동
while ((targetPosition != Vector3.zero))
{
transform.position = Vector3.MoveTowards(transform.position, targetPosition, Speed * Time.deltaTime);
// 탱크가 목표 위치에 도달하면 저장된 위치 초기화
if (this.transform.position == targetPosition)
{
targetPosition = Vector3.zero;
}
yield return null;
}
}
}
하지만 실행을 해보니 클릭을 할 수록 빨라졌고 코루틴을 중지하는 것이 필요하다고 판단하였다.
멤버변수에 현재 실행중인 코루틴을 저장하기 위해 선언하였고
코루틴안에서 실행중이면 정지하도록 하고
다시 코루틴을 시작하게 하였다.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Tank : MonoBehaviour
{
public float Speed = 3f;
public Vector3 targetPosition = Vector3.zero; // 클릭한 위치를 저장할 변수
private Coroutine moveCoroutine; // 현재 실행 중인 코루틴을 저장하기 위한 변수
private void Start()
{
}
void Update()
{
if (Input.GetMouseButtonDown(1)) // 오른쪽 마우스 버튼을 클릭했을 때
{
// 기존에 실행 중인 코루틴이 있으면 중지시킴
if (moveCoroutine != null)
{
StopCoroutine(moveCoroutine);
}
// 새로운 코루틴 시작
moveCoroutine = StartCoroutine(CoMove()); // 코루틴을 실행합니다.
}
}
IEnumerator CoMove()
{
// 마우스 클릭한 위치를 저장
Vector3 mousePosScreen = Input.mousePosition;
targetPosition = Camera.main.ScreenToWorldPoint(mousePosScreen);
//targetPosition.z = 0f; // 2D 게임에서 z 축 값은 0으로 고정
Debug.Log("New target position: " + targetPosition);
// 탱크가 저장된 위치로 이동
while ((targetPosition != Vector3.zero))
{
transform.position = Vector3.MoveTowards(transform.position, targetPosition, Speed * Time.deltaTime);
// 탱크가 목표 위치에 도달하면 저장된 위치 초기화
if (this.transform.position == targetPosition)
{
targetPosition = Vector3.zero;
}
yield return null;
}
}
}
코드를 수정하기 전에도 있었던 문제 같은데 위치에 도달하면 Tank가 사라지는 것을 발견
scene에는 있는데 game scene에서 사라지는 이유를 찾다가
layer in order로 맵뒤에 있는건 아닌지 확인도 하였지만
알고보니, 2D인데 클릭한 좌표가 z축이 입력되서 카메라 시점이 같이 움직였기에 시야 밖에서 사라진 것이었다.
z좌표를 0 으로 초기화하는 변수를 지정하고 인자로 넣어주었더니 문제 없이 실행되었다.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Tank : MonoBehaviour
{
public float Speed = 3f;
private Vector3 targetPosition = Vector3.zero; // 클릭한 위치를 저장할 변수
private Coroutine moveCoroutine; // 현재 실행 중인 코루틴을 저장하기 위한 변수
void Update()
{
if (Input.GetMouseButtonDown(1)) // 오른쪽 마우스 버튼을 클릭했을 때
{
// 기존에 실행 중인 코루틴이 있으면 중지시킴
if (moveCoroutine != null)
{
StopCoroutine(moveCoroutine);
}
// 새로운 코루틴 시작
moveCoroutine = StartCoroutine(CoMove()); // 코루틴을 실행합니다.
}
}
IEnumerator CoMove()
{
// 마우스 클릭한 위치를 저장
Vector3 mousePosScreen = Input.mousePosition;
targetPosition = Camera.main.ScreenToWorldPoint(mousePosScreen);
Debug.Log("New target position: " + targetPosition);
// 탱크가 저장된 위치로 이동
while (Vector3.Distance(transform.position, targetPosition) > 0.01f)
{
Vector3 movePos = new Vector3(targetPosition.x, targetPosition.y, 0);
transform.position = Vector3.MoveTowards(transform.position, movePos, Speed * Time.deltaTime);
yield return null;
}
// 탱크가 목표 위치에 도달하면 저장된 위치 초기화
targetPosition = Vector3.zero;
}
}
더 해야할 부분 :
아직 미완성인 부분 o버튼 누를경우 이미지 시즈모드로 변경 다시 o누르면 탱크모드
+ 이동중에 o를 누르면 그 자리에서 즉시 이미지 변경
우선 O키를 눌러서 콘솔에 찍어보았고
움직이는 중간에 계속 콘솔에 찍혔다.
이 점에 대해 구현을 한다면 O를 누르면 시즈모드가 멈추고 이미지가 변경 되어야 할 것이다.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Tank : MonoBehaviour
{
public float Speed = 3f;
private Vector3 targetPosition = Vector3.zero; // 클릭한 위치를 저장할 변수
private Coroutine moveCoroutine; // 현재 실행 중인 코루틴을 저장하기 위한 변수
void Update()
{
if (Input.GetMouseButtonDown(1)) // 오른쪽 마우스 버튼을 클릭했을 때
{
// 기존에 실행 중인 코루틴이 있으면 중지시킴
if (moveCoroutine != null)
{
StopCoroutine(moveCoroutine);
}
// 새로운 코루틴 시작
moveCoroutine = StartCoroutine(CoMove()); // 코루틴을 실행합니다.
}
if (Input.GetKeyDown(KeyCode.O))
{
Debug.Log("시즈모드 전환");
}
}
IEnumerator CoMove()
{
// 마우스 클릭한 위치를 저장
Vector3 mousePosScreen = Input.mousePosition;
targetPosition = Camera.main.ScreenToWorldPoint(mousePosScreen);
Debug.Log("New target position: " + targetPosition);
// 탱크가 저장된 위치로 이동
while (Vector3.Distance(transform.position, targetPosition) > 0.01f)
{
Vector3 movePos = new Vector3(targetPosition.x, targetPosition.y, 0);
transform.position = Vector3.MoveTowards(transform.position, movePos, Speed * Time.deltaTime);
yield return null;
}
// 탱크가 목표 위치에 도달하면 저장된 위치 초기화
targetPosition = Vector3.zero;
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BionicUnit
{
public enum BionicUnitType
{
Marine,
Medic
}
public BionicUnitType type;
public string name;
public BionicUnit(BionicUnitType type, string name)
{
this.type = type;
this.name = name;
}
}
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class DropShip : MonoBehaviour
{
//마린과 메딕을 관리할 리스트
public List<BionicUnit> units = new List<BionicUnit>();
//최대로 태울 수 있는 인원의 수
public const int CAPACITY = 8;
void Start()
{
//생성자를 만든다
BionicUnit medic = new BionicUnit(BionicUnit.BionicUnitType.Medic, "메딕");
BionicUnit marine1 = new BionicUnit(BionicUnit.BionicUnitType.Marine, "마린1");
BionicUnit marine2 = new BionicUnit(BionicUnit.BionicUnitType.Marine, "마린2");
BionicUnit marine3 = new BionicUnit(BionicUnit.BionicUnitType.Marine, "마린3");
BionicUnit marine4 = new BionicUnit(BionicUnit.BionicUnitType.Marine, "마린4");
BionicUnit marine5 = new BionicUnit(BionicUnit.BionicUnitType.Marine, "마린5");
BionicUnit marine6 = new BionicUnit(BionicUnit.BionicUnitType.Marine, "마린6");
BionicUnit marine7 = new BionicUnit(BionicUnit.BionicUnitType.Marine, "마린7");
BionicUnit marine8 = new BionicUnit(BionicUnit.BionicUnitType.Marine, "마린8");
LoadUnit(medic);
LoadUnit(marine1);
LoadUnit(marine2);
LoadUnit(marine3);
LoadUnit(marine4);
LoadUnit(marine5);
LoadUnit(marine6);
LoadUnit(marine7);
LoadUnit(marine8);
UnLoad(medic);
UnLoadAll();
}
public void LoadUnit(BionicUnit unit)
{
if (units.Count >= CAPACITY)
{
Debug.Log("<color=red> 자리가 없어서 탑승에 실패 </color>");
}
else
{
units.Add(unit);
Debug.LogFormat("{0}이 탑승했습니다. ({1}/{2})", unit.type, units.Count, CAPACITY);
//Debug.LogFormat("{0}이 탑승했습니다. ({1}/{2})", unit.name, units.Count, CAPACITY);
}
}
public void UnLoad(BionicUnit unit)
{
this.units.Remove(unit);
Debug.LogFormat("{0}이 하차했습니다. ({1},{2})", unit.type, units.Count, CAPACITY);
}
public void UnLoadAll()
{
Debug.Log("모두 하차 시작");
foreach (BionicUnit unit in units.ToList())
//()이나 Start() 메서드에서 units 리스트를 수정하지 않도록 합니다. 리스트를 수정할 필요가 있다면 반복문 밖에서 수정
{
UnLoad(unit);
}
}
}
이런식으로 .ToList()를 쓰지 않으면 오류가 난다.
이유를 찾아보니 멤버변수에 선언한 "원본" 리스트를 변경시키기 때문에 나는 현상이라고 한다.
값이 어떻게 이동되는지 이름만 옮겨지는지 이름과 값이 함께 쌍으로 넘어가는지 이 부분이 어려웠다.
Debug로 콘솔에 많이 찍어보고 값이 어떻게 출력이 되는지 확인하는데 시간을 가장 많이 썼다.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
public MonsterController[] monsters;
void Start()
{
List<MonsterController> list = new List<MonsterController>();
for (int i = 0; i < monsters.Length; i++)
{
//몬스터컨트롤러의 인스턴스 생성
MonsterController controller = monsters[i];
//Debug.Log(controller);
//플레이어와의 거리 구하기
float distance = Vector3.Distance(this.transform.position, controller.transform.position);
//Debug.LogFormat("이름 : {0}, 거리 : {1}",controller.gameObject.name, distance);
//Debug.Log(controller.gameObject.name);
if (distance <= 10)
{
list.Add(controller); //객체 형태로 담긴다
}
}
for(int i = 0; i < list.Count; i++)
{
MonsterController controller = list[i];
float distance = Vector3.Distance(this.transform.position, controller.transform.position);
//Debug.LogFormat("이름 : {0} , 거리 : {1}", controller.gameObject.name, distance);
}
//거리가 제일 가까운 객체 찾기
float minDistance = Mathf.Infinity; // 초기값을 무한대로 지정
MonsterController minObject = null; // 초기값을 담을 인스턴스 생성
for(int i = 0; i < list.Count;i++)
{
MonsterController controller = list[i];
float distance = Vector3.Distance(this.transform.position, controller.transform.position);
if (distance < minDistance)
{
minDistance = distance;
minObject = controller;
}
}
Debug.LogFormat("거리가 가장 가까운 객체 : {0}, 거리 : {1}", minObject.name, minDistance);
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CSightVisualizer : MonoBehaviour
{
public float radius = 3;
private void OnDrawGizmos()
{
GizmosExtensions.DrawWireArc(this.transform.position, this.transform.forward, 360, radius);
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MonsterController : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
점프 : 흐름을 특정 위치로 단번에 이동 break, continue, goto, return, throw
break 반복문이나 switch문의 실행을 중단
continue 반복을 건너 뛰어 반복을 계속 수행
goto 지정한 레이블로 제어를 이동
패턴매칭 식이 특정패턴과 일치하는지를 검사
패턴매칭1 : 선언 패턴 주어진 식이 특정형식(int, string) 과 일치하는지를 평가
패턴매칭2 : 형식 패턴 선언 패턴과 거의 비슷하지만 변수를 선언하지 않는다.
패턴매칭3 : 상수 패턴 식이 특정 상수와 일치하는지를 검사
패턴매칭4 : 프로퍼티 패턴 식의 속성이나 필드가 패턴과 일치하는지를 검사
패턴매칭5 관계 패턴 관계 연사자를 이용하여 입력받은 식을 상수와 비교
패턴매칭6 : 논리패턴 복수의 패턴을 논리 연산자(and, or, not)로 조합
패턴매칭7 : 괄호패턴 괄호()로 패턴을 감쌈
패턴매칭8 : 위치 패턴 식의 결과를 분해하고, 분해된 값들이 내장된 복수의 패턴과 일치하는지 검사
패턴매칭9 : var 패턴 null을 포함한 모든 식의 패턴 매칭을 성공시키고, 그 식의 결과를 변수에 할당
패턴매칭10 : 무시 팬턴 var패턴처럼 모든 식과의 패턴 일치 검사를 성공 단, is식에서는 사용할 수 없고, switch식에서만 사용 가능
패턴매칭11 : 목록 패턴 배열이나 리스트가 패턴의 시퀀스가 일치하는지를 검사
using System;
using System.Collections.Generic;
using System.Diagnostics.Tracing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _20240226
{
internal class Program
{
static void Main(string[] args)
{
//int a = 1;
//while(a== 2)
//{
// Console.WriteLine("true");
//}Console.WriteLine("false");
//1. 구구단 출력하기: 사용자로부터 숫자를 입력받아 해당 숫자의 구구단을 출력하는 프로그램을 작성하세요.
//for (int i = 1; i <= 9; i++)
//{
// for(int j = 1; j <= 9; j++)
// {
// Console.WriteLine($"{i} * {j} = {i * j}");
// }
//}
//2. 숫자 맞히기 게임: 컴퓨터가 1에서 100 사이의 무작위 숫자를 선택하고, 사용자가 그 숫자를 맞히는 게임을 만드세요.사용자가 입력한 숫자가 정답보다 크면 "더 작은 수를 입력하세요"를, 작으면 "더 큰 수를 입력하세요"를 출력하세요. 정답을 맞힐 때까지 반복합니다.
//Random random = new Random(); //Random 클래스 인스턴스 생성
//int rand = random.Next(1, 101);// 1부터 100까지 난수 생성
//Console.Write("숫자를 입력하세요. >> ");
//int num = int.Parse(Console.ReadLine());
//Console.WriteLine("컴퓨터가 입력한 숫자는 {0}입니다.", rand);
//if (rand == num)
//{
// Console.WriteLine("정답");
//}
//else Console.WriteLine("오답");
//3. 짝수와 홀수 합계: 1에서 100까지의 모든 짝수와 홀수의 합을 구하는 프로그램을 작성하세요.
//int odd = 0;
//int even = 0;
//for (int i = 1; i <= 100; i++)
//{
// if(i % 2 != 0)
// {
// odd += i;
// }else if(i % 2 == 0)
// {
// even += i;
// }
//}
//Console.WriteLine(odd);
//Console.WriteLine(even);
//4. 사용자가 입력한 수의 팩토리얼 계산: 사용자로부터 정수를 입력받고, 그 수의 팩토리얼을 계산하여 출력하는 프로그램을 작성하세요.
//int a = Convert.ToInt32(Console.ReadLine());
//int factorialA = 1;
//for(int i = 1; i <= a; i++)
//{
// factorialA *= i;
//}
//Console.WriteLine(factorialA);
//5. 세 수 중 최댓값 찾기: 사용자로부터 세 개의 숫자를 입력받고, 그 중 가장 큰 숫자를 출력하는 프로그램을 작성하세요.
//int a = Convert.ToInt32(Console.ReadLine());
//int b = Convert.ToInt32(Console.ReadLine());
//int c = Convert.ToInt32(Console.ReadLine());
//int maxNum = a;
//if( b > maxNum)
//{
// maxNum = b;
//}
//if( c > maxNum)
//{
// maxNum = c;
//}
//Console.WriteLine("입력된 숫자중 가장 큰 수는 {0} 입니다. ", maxNum);
}
}
}
int a = 10;
Console.WriteLine(++a);
// a = 11
int b = 10;
Console.WriteLine(b++);
// b = 10
Console.WriteLine(b++);
// b = 11
전위 연산자는 보기와 같이 기존에 정해진 값에서 더한 후 그 값을 출력
후위 연산자는 출력된 후 더하므로
다음 출력때 더해진 값을 출력
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _20240223
{
internal class Program
{
static void Main(string[] args)
{
//사용자로부터 두 개의 숫자를 입력 받아 덧셈, 뺄셈, 곱셈, 나눗셈 연산을 수행하고 결과를 출력하는 프로그램을 작성하세요.
//Console.WriteLine(10 + 5);
//Console.WriteLine(10 - 5);
//Console.WriteLine(10 * 5);
//Console.WriteLine(10 / 5);
//반지름을 입력 받아 원의 넓이를 계산하여 출력하는 프로그램을 작성하세요. (힌트: 원의 넓이 공식 - π * r * r)
//int r = 5;
//float circle = r * r * 3.14f;
//Console.WriteLine(circle);
//비교 연산자:
//사용자로부터 두 개의 숫자를 입력 받아 두 숫자가 같은지 여부를 판단하여 결과를 출력하는 프로그램을 작성하세요.
//Console.WriteLine(10 == 5);
//사용자로부터 세 개의 숫자를 입력 받아 가장 큰 숫자를 출력하는 프로그램을 작성하세요.
//int num1 = Convert.ToInt32(Console.ReadLine());
//int num2 = Convert.ToInt32(Console.ReadLine());
//int num3 = Convert.ToInt32(Console.ReadLine());
//int maxNum = Math.Max(num1, Math.Max(num2, num3));
//Console.WriteLine(maxNum);
//논리 연산자:
//사용자로부터 입력받은 숫자가 짝수인지 여부를 판단하여 결과를 출력하는 프로그램을 작성하세요.
//int num = int.Parse(Console.ReadLine());
//bool isEven = num % 2 == 0;
//Console.WriteLine(isEven);
//사용자로부터 입력받은 숫자가 3의 배수인지 그리고 5의 배수인지를 동시에 판단하여 결과를 출력하는 프로그램을 작성하세요.
//int num = int.Parse(Console.ReadLine());
//if(num % 15 == 0)
//{
// Console.WriteLine("3과 5배 공배수");
//}
//else if(num % 3 == 0)
//{
// Console.WriteLine("3의 배수입니다.");
//}else if(num % 5 == 0){
// Console.WriteLine("5의 배수");
//}
//else {
// Console.WriteLine("다른 수");
//}
//대입 연산자:
//사용자로부터 숫자를 입력 받아 그 숫자를 10배로 증가시킨 후 결과를 출력하는 프로그램을 작성하세요.
//int number = Convert.ToInt32(Console.ReadLine());
//int result = number * 10;
//Console.WriteLine("Result: " + result);
//두 변수의 값을 교환하는 프로그램을 작성하세요. (예: 변수 a에 5, 변수 b에 10이 있다면 a에는 10, b에는 5가 저장되어야 함)
//int a = 10;
//int b = 20;
//int temp = a;
//a = b;
//b = temp;
//Console.Write("a는 {0} b는 {1}", a, b);
}
}
}
쌓인 순서의 역순으로 필요 없는 데이터를 자동으로 제거(자동메모리) => LIFO(Last In First Out)
힙(Heap):
자유롭게 데이터를 저장할 수 있는 메모리
별명 : 자유 저장소
값 형식(Value Type):
메모리에 값을 담는 형식
스택에 할당
기본 데이터 형식과 구조체가 여기에 해당됨
참조형식(Reference Type):
메모리에 다른 변수의 "주소를 담는" 데이터 형식
힙에 할당
기본 데이터 형식(Primitive Types)
수 형식(정수 형식, 부동 소수점 형식)
논리 형식
문자열 형식
object 형식
복합데이터 형식 : 기본 데이터 형식을 바탕으로 만들어짐
박싱 : 값 형식을 object형식에 담아 힙에 올리기 언박싱 : 힙에 올라가 있는 데이터를 object에서 꺼내 값 형식으로 옮기기
변수 : 변경이 가능한 수 상수 : 항상 최초의 상태를 유지하는 수 -> 변경하려는 시도시 컴파일 에러
열거형식 : 하나의 이름 아래 묶인 상수들의 집합
=> enum키워드 사용 상수 선언시 ex) enum dia{yes} -> dia.yes;
var키워드 - 컴파일러가 자동으로 형식을 추론 ex) var a = 3; // a는 int 형식 주의 : "지역변수 안"에서만 사용가능(메소드 안에서만 ) + 클래스, 구조체 사용불가
using System;
using System.Collections.Generic;
using System.Data.SqlTypes;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _20240222
{
internal class Program
{
static void Main(string[] args)
{
//변수(Variables)에 대한 예제 문제:
//1-1. 특정 프로그램에서 사용자의 이름을 입력받아 변수에 저장하고, 그 이름을 환영하는 메시지를 출력하는 프로그램을 작성하세요.
//string a = "예준";
//Console.WriteLine($"어서오세요 {a}");
//Console.WriteLine("어서오세요 {0}", a);
//2-2. 특정 도시의 현재 온도를 나타내는 변수를 만들고, 이 변수의 값을 5도 증가시킨 후 새로운 온도를 출력하는 프로그램을 작성하세요.
//int temp = 24;
//int now = temp + 5;
//Console.WriteLine($"현재 온도는 {now}도 입니다");
//3-3. 사용자로부터 두 개의 숫자를 입력받아 변수에 저장하고, 이 두 숫자를 더한 결과를 출력하는 프로그램을 작성하세요.
//int a = 10;
//int b = 20;
//Console.WriteLine(a + b);
//상수(Constants)에 대한 예제 문제:
//2-1. 원주율을 상수로 선언하여 반지름이 5인 원의 넓이를 계산하여 출력하는 프로그램을 작성하세요.
//float pi = 3.14f;
//int r = 5; // => float 과 int 의 곱이 된다.
//float size = pi * pi * r;
//Console.WriteLine(size);
//2-2. 세금 비율을 0.1로 상수로 선언하고, 사용자로부터 어떤 상품의 가격을 입력받아 세금을 계산하여 총 가격을 출력하는 프로그램을 작성하세요.
//float rate = 0.1f;
//float price = 50.6f;
//float total = rate * price;
//Console.WriteLine(total); //=> 5.06
//2-3. 1년에는 몇 개의 달이 있는지를 상수로 선언하고, 이 값을 사용하여 1년이 몇 개의 주가 있는지를 출력하는 프로그램을 작성하세요.
//int CountOfMonth = 12;
//int day = 365;
//float CountOfWeek = day / CountOfMonth;
//Console.WriteLine(CountOfWeek);
// => 인트형끼리 나누면 소수점 자리가 Truncate을 하지 않아도 된다.
//float CountOfMonth = 12f;
//float day = 365f;
////float CountOfWeek = Math.Truncate(day / CountOfMonth); ==> 오류
//float CountOfWeek = day / CountOfMonth;
//Console.WriteLine(Math.Truncate(CountOfWeek)); // 30
}
}
}