본문 바로가기
프로그램

[파이썬] 문제 : 공에 숫자와 그림(RED, GREEN,HEART,CLOVER) 게임

by 오디세이99 2023. 4. 4.
728x90
반응형

(문제)

상자에는 숫자와 그림이 그려져 있는 공들이 들어있다.
두 사람이 상자에서 공을 하나씩 꺼낸다.
빨간색 하트가 그려진 공을 꺼내면 공의 숫자*2의 점수를 받는다.
빨간색 클로버가 그려진 공을 꺼내면 0점을 받는다.
초록색 하트가 그려진 공을 꺼내면 공의 숫자-1의 점수를 받는다.
초록색 클로버가 그려진 공을 꺼내면 공의 숫자+2의 점수를 받는다.
점수가 높은 사람이 승리할 때, 두 사람의 승부 결과를 출력하시오.

 

(방법)

- 공에 숫자가 있다고 하는데 이 숫자에 대한 정의가 없어서 임의의 숫자(1~3)로 했습니다.

- RED, GREEN, HEART, CLOVER 등의 문자열 입력에 대한 유효성 체크 등의 코드는 없습니다.

import random

def play(hc, color):                          # hc(HEART, CLOVER)와 color(RED, GREEN)을 함수의 인수로 받음
    score = 0
    ball_no = random.randint(1, 3)             # 공에 적혀있는 숫자. 정의가 없어서 임의의로 1~3까지로 함
    if hc == 'HEART' and color == 'RED':      # 점수 계산
        score = ball_no * 2
    elif hc == 'CLOVER' and color == 'RED':
        player_score = 0
    elif hc == 'HEART' and color == 'GREEN':
        score = ball_no - 1
    elif hc == 'CLOVER' and color == 'GREEN':
        score = ball_no + 1
        
    return score                               # 점수를 봔환


p1_hc = input()                      # input HEART, CLOVER
p1_color = input()                   # input RED, GREEN
p1_score = play(p1_hc, p1_color)     # play() 함수로 점수를 반환 받음
print(p1_score)                      # 점수 출력

p2_hc = input()                      # input HEART, CLOVER
p2_color = input()                    # input RED, GREEN
p2_score = play(p2_hc, p2_color)
print(p2_score)

# player1과 player2의 점수에 따른 승자 출력
if p1_score > p2_score:
    print('player1 win, player2 lose')
elif p1_score < p2_score:
    print('player2 win, player1 lose')

 

처음 문제를 해석을 잘 못해서 RED, GREEN, HEART, CLOVER 등을 컴퓨터가 임의의 선택하도록 하는 코드 입니다.

사용자1와 2는 Enter만 하면 됨.

import random

ball_lst = ['RED HEART', 'RED CLOVER','GREEN HEART', 'GREEN CLOVER']
ball_no = 5

def play(player_name):
    _ = input(player_name + '(Enter): ')
    player_ball = random.randint(0, len(ball_lst)-1)
    player_ball_no = random.randint(1,ball_no)
    player_score = 0
    if player_ball == 0:
        player_score = player_ball_no * 2
    elif player_ball == 1:
        player_score = 0
    elif player_ball == 2:
        player_score = player_ball_no - 1
    elif player_ball == 3:
        player_score = player_ball_no + 1
        
    return player_ball, player_ball_no, player_score


while True:
    player1_ball, player1_ball_no, player1_score = play('player1')
    player2_ball, player2_ball_no, player2_score = play('player2')
    
    print('  >', ball_lst[player1_ball], player1_ball_no, player1_score)
    print('  >', ball_lst[player2_ball], player2_ball_no, player2_score)
    
    if player1_score > player2_score:
        print('player1 win, player2 lose')
    elif player1_score < player2_score:
        print('player2 win, player1 lose')
        
    yn = input('게임 종료(Y/N): ')
    if yn.upper() == 'Y':
        break

728x90
반응형

댓글