유니티3D 프로그래밍
C# 1주차 2일 수업 내용 (21.03.09) 본문
Char형 형변환
다양한 형태의 형변환을 테스트 해보고 실행되는 코드를 찾는다.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Study01
{
class Program
{
static void Main(string[] args)
{
//char Character = 'j';
//int integer = (int)Char.GetNumericValue(Character);
//Console.WriteLine(integer); //-1
//char Character = 'j';
//int integer = int.Parse(Character.ToString());
//Console.WriteLine(integer);
//char letterA = Convert.ToChar(106);
//Console.WriteLine(letterA);
int x = Convert.ToInt32('j');
Console.WriteLine(x);
}
}
}
주석 처리된 3개의 코드는 맞지 않은 형태의 형변환이다.
enum 테스트
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Study01
{
public enum Days
{
Numbers = 20,
DayType = 3
}
class Program
{
static void Main(string[] args)
{
int abc = (int)Days.Numbers;
Console.WriteLine(abc);
}
}
}
연산자에 관하여
산술 연산자
단항 : ++(증분), --(감소), +(더하기), -(빼기) 연산자
이진 : *(곱하기), /(나누기), %(나머지), +(더하기) 및 -(빼기) 연산자
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Study01
{
class Program
{
static void Main(string[] args)
{
int a = 33;
int b = 8;
Console.WriteLine(a + b);
Console.WriteLine(a - b);
Console.WriteLine(a * b);
Console.WriteLine(a / b);
Console.WriteLine(a % b);
}
}
}
복합 할당식
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Study01
{
class Program
{
static void Main(string[] args)
{
int a = 5;
a += 9;
Console.WriteLine(a); // output : 14
a -= 4;
Console.WriteLine(a); // output : 10
a *= 2;
Console.WriteLine(a); // output : 20
a /= 4;
Console.WriteLine(a); // output : 5
a %= 3;
Console.WriteLine(a); // output : 2
}
}
}
마린과 히드라
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Study01
{
class Program
{
static void Main(string[] args)
{
string marine = "marine";
int marineDamage = 1;
string hydra = "hydra";
int hydraMaxHp = 10;
int hydraHp = hydraMaxHp;
hydraHp -= marineDamage;
float per = (float)hydraHp / hydraMaxHp * 100f;
Console.WriteLine("{0}이 {1}를 공격 했습니다. -{2}", marine, hydra, marineDamage);
Console.WriteLine("hydra HP : {0}/{1} ({2}%)", hydraHp, hydraMaxHp, per);
}
}
}
증가 감소 연산자
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Study01
{
class Program
{
static void Main(string[] args)
{
int level = 1;
string name = "홍길동";
// 홍길동님이 레벨업을 했습니다.
Console.WriteLine("{0}님이 레벨업을 했습니다. +1", name);
// 홍길동님의 레벨이 2가 되었습니다.
level++;
Console.WriteLine("{0}님의 레벨이 {1}가 되었습니다.", name, level);
Console.WriteLine();
int enhanced = 3;
string weaponName = "장검";
//장검+3
Console.WriteLine("{0}+{1}", weaponName, enhanced);
//강화시도
Console.WriteLine("강화시도");
//강화실패
Console.WriteLine("강화실패");
//장검+2
Console.WriteLine("{0}+{1}", weaponName, --enhanced);
}
}
}
modulo operation
(%) 홀수, 짝수 검사에 사용
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Study01
{
class Program
{
static void Main(string[] args)
{
int a = 123;
Console.WriteLine(a % 3); // 0
a = 388;
Console.WriteLine(a % 3); // 1
a = 8;
Console.WriteLine(a % 3); // 2
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Study01
{
class Program
{
static void Main(string[] args)
{
Random rand = new Random();
int num = rand.Next(0, 101);
Console.WriteLine(num);
Console.WriteLine(num % 3);
num = rand.Next(0, 101);
Console.WriteLine(num);
Console.WriteLine(num % 3);
}
}
}
비교 연산자
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Study01
{
class Program
{
static void Main(string[] args)
{
int a = 50, b = 80;
Console.WriteLine(a < b); // 50 < 60, True
Console.WriteLine(a > b); // 50 > 60, False
Console.WriteLine(a == b); // 50 == 60, False
Console.WriteLine(a != b); // 50 != 60, True
Console.WriteLine(a >= b); // 50 >= 60, False
Console.WriteLine(a <= b); // 50 <= 60, True
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Study01
{
class Program
{
static void Main(string[] args)
{
string heroName = "홍길동";
int heroMaxHp = 10;
float heroHp = heroMaxHp;
int heroDamage = 3;
string monsterName = "고블린";
float monsterDamage = 2.5f;
int monsterMaxhp = 2;
int monsterHp = monsterMaxhp;
//홍길동이 고블린으로부터 피해(-2.5)를 받았습니다. (7.5/10) 75%
heroHp = heroHp - monsterDamage;
float per = heroHp / heroMaxHp * 100;
Console.WriteLine("{0}이 {1}으로부터 피해(-{2})를 받았습니다. ({3}/{4}) {5}%", heroName, monsterName, monsterDamage, heroHp, heroMaxHp, per);
//고블린이 홍길동으로부터 피해 (-3)을 받았습ㄴ다. (0/2) 0%
monsterHp = monsterHp - heroDamage;
Console.WriteLine("{0}이 {1}으로부터 피해(-{2})을 받았습니다. ({3}/{4})", monsterName, heroName, heroDamage, monsterHp, monsterMaxhp);
//고블린 생존 여부 : False
Boolean monsterIsArrive = monsterHp >= 0;
Console.WriteLine("{0} 생존여부 : {1}", monsterName, monsterIsArrive);
}
}
}
부울 논리 연산자
단항 : !(논리 부정) 연산자
이진 : &(논리 AND) | 논리(OR) 및 ^ (논리 배타적 OR) 연산자
이진 : &&(조건부 논리 AND), 및 ||(조건부 논리 OR)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Study01
{
class Program
{
static void Main(string[] args)
{
string name = "홍길동";
float sight = 5.4f;
float attackRange = 3.3f;
float heroX = 0;
float heroY = 0;
string monsterName = "고블린";
float monsterX = 4f;
float monsterY = 3f;
double a = Math.Pow(monsterX - heroX, 2);
double b = Math.Pow(monsterY = heroY, 2);
double distance = Math.Sqrt(a + b);
Console.WriteLine(distance);
//AND 논리 연산자 &&
//모두 True 몇 결과 값은 True
//하나라도 False면 False
bool isAttackAvailable = (distance < sight) && (distance <= attackRange);
//홍길동이 고블린을 공격할 수 있는 상태인가?
Console.WriteLine("{0}이 {1}을 공격할 수 있는 상태인가 : {2}", name, monsterName, isAttackAvailable);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Study01
{
class Program
{
static void Main(string[] args)
{
string heroName = "홍길동";
float heroDamage = 1.5f;
Random random = new Random();
int num = random.Next(0, 101);
bool isAttackSuccess = true;
bool isCriticalAttack = (num > 20) && isAttackSuccess;
Console.WriteLine(isCriticalAttack);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Study01
{
class Program
{
static void Main(string[] args)
{
int dungeonRequirelevel = 30;
int player1Level = 10; // 쪼렙
int player2Level = 60; // 만렙
bool isAvailableEnter = (player1Level >= dungeonRequirelevel) || (player2Level >= dungeonRequirelevel);
Console.WriteLine("입장 가능 여부 : " + isAvailableEnter);
int player1Hp = 10;
bool isAlive = player1Hp > 0;
bool isDie = !isAlive;
}
}
}
비트 및 시프트 연산자
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Study01
{
class Program
{
static void Main(string[] args)
{
//삼항 연산자
string result = 1 > 3 ? "사실" : "거짓";
//int result = 1 > 3 ? 100 : 200;
Console.WriteLine(result);
}
}
}
문 (Statement)
문은 프로그램 명령이며 순서대로 실행된다.
프로그램이 수행하는 작업은 문으로 표현된다.
프로그램에서 문이 실행되는 순서를 제어 흐름 또는 실행 흐름이라고 한다.
제어 흐름은 프로그램이 런타임 시 수신하는 입력에 대응하는 방식에 따라 프로그램 할 때마다 달라질 수 있다.
문은 세미콜론으로 끝나는 코드 한 줄이나 일련의 한 줄 문으로 이루어진 블록일 수 있다.
문 블록은 {} 괄호로 묶여 있으며 중첩 블록을 포함할 수 있다.
if-else문
if문은 부울 식에 따라서 실행할 문을 작성한다.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Study01
{
class Program
{
static void Main(string[] args)
{
int heroHp = 10;
string heroName = "홍길동";
heroHp -= 100;
Console.WriteLine("name: {0}, hp : {1}", heroName, heroHp);
if(heroHp <= 0)
{
Console.WriteLine("{0}님이 사망했습니다.", heroName);
heroHp = 0;
Console.WriteLine("name: {0}, hp : {1}", heroName, heroHp);
}
else
{
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Study01
{
class Program
{
static void Main(string[] args)
{
int reinforcePercent = 13;
Random rand = new Random();
int num = rand.Next(0, 101);
if(num > reinforcePercent)
{
//강화 성공
Console.WriteLine("강화 성공");
}
else
{
//강화 실패
Console.WriteLine("강하 실패");
}
}
}
}
Switch문
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Study01
{
class Program
{
static void Main(string[] args)
{
string fruitsName = "샤인머스켓";
switch(fruitsName)
{
case "포도":
Console.WriteLine("포도입니다");
break;
case "바나나":
Console.WriteLine("바나나입니다");
break;
case "수박":
Console.WriteLine("수박입니다");
break;
default:
Console.WriteLine("{0}입니다.", fruitsName);
break;
}
}
}
}
반복문
for문
for문은 지정된 부울 식이 true로 계산되는 동안 문 또는 문 블록을 실행합니다.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Study00
{
class Program
{
static void Main(string[] args)
{
int count = 0;
for (int i = 0; i < 5; i++) {
Console.WriteLine("줄넘기를 {0}회 했습니다.", i+1);
count++;
}
Console.WriteLine("******************");
Console.WriteLine("총 줄넘기한 횟수 : {0}회", count);
//줄넘기를 1회 했습니다.
//줄넘기를 2회 했습니다.
//줄넘기를 3회 했습니다.
//줄넘기를 4회 했습니다.
//줄넘기를 5회 했습니다.
//**********************
//총 줄넘기한 횟수 : 5회
}
}
}
While문
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Study01
{
class Program
{
static void Main(string[] args)
{
int n = 0;
while (n < 5)
{
Console.WriteLine(n);
n++;
}
}
}
}
foreach문
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Study01
{
class Program
{
static void Main(string[] args)
{
string[] names = new string[3] {"홍길동", "임꺽정", "장길산"};
foreach(string name in names)
{
Console.WriteLine(name);
}
}
}
}
점프문
break문
break문 배치된 지점에서 가장 가까운 바깥쪽 루프 또는 switch문을 종료한다.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Study01
{
class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 100; i++)
{
if(i == 5)
{
break;
}
Console.WriteLine(i);
}
}
}
}
continue문
continue문은 자신이 나타나는 바깥쪽 while, do, for 또는 foreach 문의 다음 반복으로 제어를 전달한다.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Study01
{
class Program
{
static void Main(string[] args)
{
for(int i = 0; i <= 10; i++)
{
if(i < 9)
{
continue;
}
Console.WriteLine(i);
}
}
}
}
예제
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Study01
{
class Program
{
static void Main(string[] args)
{
string terranMarin = "마린";
int marinPower = 2;
int marinHp = 10;
string zergZergling = "저글링";
int zerglingPower = 1;
int zerglingMaxHp = 5;
int zerglingHp = zerglingMaxHp;
float per;
Console.WriteLine("{0}이 생성되었습니다.", terranMarin);
Console.WriteLine("공격력 : {0}", marinPower);
Console.WriteLine("체력 : {0}", marinHp);
Console.WriteLine("{0}이 생성되었습니다.", zergZergling);
Console.WriteLine("공격력 : {0}", zerglingPower);
Console.WriteLine("체력 : {0}", zerglingMaxHp);
for(int i = 0; i < 3; i++)
{
zerglingHp -= marinPower;
if (zerglingHp <= 0)
{
zerglingHp = 0;
}
per = (float)zerglingHp / zerglingMaxHp * 100f;
Console.WriteLine("{0}이 {1}을 공격({2})했습니다. ({3}/{4}) {5}%", terranMarin, zergZergling, marinPower, zerglingHp, zerglingMaxHp, per);
}
Console.WriteLine("{0}이 죽었습니다.", zergZergling);
//마린이 생성되었습니다.
//공격력 : 2
//체력 : 10
//저글링이 생성되었습니다.
//공격력 : 1
//체력 : 5
//마린이 저글링을 공격(2)했습니다. (3/5) 60%
//마린이 저글링을 공격(2)했습니다. (1/5) 20%
//마린이 저글링을 공격(2)했습니다. (0/5) 0%
//저글링이 죽엇습니다.
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Study01
{
class Program
{
static void Main(string[] args)
{
string mineral = "미네랄";
string gas = "가스";
int mineralAmount = 90;
int gasAmount = 200;
string building = "서플라이디폿";
int buildIncreaseNum = 8;
int buildNeedMineral = 100;
string unit = "SCV";
int unitOnceProduction = 8;
int unitCount = 0;
int unitMaxCount = 10;
Console.WriteLine("{0} : {1}",mineral, mineralAmount);
Console.WriteLine("{0} : {1}",gas, gasAmount);
Console.WriteLine("{0}가 생성되었습니다.", unit);
unitCount++;
Console.WriteLine("인구수 : {0}/{1}", unitCount, unitMaxCount);
Console.WriteLine("{0} 정보", building);
Console.WriteLine("필요 {0} : {1}", mineral, buildNeedMineral);
Console.WriteLine("{0}가 {1}을 건설을 시도합니다", unit, building);
Console.WriteLine("{0}이 부족합니다.", mineral);
Console.WriteLine("{0}가 {1}을 캤습니다. +{2}", unit, mineral, unitOnceProduction);
mineralAmount += unitOnceProduction;
Console.WriteLine("{0} : {1}", mineral, mineralAmount);
Console.WriteLine("{0}가 {1}을 캤습니다. +{2}", unit, mineral, unitOnceProduction);
mineralAmount += unitOnceProduction;
Console.WriteLine("{0} : {1}", mineral, mineralAmount);
Console.WriteLine("{0}가 {1}을 건설을 시도합니다", unit, building);
mineralAmount -= buildNeedMineral;
Console.WriteLine("{0} : {1}", mineral, mineralAmount);
for (int i = 0; i < 100; i++)
{
int bulidProgress = 5;
bulidProgress *= i+1;
Console.WriteLine("{0}가 {1}을 건설합니다. {2}%", unit, building, bulidProgress);
if (bulidProgress == 100)
{
break;
}
}
Console.WriteLine("{0}이 완성 되었습니다.", building);
unitMaxCount += buildIncreaseNum;
Console.WriteLine("인구수 : {0}/{1}", unitCount, unitMaxCount);
//미네랄 : 90
//가스 : 200
//SCV가 생성되었습니다.
//인구수 : 1/10
//서플라이디폿 정보
//필요 미네랄 : 100
//SCV가 서플라이디폿을 건설을 시도 합니다.
//미네랄이 부족합니다.
//SCV가 미네랄을 캤습니다. +8
//미네랄 : 98
//SCV가 미네랄을 캤습니다. +8
//미네랄 : 106
//SCV가 서플라이디폿을 건설을 시도 합니다.
//미네랄 : 6
//SCV가 서플라이디폿을 건설합니다. 5%
//SCV가 서플라이디폿을 건설합니다. 10%
//....
//SCV가 서플라이더폿을 건설합니다. 100%
//서플라이 디폿이 완성 되었습니다.
//인구수 : 1/18
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Study01
{
class Program
{
static void Main(string[] args)
{
string templer = "템플러";
int templerMaxEnergy = 200;
int templerEnergy = 10;
int energyCharge = 10;
string templerSkill = "지짐이";
int skillNeedEnergy = 75;
Console.WriteLine("{0}가 생성되었습니다.", templer);
Console.WriteLine("에너지 {0}/{1}", templerEnergy, templerMaxEnergy);
Console.WriteLine();
Console.WriteLine("{0} {1} 정보", templer, templerSkill);
Console.WriteLine("필요 에너지 : {0}", skillNeedEnergy);
Console.WriteLine();
Console.WriteLine("{0}가 {1}를 시도 합니다.", templer, templerSkill);
Console.WriteLine("에너지가 부족합니다.");
for(int i = 0; ; i++)
{
templerEnergy += energyCharge;
Console.WriteLine("에너지가 충전되었습니다. ({0}/{1})", templerEnergy, templerMaxEnergy);
if(templerEnergy == templerMaxEnergy)
{
break;
}
}
Console.WriteLine();
Console.WriteLine("{0}가 {1}를 시도합니다.", templer, templerSkill);
templerEnergy -= skillNeedEnergy;
Console.WriteLine("{0}가 지졌습니다.", templer);
Console.WriteLine("에너지 ({0}/{1})", templerEnergy, templerMaxEnergy);
}
}
}
'C# > 수업내용' 카테고리의 다른 글
C# 1주차 3일 수업 내용 예제 4번 (21.03.10) (0) | 2021.03.10 |
---|---|
C# 1주차 3일 수업 내용 예제 3번 (21.03.10) (0) | 2021.03.10 |
C# 1주차 3일 수업 내용 예제 2번 (21.03.10) (0) | 2021.03.10 |
C# 1주차 3일 수업 내용 예제 1번 (21.03.10) (0) | 2021.03.10 |
C# 1주차 3일 수업 내용 (21.03.10) (0) | 2021.03.10 |