프로그램
[파이썬] 문제 : if, 반복문,사용자 정의 함수 사용해 게임코드 만들기
오디세이99
2022. 11. 26. 19:08
728x90
반응형
(문제)
1. if문을 2번이상 다르게 포함
2. 반복문으로 2번이상 반복하여 실행
3. 사용자 정의 함수를 포함하고 메인프로그램에서 호출하여 사용
위 3가지 조건을 만족하는 게임 코드
(방법)
import random
game = ['가위','바위','보'] # 리스트 사용
def my_game(m, c): # 승리 판단 함수
rtn = ''
print("컴퓨터 :", c)
if m == c:
print("비겼습니다.")
rtn = 't'
elif m == "가위" and c == "보" or m == '바위' and c == '가위' or m == '보' and c == '바위':
print("당신이 이겼습니다.")
rtn = 'v'
else:
print("컴퓨터가 이겼습니다.")
rtn = 'd'
return rtn
game_cnt = 0 # 게임 횟수
victory_cnt = 0 # 승리 횟수
defeat_cnt = 0 # 패배 횟수
tie_cnt = 0 # 무승부 횟수
game_history = []
while True: # 반복문 사용
my = input("가위 / 바위 / 보 중 하나를 입력하세요(Enter:종료): ") # 입력 받기
if my == '': # 입력이 'endter면 입력이 없기 때문에('') 종료
for i in range(len(game_history)):
if game_history[i] == 'v': # 승리 Count
victory_cnt += 1
elif game_history[i] == 'd': # 패배 Count
defeat_cnt += 1
elif game_history[i] == 't': # 무승부 Count
tie_cnt += 1
print(f"총 게임수:{game_cnt} 승리:{victory_cnt} / 퍠배:{defeat_cnt} / 무승부:{tie_cnt}") # 종료시 게임 현황 출력
break
computer = random.choice(game) # 컴퓨터는 랜덤하게 가위,바위,보 선택
rtn = my_game(my, computer) # 승리 판단 함수 실행
game_history.append(rtn)
game_cnt += 1 # 게임횟수 증가
728x90
반응형