인프라 활용을 위한 파이썬 #03 실습(Tictactoe 게임)

만두다섯개·2023년 10월 27일
0

SK 루키즈 16기

목록 보기
7/52

1. Tictactoe 게임 (ver_5)

  • 기능 : 2인 플레이 기능, 중복 위치 선택 방지기능
  • Tictactoe 게임 (ver_6) 예정 기능 : 위치 선택 필터링기능(정규식사용), 1인 플레이 기능
# tictacto_V5 기능 : 2인 플레이 기능, 중복 위치 선택 방지기능
the_board = {  # 보드 생성, (딕셔너리)
    'top-L': ' ', 'top-M': ' ', 'top-R': ' ',
    'mid-L': ' ', 'mid-M': ' ', 'mid-R': ' ',
    'low-L': ' ', 'low-M': ' ', 'low-R': ' '
}
def print_board(board):  # tictacto 게임 메인 함수
    top_list = []
    mid_list = []
    low_list = []
    for k, v in board.items():  # board 딕셔너리로부터 키와 값을 받아 top/mid/low 리스트에 추가한다
        if 'top' in k:
            top_list.append(v)
        if 'mid' in k:
            mid_list.append(v)
        if 'low' in k:
            low_list.append(v)
    top_str = '|'.join(top_list)
    mid_str = '|'.join(mid_list)
    low_str = '|'.join(low_list)
    print('-------------------------------------------')
    print('{}\n-+-+-\n{}\n-+-+-\n{}'.format(top_str, mid_str, low_str))
    print('-------------------------------------------')

    # print('{}|{}|{}'.format(*args: board['top-L'] + '|' + board['top-M'] + '|' + board['top-R']))
    # print(board['top-L'] + '|' + board['top-M'] + '|' + board['top-R'])
    # print('-+-+-')
    # print(board['mid-L'] + '|' + board['mid-M'] + '|' + board['mid-R'])
    # print('-+-+-')
    # print(board['low-L'] + '|' + board['low-M'] + '|' + board['low-R'])

turn = 'X'
board_location = list(the_board.keys())  # 보드판의 키 값들로 리스트를 만든다 즉, 키 값 = 보드에서의 위치 ( 0 ~ 8 )
# for i in range(9):
while True:
    if ' ' not in list(the_board.values()):  # 보드판이 꽉 차는 순간 보드판을 출력 후 게임 종료
        print("게임이 종료되었습니다")
        break
    print_board(the_board)
    print("다음 상대의 차례! %s . 어느 위치로 이동하시겠습니까?" % turn)  # X 순서부터 시작한다.
    move = int(input()) - 1  # 입력받은 수 (1~9) - 1 은 이동할 좌표와 동일. move 변수는 이동할 위치
    key_move = board_location[move]
    if the_board[key_move] != ' ':  # 보드판에 이동할 위치가 비어있지 않다면, 해당 위치로 이동 불가. continue로 위에서 다시 수를 입력받아 진행
        print('다시 입력하세요!')
        continue
    the_board[key_move] = turn  # turn : X OR 0 문자열을 보드판의 vlaue 로 넣는다.
    # the_board[move] = turn
    if turn == 'X':
        turn = '0'
    else:
        turn = 'X'

profile
磨斧爲針

0개의 댓글