Last active
May 20, 2021 00:02
-
-
Save deep-diver/d17f7e4943f18079ebd592a75c152c53 to your computer and use it in GitHub Desktop.
숫자맞추기게임
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 숫자 맞추기 게임 완성본 | |
package main | |
import ( | |
"bufio" | |
"fmt" | |
"math/rand" | |
"os" | |
"time" | |
) | |
// @박박사님 | |
// - 보통 전역으로 함수와 스트럭을 선언하고 메인에서 사용합니다. | |
// - (이거 리시버 일꺼에요 전역 변수도로도 많이 선언해요!) | |
// @내생각 | |
// - 그냥 관용적이긴 한데, 이렇게 안써도 상관은 없을듯? | |
// @권경모 | |
// - stdin 밖으로 뺀건 Reader state 때문에 | |
// - ? -> | |
var stdin = bufio.NewReader(os.Stdin) | |
// error는 데이터 타입 중 하나 (고랭 built-in) | |
/* | |
error 도 데이터 타입 중 하나임. 이름이 아님. | |
- 그러면 error 에 포함된 에러 종류는 어떤게 있나? | |
대충 찾아보니 그냥 interface 임. 그리고 단순히 String 을 담는듯 | |
type error interface { | |
Error() string | |
} | |
// errorString is a trivial implementation of error. | |
type errorString struct { | |
s string | |
} | |
func (e *errorString) Error() string { | |
return e.s | |
} | |
*/ | |
func InputIntValue() (int, error) { | |
var n int | |
// n 이 정수형 이라서 Scanln은 입력 받은것을 정수로 리턴함. 정수형에 어긋날시 err 발생 | |
_, err := fmt.Scanln(&n) | |
if err != nil { | |
// fmt.Scanln 은 \n 이전까지의 문자열을 입력받음 | |
// 마지막에 남은 \n을 제거 해 줘야함 | |
/* | |
책 주석대로라면, 에러 발생 시 입력 스트림을 비움 이라고 되어 있음. | |
- 적당히 설명을 찾아보면, 마지막 줄까지 읽어들이는 행위임 | |
- 그러면 fmt.Scanln 은 \n 까지 읽지 않는 것인가? \n 딱 이전까지만 읽는것인가? 공식문서에 따르면 그런듯 하다. | |
Scanln is similar to Scan, but stops scanning at a newline and after the final item there must be a newline or EOF. | |
- 그래서 마지막 \n 까지 읽어서 깔끔하게 비워버리는듯. | |
- 근데 왜 에러가 발생 했을때만 이 짓을하나? | |
@권경모 | |
fmt.Scanln() 이라 정상이라면 라인 먹고 버립니다. | |
근데 에러나서 라인 엔딩까지 못가고 뻗음 | |
그래서 라인엔딩 섭취해주지 않으면 다음 인풋때 망함 | |
그래서 에러날시 섭취 쩝쩝 | |
https://stackoverflow.com/questions/14640218/how-to-flush-stdin-after-fmt-scanf-in-go | |
*/ | |
stdin.ReadString('\n') | |
} | |
return n, err | |
} | |
func main() { | |
rand.Seed(time.Now().UnixNano()) | |
/* | |
@박박사님 | |
- 보통 최초 선언시 := 를 쓰고 덮어야 할 때 = 사용합니다. | |
= vs := : assignment vs short variable declarations | |
여섯가지 RULE이 존재함. check it out: https://stackoverflow.com/questions/17891226/difference-between-and-operators-in-go/45654233#45654233 | |
https://www.godesignpatterns.com/2014/04/assignment-vs-short-variable-declaration.html | |
*/ | |
r := rand.Intn(100) | |
cnt := 1 | |
for { | |
// fmt.Print 도 있음. | |
// https://golang.org/pkg/fmt/#example_Print | |
fmt.Printf("숫자값을 입력하세요:") | |
n, err := InputIntValue() | |
if err != nil { | |
fmt.Println("숫자만 입력하세요.") | |
} | |
else { | |
if n > r { | |
fmt.Println("입력하신 숫자가 더 큽니다.") | |
} | |
else if n < r { | |
fmt.Println("입력하신 숫자가 더 작습니다.") | |
} | |
else { | |
fmt.Println("숫자를 맞췄습니다. 축하합니다. 시도한 횟수:", cnt) | |
} | |
cnt++ | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment