(Python) 숫자 야구 만들기

2022. 5. 6. 18:52·Python

오늘은 강의시간이 비어 남는 시간에 숫자야구를 만들어보았다. 이런 프로그램을 혼자 처음 만들어봐서 완성했을때 뿌듯함도 컸고 나름 재미있었다.
 
다음에는 def와 class를 이용해서 코드를 조금 더 보기 쉽게 보완할 생각이다.
 

# 1 

import random

base_ball = []

strike = 0
ball = 0

# 첫번째 게임이 끝난 후에도 게임이 지속되게 반복
running = True
while running:					
    for i in range(4):
        a = (random.randint(1,9))		# 랜덤수를 a에 저장 후 중복이 아니라면 base_ball 리스트에 저장
        while a in base_ball:
            a = random.randint(1,9)
        base_ball.append(a)

    base_ball = list(map(int,base_ball))

    ans_list = []

    while ans_list != base_ball:		# 수가 같지않다면 (정답이 아니라면) 맞을 때 까지 실행
        count = 1

        ans = input('4자리 수를 입력하세요 :')
        ans_list = list(ans)
        ans_list = list(map(int,ans_list))

        if ans_list[0] in base_ball:
            if ans_list[0] == base_ball[0]:
                strike += 1				# 스트라이크와 볼의 개수를 증가시켜 변수에 저장
            else :
                ball += 1

        if ans_list[1] in base_ball:
            if ans_list[1] == base_ball[1]:
                strike += 1
            else :
                ball += 1

        if ans_list[2] in base_ball:
            if ans_list[2] == base_ball[2]:
                strike += 1
            else :
                ball += 1

        if ans_list[3] in base_ball:
            if ans_list[3] == base_ball[3]:
                strike += 1
            else :
                ball += 1
                
        if count > 10:
        	print('10번안에 맞추지 못했습니다 게임을 종료합니다.')
        	running = False 	# 10번 안에 맞추지 못할 경우 게임을 종료함

        print(f'strike : {strike}, ball : {ball}')
        strike = 0		# 스트라이크와 볼의 개수가 계속 저장되면 다음에도 이어서 출력되기 때문에 초기화
        ball = 0
        count += 1
    
    if ans_list == base_ball:
        print(f'축하합니다! {count}번 만에 맞췄습니다')

+ 추가
 
집에 오는길에 다시 한번 코드를 살펴보니 if 절이 계속 반복되고 있는 것을 볼 수 있었다. 그래서 for 문으로 묶어 한 번에 처리할 수 있도록 보완했다.
 

import random

base_ball = []

strike = 0
ball = 0
out = 0

while True:
    for i in range(4):
        a = (random.randint(1,9))
        while a in base_ball:
            a = random.randint(1,9)
        base_ball.append(a)

    base_ball = list(map(int,base_ball))

    ans_list = []

    while ans_list != base_ball:
        count = 1

        ans = input('4자리 수를 입력하세요 :')
        ans_list = list(ans)
        ans_list = list(map(int,ans_list))

        for i in range (0,4):				# 코드 변경 부분
            if ans_list[i] in base_ball:
                if ans_list[i] == base_ball[i]:
                    strike += 1
                else :
                    ball += 1

        i += 1

        print(f'strike : {strike}, ball : {ball}, out : {out}')
        strike = 0
        ball = 0
        count += 1
    
    if ans_list == base_ball:
        print(f'축하합니다! {count}번 만에 맞췄습니다')
반응형
저작자표시 (새창열림)

'Python' 카테고리의 다른 글

(Python) def 를 이용한 함수 생성  (0) 2022.05.15
(Python) 숫자 up & down 게임  (0) 2022.05.07
(Python) if 를 이용한 조건문  (0) 2022.05.04
(Python) While()을 이용한 반복문  (0) 2022.04.26
(Python) 리스트 할당  (0) 2022.04.19
'Python' 카테고리의 다른 글
  • (Python) def 를 이용한 함수 생성
  • (Python) 숫자 up & down 게임
  • (Python) if 를 이용한 조건문
  • (Python) While()을 이용한 반복문
re-hwi
re-hwi
재휘의 개발일기
    반응형
  • re-hwi
    Dvelopment blog
    re-hwi
  • 전체
    오늘
    어제
    • 재휘의 개발일기 (168) N
      • 개발 (1) N
        • 소프트웨어 공학 (25)
      • Python (18)
        • numpy (8)
      • OS (23)
        • 쉽게 배우는 운영체제 (23)
      • Front end (1)
        • HTML (6)
        • CSS (9)
        • JavaScript (18)
        • React (2)
        • Vue.js (5)
        • TypeScript (5)
        • Sass (3)
      • Algorithm (1)
        • 파이썬 알고리즘 인터뷰 (2)
        • 자료구조와 함께 배우는 알고리즘 (20)
      • Android (2)
        • 안드로이드 앱 프로그래밍 with 코틀린 (2)
      • Project (15)
      • Network (0)
      • etc (12)
        • 이것저것 (10)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    리액트
    자료흐름도
    연결리스트
    HTML
    FE
    정처기
    뷰
    파이썬
    js
    프론트엔드
    numpy
    티스토리챌린지
    컴포넌트
    자료구조
    플레이리스트
    vue
    sass
    알고리즘
    정보처리기사
    pwa
    타입스크립트
    scss
    오블완
    표
    REACT
    TS
    typeScript
    CSS
    개발
    JavaScript
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
re-hwi
(Python) 숫자 야구 만들기
상단으로

티스토리툴바