코딩도장

tic-tac-toe game

아마존 본사 입사 문제였습니다.

tic-tac-toe는 두 명의 플레이어가 턴을 돌아가면서 1부터 9까지 포지션을 선택하는 게임 입니다. 선택된 포지션은 X나 0로 표시가 되며, 선택된 포지션은 다시 선택할 수가 없습니다. 게임 그리드는 3*3으로 다음과 같습니다.


 * * 
 1 * 2 * 3 
 * * 
 * * 
 4 * 5 * 6 
 * * 
 * * 
 7 * 8 * 9 
 * *

가로 세로 대각선으로 먼저 세 줄을 연속으로 만드는 플레이어가 우승하게 되며 무승부인 경우도 생깁니다. (매 턴마다 포지션을 입력해야 하지만, 출력은 게임이 끝이 났을 때만 하셔도 됩니다)

입력의 예:


Player 1 - please type a position (available position(s) are 1,2,3,4,5,6,7,8,9):


출력의 예:


 * * 
 X * X * 0 
 * * 
 * * 
 X * 0 * 6 
 * * 
 * * 
 X * 8 * 9 
 * *

Win playear is: player 1


sort
(追記) (追記ここまで)
댓글 작성은 로그인이 필요합니다.
이거 빙고게임이라고 생각하면 되나요? - 김 한길, 2014年12月05日 22:58 M D
네 ᄒ 3*3 빙고게임이라고 생각하시면 됩니다. - Straß Böhm Jäger, 2015年05月15日 08:06 M D
(注記) 상대에게 상처를 주기보다 서로에게 도움이 될 수 있는 댓글을 달아 주세요.

22개의 풀이가 있습니다. 1 / 3 Page

# 포지션 변경 함수
def change (arr,n,k):
 k_arr={1:'X',2:'O'}
 s =k_arr[k]
 if n ==1: arr[1][0] = s
 elif n==2 : arr[1][4] = s
 elif n==3 : arr[1][8] = s
 elif n==4 : arr[4][0] = s
 elif n==5 : arr[4][4] = s
 elif n==6 : arr[4][8] = s
 elif n==7 : arr[7][0] = s
 elif n==8 : arr[7][4] = s
 else : arr[7][8] = s
 return arr
#빙고 판단 함수
def judge(arr):
 if arr[1][0] == arr[1][4] == arr[1][8] or \
 arr[4][0] == arr[4][4] == arr[4][8] or \
 arr[7][0] == arr[7][4] == arr[7][8] or \
 arr[1][0] == arr[4][0] == arr[7][0] or \
 arr[1][4] == arr[4][4] == arr[7][4] or \
 arr[1][8] == arr[4][8] == arr[7][8] or \
 arr[1][0] == arr[4][4] == arr[7][8] or \
 arr[7][0] == arr[4][4] == arr[1][8] :
 return False
 else:
 return True
# positin 배열 출력 함수
def print_p (arr):
 for k in arr:
 for i in k:
 print(i,end='')
 print('')
#game의 초기 포지션 배열
game = [[' '*2,'*',' '*3,'*',' '*2],[1,' ','*',' ',2,' ','*',' ',3],\
 [' '*2,'*',' '*3,'*',' '*2],[' '*2,'*',' '*3,'*',' '*2],\
 [4,' ','*',' ',5,' ','*',' ',6],[' '*2,'*',' '*3,'*',' '*2],\
 [' '*2,'*',' '*3,'*',' '*2],[7,' ','*',' ',8,' ','*',' ',9],\
 [' '*2,'*',' '*3,'*',' '*2]]
position=[i for i in range(1,10)]
p={1:1,-1:2} # player를 번갈아 가며 진행하기위해 key vlaue로 순환 반복
k=-1
while True:
 k*=-1
 print('Player',p[k],'- please type a position (available position(s) are',position)
 while True:
 n = int(input())
 if n in position:
 break
 game = change(game,n,p[k])
 position.remove(n)
 print_p(game)
 if judge(game) == False:
 print('Win player is: player',p[k])
 break

재밌네요~ 코드가 길지만 2차원 배열과 키 밸류를 이용해서 플레이어가 번갈아가며 진행할수 있도록 해봤어요~ position 배열은 따로둬서, 각 포지션을 고를떄마다 position 배열에서 remove 해서 중복 선택 못하도록 했습니다

2022年02月23日 20:53

양캠부부

댓글 작성은 로그인이 필요합니다.
(注記) 상대에게 상처를 주기보다 서로에게 도움이 될 수 있는 댓글을 달아 주세요.
board = [['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]
for i in board:
 print(' | '.join(i))
selected = []
for i in range(1, 10):
 if i%2 == 1:
 symbol = 'O' # 1번 플레이어는 O 마크 사용
 else:
 symbol = 'X'
 p = int(input(symbol + '의 위치를 선택하세요: ')) - 1
 while p in selected:
 p = int(input(symbol + '의 다른 위치를 선택하세요: ')) - 1
 selected.append(p)
 y, x = p//3, p%3 # 선택 위치는 한 행당 3개씩 있기 때문에 3으로 나눈 몫이 행, 나머지는 열
 board[y][x] = symbol
 for ii in board:
 print(' | '.join(ii))
 tmpy = set()
 tmpx = set()
 for ip in range(3): # 선택된 행과 열의 값이 같은지 확인
 tmpy.add(board[ip][x])
 tmpx.add(board[y][ip])
 if len(tmpy) == 1 or len(tmpx) == 1:
 print(symbol, 'WIN !!!')
 break
 if len(selected) == 9:
 print('DRAW GAME')
 break
댓글 작성은 로그인이 필요합니다.
(注記) 상대에게 상처를 주기보다 서로에게 도움이 될 수 있는 댓글을 달아 주세요.
import numpy as np
import random
data = np.array([[1,2,3],[4,5,6],[7,8,9]])
def trans():
 a = int(input("선택할 숫자 입력 : "))
 if a-3>3 :
 a-=7
 b=2
 elif a-3>=1:
 a-=4
 b=1
 elif a-3<=0:
 a-=1
 b=0
 if data[b][a] == 10 or data[b][a] ==11 :
 print("선택된 공간입니다")
 trans()
 else:
 data[b][a] = 10
 #print(data)
def com():
 while True:
 c = random.randint(0,2)
 d = random.randint(0,2)
 if data[d][c] == 10 or data[d][c] == 11 :
 print("이미 선택된 공간입니다")
 else:
 data[d][c] = 11
 break
def tic():
 while True:
 com()
 if data[0][0]==10 and data[0][1]==10 and data[0][2]==10:
 print("이겼습니다!")
 w=1
 break
 elif data[1][0]==10 and data[1][1]==10 and data[1][2]==10:
 print("이겼습니다!")
 w=1
 break
 elif data[2][0]==10 and data[2][1]==10 and data[2][2]==10:
 print("이겼습니다")
 w=1
 break
 elif data[0][0]==10 and data[1][0]==10 and data[2][0]==10:
 print("이겼습니다")
 w=1
 break
 elif data[0][1]==10 and data[1][1]==10 and data[2][1]==10:
 print("이겼습니다")
 w=1
 break
 elif data[0][2]==10 and data[1][2]==10 and data[2][2]==10:
 print('이겼습니다')
 w=1
 break
 elif data[0][0]==10 and data[1][1]==10 and data[2][2]==10:
 print("이겼습니다")
 w=1
 break
 elif data[0][2]==10 and data[1][1]==10 and data[2][0]==10:
 print("이겼습니다")
 w=1
 break
 if data[0][0]==11 and data[0][1]==11 and data[0][2]==11:
 print("졌습니다!")
 w=1
 break
 elif data[1][0]==11 and data[1][1]==11 and data[1][2]==11:
 print("졌습니다!")
 w=1
 break
 elif data[2][0]==11 and data[2][1]==11 and data[2][2]==11:
 print("졌습니다")
 w=1
 break
 elif data[0][0]==11 and data[1][0]==11 and data[2][0]==11:
 print("졌습니다")
 w=1
 break
 elif data[0][1]==11 and data[1][1]==11 and data[2][1]==11:
 print("졌습니다")
 w=1
 break
 elif data[0][2]==11 and data[1][1]==11 and data[2][0]==11:
 print('졌습니다')
 w=1
 break
 elif data[0][0]==11 and data[1][1]==11 and data[2][2]==11:
 print("졌습니다")
 w=1
 break
 elif data[0][2]==11 and data[1][1]==11 and data[2][0]==11:
 print("졌습니다")
 w=1
 break
 print(data)
 trans()
tic()

지저분..

2021年04月12日 18:55

fox.j

댓글 작성은 로그인이 필요합니다.
(注記) 상대에게 상처를 주기보다 서로에게 도움이 될 수 있는 댓글을 달아 주세요.
grid=[["1","|","2","|","3"],["4","|","5","|","6"],["7","|","8","|","9"]]
for lst in grid:
 for cpn in lst:
 print("%2s"%cpn, end="")
 print()
nlst=[1,2,3,4,5,6,7,8,9]
def chngnum(num):
 global n
 if n==1:
 p1="O"
 else:
 p1="X"
 if num>0 and num<=3:
 grid[0][grid[0].index(str(num))]=p1
 elif num>3 and num<=6:
 grid[1][grid[1].index(str(num))]=p1
 else:
 grid[2][grid[2].index(str(num))]=p1
def decision():
 for i in range(3):
 if grid[0][i*2]==grid[1][i*2]==grid[2][i*2]:
 return grid[0][i*2]
 if grid[i][0]==grid[i][2]==grid[i][4]:
 return grid[i][0]
 if grid[0][0]==grid[1][2]==grid[2][4] or grid[0][4]==grid[1][2]==grid[2][0]:
 return grid[1][2]
n=1
while True:
 inp=input("Player %s - please type a position(available position(s) are "%n+str(",".join(list(map(str,nlst)))+": "))
 if int(inp) not in nlst:
 print("choose wrong position try another one")
 continue
 nlst.remove(int(inp))
 chngnum(int(inp))
 for lst in grid:
 for cpn in lst:
 print("%2s"%cpn, end="")
 print()
 if nlst==[]:
 print("Draw")
 break
 elif decision()=="O":
 print("Player1 Win!!!")
 break
 elif decision()=="X":
 print("Player2 Win!!!")
 break
 if n==2:
 n=1
 else:
 n+=1

2020年03月01日 16:53

박시원

댓글 작성은 로그인이 필요합니다.
(注記) 상대에게 상처를 주기보다 서로에게 도움이 될 수 있는 댓글을 달아 주세요.

파이썬 3입니다.

A = list(range(1, 10))
def grid(li):
 for i in range(9):
 if (i - 1) % 3 == 0:
 print(3 * ' ', li[i - 1], 3 * ' ', '*', 3 * ' ', li[i], 3 * ' ', '*', 3 * ' ', li[i + 1], 3 * ' ', sep='')
 else:
 print(7 * ' ', '*', 7 * ' ', '*', 7 * ' ', sep='')
def victory_cond(x, li):
 return [li[0], li[1], li[2]] == 3 * [x] or [li[3], li[4], li[5]] == 3 * [x] or \
 [li[6], li[7], li[8]] == 3 * [x] or [li[0], li[3], li[6]] == 3 * [x] or \
 [li[1], li[4], li[7]] == 3 * [x] or [li[2], li[5], li[8]] == 3 * [x] or \
 [li[0], li[4], li[8]] == 3 * [x] or [li[2], li[4], li[6]] == 3 * [x]
def draw_cond(x, y, li):
 temp = list(map(lambda z: x if type(z) == int else z, li))
 d = not victory_cond(x, temp)
 temp = list(map(lambda z: y if type(z) == int else z, li))
 d &= not victory_cond(y, temp)
 return d
def avail(li):
 temp = []
 for n in li:
 if type(n) == int:
 temp.append(n)
 return str(temp).strip('[]')
grid(A)
player = 1
while True:
 if victory_cond('X', A) or victory_cond('O', A):
 print('The winner is: Player {}'.format(1 * victory_cond('X', A) + 2 * victory_cond('O', A)))
 break
 if draw_cond('X', 'O', A):
 print('DRAW!!')
 break
 i = int(input('Player {} - please type a position (available position(s) are {}): '.format(player, avail(A)))) - 1
 if type(A[i]) == str:
 print('\nPLEASE TYPE AN AVAILABLE POSITION\n')
 continue
 A[i] = 'X' * (player == 1) + 'O' * (player == 2)
 player = 3 - player
 print()
 grid(A)

2020年01月31日 19:21

우재용

댓글 작성은 로그인이 필요합니다.
(注記) 상대에게 상처를 주기보다 서로에게 도움이 될 수 있는 댓글을 달아 주세요.

살짝 최적화

turn=1
notvalid=0
p=[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
board=[1, 2, 3, 4, 5, 6, 7, 8, 9]
def winner():
 if str(p[0][0]) == str(p[1][1]) == str(p[2][2]) or str(p[2][0]) == str(p[1][1]) == str(p[0][2]):
 return str(p[1][1])
 for i in range(3):
 if str(p[0][i]) == str(p[1][i]) == str(p[2][i]):
 return str(p[0][i])
 if str(p[i][0]) == str(p[i][1]) == str(p[i][2]):
 return str(p[i][0])
print(" >>> Tic-tac-toe 대각선/가로/세로 줄을 완성하면 승리합니다. <<<")
while True:
 print (" "+str(p[0][0])+" | "+str(p[0][1])+" | "+str(p[0][2]))
 print (" "+str(p[1][0])+" | "+str(p[1][1])+" | "+str(p[1][2]))
 print (" "+str(p[2][0])+" | "+str(p[2][1])+" | "+str(p[2][2]))
 print ("")
 try:
 n=int(input("Player %d - Please type a position (available position(s) are " % turn+ ", ".join(map(str, board)) +" ): "))
 board.remove(n)
 except ValueError:
 print("Not Valid Number!")
 notvalid=1
 if notvalid==0:
 a=n//3
 b=n-a*3-1
 if b==-1:
 a-=1
 b=2
 if turn==1:
 p[a][b] = "o"
 if turn==2:
 p[a][b] = "x"
 turn += 1
 if turn == 3:
 turn = 1
 if winner() == 'o':
 print(">> Player 1 Won!")
 break;
 if winner() == 'x':
 print(">> Player 2 Won!")
 break;
 if board==[]:
 print(">> Draw!")
 break;
 else:
 notvalid=0
print (" "+str(p[0][0])+" | "+str(p[0][1])+" | "+str(p[0][2]))
print (" "+str(p[1][0])+" | "+str(p[1][1])+" | "+str(p[1][2]))
print (" "+str(p[2][0])+" | "+str(p[2][1])+" | "+str(p[2][2]))
print ("")
댓글 작성은 로그인이 필요합니다.
(注記) 상대에게 상처를 주기보다 서로에게 도움이 될 수 있는 댓글을 달아 주세요.
board = ['1','2','3','4','5','6','7','8','9']
state = {'x':'1Player','o':'2Player'}
def printboard():
 print('*'*13)
 for i in range(3):
 print('* {0} * {1} * {2} *'.format(board[i*3],board[i*3+1],board[i*3+2]))
 print('*'*13)
def detGame(board):
 ##가로 확인
 for j in range(3):
 if board[j*3] == board[j*3+1] == board[j*3+2]:
 return [j*3,j*3+1,j*3+2]
 ##세로 확인
 for k in range(3):
 if board[k] == board[3+k] == board[6+k]:
 return [k,3+k,6+k]
 ##대각선 확인
 if board[0] == board[4] == board[8]:
 return [0,4,8]
 if board[2] == board[4] == board[6]:
 return [2,4,6]
 return 0
def playgame():
 _round=0
 _turn=1
 sign='1'
 printboard()
 while _round != 9:
 n = input()
 if _turn%2 == 0:
 sign = 'o'
 else:
 sign = 'x'
 board[board.index(str(n))] = sign
 _turn+=1
 _round+=1
 ##여기에 승패 판단
 cur_state = detGame(board)
 if cur_state:
 printboard()
 print("{0} win~!".format(state[board[cur_state[0]]]))
 return
 print('='*13+'\n')
 printboard()
playgame()

2018年09月20日 23:13

JaehakChoi

댓글 작성은 로그인이 필요합니다.
(注記) 상대에게 상처를 주기보다 서로에게 도움이 될 수 있는 댓글을 달아 주세요.
def bingo(occupied):
 lines = [{'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'}, \
 {'1', '4', '7'}, {'2', '5', '8'}, {'3', '6', '9'}, \
 {'1', '5', '9'}, {'3', '5', '7'}]
 return [line - occupied == {} for line in lines].count(True) >= 3
def print_status(available, occupied):
 for pos in '123456789':
 if pos in available: print(' ' + pos + ' ', end = '')
 elif pos in occupied['X']: print(' X ', end = '')
 else: print(' O ', end = '')
 if pos in '369': print()
available, occupied = set('123456789'), {'X':set(), 'O':set()}
player = 'X'
while available:
 pos = input('Player ' + player + ' - please type a position(available position(s) are ' + ' '.join(sorted(available)) + ') ')
 if pos not in available:
 continue
 occupied[player].add(pos)
 available.remove(pos)
 print_status(available, occupied)
 if bingo(occupied[player]):
 print('winner is ' + player)
 exit()
 player = {'O':'X', 'X':'O'}[player]

2018年08月14日 00:48

Noname

댓글 작성은 로그인이 필요합니다.
(注記) 상대에게 상처를 주기보다 서로에게 도움이 될 수 있는 댓글을 달아 주세요.
def win_di(x):
 y = set(x)
 for i in range(3):
 if set(range(i+1,10,3)) <= y: return True
 for i in range(3):
 if set(range(i*3+1,i*3+1+3)) <= y: return True
 if set(range(1,10,4)) <= y or set(range(3,8,2)) <= y: return True
 return False
p, position = 1, [[],[]]
while 1:
 print('Player {} - please type a position (available position(s) are {}): '.format(p,', '.join(str(i) for i in set(range(1,10))-set(position[0]+position[1]))),end='')
 n = int(input())
 if n in position[0]+position[1]: print('이미 선택된 번호입니다. 다시 입력하세요.'); continue
 position[p%2].append(n)
 if win_di(position[p%2]): print('Winner player is Player {}'.format(p)); break
 if len(position[0]+position[1]) == 9: print('Draw')
 p = 2 if (p+1)%2 == 0 else 1
for i in range(3):
 for j in range(3):
 print('{}'.format('O' if i*3+j+1 in position[0] else 'X' if i*3+j+1 in position[1] else i*3+j+1),end='')
 print()
Player 1 - please type a position (available position(s) are 1, 2, 3, 4, 5, 6, 7, 8, 9): 1
Player 2 - please type a position (available position(s) are 2, 3, 4, 5, 6, 7, 8, 9): 2
Player 1 - please type a position (available position(s) are 3, 4, 5, 6, 7, 8, 9): 3
Player 2 - please type a position (available position(s) are 4, 5, 6, 7, 8, 9): 4
Player 1 - please type a position (available position(s) are 5, 6, 7, 8, 9): 5
Player 2 - please type a position (available position(s) are 8, 9, 6, 7): 6
Player 1 - please type a position (available position(s) are 8, 9, 7): 7
Winner player is Player 1
XOX
OXO
X89
댓글 작성은 로그인이 필요합니다.
(注記) 상대에게 상처를 주기보다 서로에게 도움이 될 수 있는 댓글을 달아 주세요.

Python 굉장히 지저분한 코드군요..

def checkBingo(mat):
 #row
 cnt = 0
 for x in range(0, 9, 3):
 if mat[x] == mat[x+1] == mat[x+2] == 1:
 cnt += 1
 for x in range(3):
 if mat[x] == mat[x+3] == mat[x+6] == 1:
 cnt += 1
 if mat[0] == mat[4] == mat[8]:
 cnt += 1
 if mat[2] == mat[4] == mat[6]:
 cnt += 1
 return cnt
player1 = [0 for _ in range(9)]
player2 = [0 for _ in range(9)]
output = [i+1 for i in range(9)]
isEnd = False
cnt = 0
ava = [i+1 for i in range(9)]
while isEnd is False:
 number = cnt % 2
 pos = int(input("Player {} - please type a position (available position(s) are {}): ".\
 format(number, ','.join(map(str, ava)))))
 ava.pop(ava.index(pos))
 cnt += 1
 player1[pos-1] = 1
 player2[pos-1] = 1
 p1_b = checkBingo(player1)
 p2_b = checkBingo(player2)
 output[pos-1] = "O" if number == 0 else "X"
 if p1_b == 3 and p2_b == 3:
 print("Draw!!")
 break
 elif p1_b == 3 and p2_b < 3:
 print("Win player is: player0")
 break
 elif p2_b == 3 and p1_b < 3:
 print("Win player is: player1")
 break
for i in range(9):
 if i in [1, 4, 7]:
 print("*".join(map(str,output[i-1:i+2])))
 else:
 print(" * * ")

2018年07月01日 14:33

Taesoo Kim

댓글 작성은 로그인이 필요합니다.
(注記) 상대에게 상처를 주기보다 서로에게 도움이 될 수 있는 댓글을 달아 주세요.

풀이 작성

(注記) 풀이작성 안내
  • 본문에 코드를 삽입할 경우 에디터 우측 상단의 "코드삽입" 버튼을 이용 해 주세요.
  • 마크다운 문법으로 본문을 작성 해 주세요.
  • 풀이를 읽는 사람들을 위하여 풀이에 대한 설명도 부탁드려요. (아이디어나 사용한 알고리즘 또는 참고한 자료등)
  • 작성한 풀이는 다른 사람(빨간띠 이상)에 의해서 내용이 개선될 수 있습니다.
풀이 작성은 로그인이 필요합니다.
목록으로
코딩도장

코딩도장은 프로그래밍 문제풀이를 통해서 코딩 실력을 수련(Practice)하는 곳입니다.

sort x 2
연관 문제
김규태, 2026年01月05日 18:41

언어별 풀이 현황
전 체 x 37
cs x 3
java x 2
python x 22
scala x 2
haskell x 1
기 타 x 3
cpp x 3
ruby x 1
코딩도장 © 2014 · 문의 [email protected]
피드백 · 개인정보취급방침 · RSS

AltStyle によって変換されたページ (->オリジナル) /