코딩도장

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

class Tictactoe:
 casetowin = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (0, 3, 6), (1, 4, 7), (2, 5, 8), (0, 4, 8), (2, 4, 6))
 def __init__(self):
 self.board = list(range(1, 10))
 self.available = list(range(1, 10))
 self.winner = 0
 self.phase = 1
 def __str__(self):
 string = ''
 for i in range(3):
 row = self.board[i * 3:i * 3 + 3]
 string += '\t\t*\t\t*\t\n\t{0[0]}\t*\t{0[1]}\t*\t{0[2]}\n\t\t*\t\t*\t\n'.format(row)
 return string
 def move(self, x):
 self.board[x - 1] = 'O' if self.phase == 1 else 'X'
 self.available.remove(x)
 self.winner = self.checkcase()
 self.phase = 2 if self.phase == 1 else 1
 def checkcase(self):
 caselist = []
 for case in self.casetowin:
 caselist = [self.board[x] for x in case]
 if caselist.count('O') == 3:
 return 1
 elif caselist.count('X') == 3:
 return 2
 else:
 continue
 return 0
if __name__ == '__main__':
 t = Tictactoe()
 while t.winner == 0 and len(t.available) != 0:
 move = 0
 print('\n' + str(t))
 string = 'Player {0} - Please type a position (available position(s) are {1}): ' \
 .format(t.phase, ','.join([str(x) for x in t.available]))
 while move not in t.available:
 try:
 move = int(input(string))
 if move not in t.available: raise TypeError
 except:
 print('Please try again. ', end='')
 t.move(move)
 else:
 print(t)
 if t.winner > 0:
 print('The winner is: Player ' + str(t.winner))
 else:
 print('The game ended up in a tie')

2014年12月09日 01:46

투플러스

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

python 3.4

#화면 출력
def show(map):
 mapPosion = [7,9,11,
 25,27,29,
 43,45,47]
 for i in range(1,55):
 count = 0
 ch1 = '\n' if i%6==0 else ' * '
 ch2 = ' '+map[mapPosion.index(i)] if i in mapPosion else ' '
 ch3 = ch1 if i%2==0 else ch2
 print(ch3,end='')
#값 입력
def inValue(player,map):
 piece = 'O' if player == 1 else 'X'
 strNo = input('\nplayer%s(%s)\n원하는 위치를 입력해 주세요.: ' % (player,piece))
 result = 0
 if strNo in map:
 if map[int(strNo)-1] in ('O','x'):
 print('\n!!!!! 그 자리에는 넣을 수 없습니다. !!!!!\n')
 else:
 index = int(strNo)-1
 map[index] = piece
 result = int(strNo)
 else:
 print('\n!!!!!유요한 값이 아닙니다.!!!!!\n')
 return int(result)
#조건체크
def check(player,map):
 w,h = 3,3
 name = 'player1' if player == 1 else 'player2'
 check = 0
 #가로
 for i in range(w-1,(w*h),w):
 check += (map[i] == map[i-1] and map[i] == map[i-2])
 #세로
 for i in range(w):
 check += (map[i] == map[i+w] and map[i] == map[i+(w*2)])
 #대각선 \
 check += map[0] == map[w+1] and map[0] == map[(w+1)*2]
 #대각선 /
 check += map[w-1] == map[(w-1)*2] and map[w-1] == map[(w-1)*3]
 #무승부
 if check:
 print('\n%s 승리!!!\n' % name)
 else:
 count = 0 
 for i in map:
 count += (not i.isdigit())
 if count == len(map):
 print('\n무승부!!!\n')
 check = 1
 return check
def main():
 #필드
 map = ['1','2','3',
 '4','5','6',
 '7','8','9']
 player = 1
 while 1:
 show(map)
 if inValue(player,map):
 if check(player,map):
 break;
 player = player * (-1)
main()

2015年01月16日 14:56

eunpyo

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

coding by python beginner

board = [['1','2','3'],['4','5','6'],['7','8','9']]
symbol = ['X', 'O']
player = 1
def chkWin(): 
 if board[0][0] == board[1][1] and board[1][1] == board[2][2]:
 return board[0][0] 
 elif board[0][2] == board[1][1] and board[1][1] == board[2][0]:
 return board[0][2]
 else:
 for i in range(len(board)): 
 if len(list(set([board[0][i],board[1][i], board[2][i]]))) == 1:
 return board[0][i]
 elif len(list(set([board[i][0], board[i][1], board[i][2]]))) == 1:
 return board[i][0]
 return False
def printBoard():
 print('-' * 7) 
 for t in board:
 print('|' + '|'.join(t) + '|') 
 print('-' * 7)
def tic(player, idx): 
 board[int((idx-1) / 3)][(idx-1) % 3] = symbol[player-1]
 printBoard()
 if chkWin() != False:
 print('Win playear is: player %s' % player)
 return False
 return True
def play(player):
 remainPos = ''
 for arr in board:
 for pos in arr:
 if pos not in symbol:
 remainPos += pos 
 if remainPos == '':
 print('Game is draw.')
 return False
 else: 
 print('Player %d - please type a position \
(available position(s) are %s):' % (player, ','.join(list(remainPos))))
 pos = int(input())
 if remainPos.find(str(pos)) == -1:
 print('Not available position.')
 return play(player)
 else:
 return tic(player, pos)
printBoard()
while True:
 player ^= 1
 if play(player + 1) == False: break

2015年01月30日 16:39

vegan

댓글 작성은 로그인이 필요합니다.
(注記) 상대에게 상처를 주기보다 서로에게 도움이 될 수 있는 댓글을 달아 주세요.
pinkey = 0
board = [['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]
def keyreplacer(strnum, pl):
 for x in board:
 for xx in range(0, len(x)):
 if x[xx] == strnum and pl == 1:
 x[xx] = 'X'
 elif x[xx] == strnum and pl == 2:
 x[xx] = 'O'
def winident():
 for v in board:
 if v == ['X', 'X', 'X']:
 print("Player 1 won!")
 return 1
 break
 elif v == ['O', 'O', 'O']:
 print("Player 2 won!")
 return 1
 break
 elif board[1][1] == 'X':
 if (board[0][0] == 'X' and board[2][2] == 'X') or (board[0][2] == 'X' and board[2][0] == 'X'):
 print("Player 1 won!")
 return 1
 break
 elif board[1][1] == 'O':
 if (board[0][0] == 'O' and board[2][2] == 'O') or (board[0][2] == 'O' and board[2][0] == 'O'):
 print("Player 2 won!")
 return 1
 break
 else:
 return 0
 break
def showboard():
 print(" * * ")
 print(" ", board[0][0], " *", " ", board[0][1], " * ", " ", board[0][2], " ", sep = "")
 print(" * * ")
 print(" * * ")
 print(" ", board[1][0], " *", " ", board[1][1], " * ", " ", board[1][2], " ", sep = "")
 print(" * * ")
 print(" * * ")
 print(" ", board[2][0], " *", " ", board[2][1], " * ", " ", board[2][2], " ", sep = "")
 print(" * * ") 
print("Let\'s play a tix-tac-toe game!\neach turn, each player can choose a number between 1 and 9.\n")
for i in range(0, 9):
 if i%3 != 1:
 print(" * * ")
 else:
 print(" ", i, " *", " ", i+1, " * ", " ", i+2, " ", sep = "")
i = 0
while(pinkey == 0):
 display = []
 for lv1 in board:
 if type(lv1) is not list and lv1 != 'X' and lv1 != 'O':
 display.append(lv1)
 elif type(lv1) is list:
 for lv2 in lv1:
 if lv2 != 'X' and lv2 != 'O':
 display.append(lv2)
 print("Current available position(s) is(are): ", ", ".join(display))
 pl1insert = input("Player 1 - please type a position: ")
 keyreplacer(pl1insert, 1)
 if winident() == 1:
 showboard()
 pinkey = 1
 break
 display = []
 for lv1 in board:
 if type(lv1) is not list and lv1 != 'X' and lv1 != 'O':
 display.append(lv1)
 elif type(lv1) is list:
 for lv2 in lv1:
 if lv2 != 'X' and lv2 != 'O':
 display.append(lv2)
 print("Current available position(s) is(are): ", ", ".join(display))
 pl2insert = input("Player 2 - please type a position: ")
 keyreplacer(pl2insert, 2)
 if winident() == 1:
 showboard()
 pinkey = 1
 break

3x3 틱택토로 구성되어 있고, 플레이어 1이 찍은 자리는 'X', 플레이어 2가 찍은 자리는 'O'로 표기하도록 하였습니다.

2015年10月13日 20:05

박재우

댓글 작성은 로그인이 필요합니다.
(注記) 상대에게 상처를 주기보다 서로에게 도움이 될 수 있는 댓글을 달아 주세요.
import sys
def display(ttt):
 s=' '
 empty_line = s*5+'*'+s*9+'*'
 for i in range(3):
 print empty_line
 print ttt[i*3+1]+s*4+'*'+s*4+ttt[i*3+2]+s*4+'*'+s*4+ttt[i*3+3]
 print empty_line
ttt=map(str,range(10)) #tic tac toe plate
display(ttt)
while True:
 for player,mark in [('Player 1','O'),('Player 2','X')]:
 available = [int(e) for e in ttt if e.isdigit() and e!='0']
 if not available :
 print 'Tie game'
 sys.exit()
 print player, '- please type a position(available position(s)are ',available,'):',
 i = input()
 while not i in available :
 print "wrong selection. type again : ",
 i = input()
 ttt[i] = mark
 display(ttt)
 marks = set([])
 for i in range(1,10):
 if ttt[i]==mark: marks.add(i)
 for s in [{1,2,3},{4,5,6},{7,8,9},{1,4,7},{2,5,8},{3,6,9},{1,5,9},{7,5,3}]:
 if s<=marks :
 print 'winning player is',player
 sys.exit()

2016年01月29日 17:08

상파

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

승패판정을 정규식검사로 처리해봤습니다.

import re
win1 = """OOO...... ...OOO... ......OOO O..O..O.. .O..O..O. ..O..O..O O...O...O ..O.O.O..""".split()
win2 = """XXX...... ...XXX... ......XXX X..X..X.. .X..X..X. ..X..X..X X...X...X ..X.X.X..""".split()
def print_grid(data):
 print(('\n' + '-' * 9 + '\n').join(
 ' | '.join(data[x*3 + y] for y in range(3)) for x in range(3)))
def game():
 data = "123456789"
 winner = 0
 user, i = 'OX', 0
 for _ in range(9):
 availables = ', '.join([x for x in data if x not in 'OX'])
 x = 0
 while True:
 print_grid(data)
 x = int(input(
 "Player {} - please type a position (avaiable pos are {})"\
 .format(i + 1, availables)))
 if not (0 < x < 10) or data[x-1] in 'OX':
 print('invalid position')
 else:
 break
 data = data[:x-1] + user[i] + data[x:]
 i = (i + 1) % 2
 if any([True if re.match(x, data) else False for x in win1]):
 winner = 1
 elif any([True if re.match(x, data) else False for x in win2]):
 winner = 2
 if winner != 0:
 break
 else:
 print('No Winner')
 return
 print_grid(data)
 print('Win player is: player %d' % winner)
game()

2016年04月22日 14:25

룰루랄라

댓글 작성은 로그인이 필요합니다.
(注記) 상대에게 상처를 주기보다 서로에게 도움이 될 수 있는 댓글을 달아 주세요.
from itertools import cycle
nums = ''.join(str(x) for x in range(1,10))
pw = lambda : print('Wrong input')
av_pos = lambda res : 'available pos: '+ ', '.join(x for x in res if x not in ('A', 'B')) +'\n'
inpt = lambda fr, res: int(input(av_pos(res) + fr + ' : '))-1
check = lambda b: any(True if x == b&x else False for x in (448, 56, 7, 292, 146, 73, 273, 84))
output = lambda res: print(''.join(x+'\n' if i%3 == 2 else x for i, x in enumerate(res)))
main_code = list(compile('''while 1:\n {0} = inpt('{0}', res); n = 1 << {0}\n if (1 << {0}) & game == 1: pw(); continue\n else: break\ngame += n; {1} += n; res = res[:{0}] + '{0}' + res[{0}+1:]'''.format(T, T.lower()), '<string>', 'exec') for T in 'AB')
check_code = list(compile('check({})'.format(T.lower()), '<string>', 'eval') for T in 'AB')
while __name__ == '__main__':
 game = 2**9; draw = game-1
 res = nums
 a, b = 0, 0
 for i in cycle((0, 1)):
 exec(main_code[i])
 if eval(check_code[i]): break
 if a + b == draw: print('draw'); break
 output(res)
 output(res)

이진수로 풀어보았습니다. 반복되는 코드를 없애다 보니 문자열이 난무하네요. 파이썬 3.5.1

+

itertools.cycle:해당 반복가능한 객체를 반복.

댓글 작성은 로그인이 필요합니다.
(注記) 상대에게 상처를 주기보다 서로에게 도움이 될 수 있는 댓글을 달아 주세요.
arr1_1 = [[['1','2','3'],['4','5','6'],['7','8','9']]
 , [['1','4','7'],['2','5','8'],['3','6','9']]
 , [['1','5','9'],['3','5','7'],['.','.','.']]]
def f1():
 result = ', '.join([', '.join([x1 for x1 in x if x1!='O' and x1!='X']) for x in arr1_1[0]])
 return result
def f2(nums, typ1):
 for i1 in range(0, len(arr1_1)):
 for i2 in range(0, len(arr1_1[i1])):
 if arr1_1[i1][i2].count(nums) > 0:
 arr1_1[i1][i2][arr1_1[i1][i2].index(nums)] = typ1
 print('\n'.join([' * '.join([x1 for x1 in x]) for x in arr1_1[0]]))
def f3(typ1, idx1):
 for i1 in range(0, len(arr1_1)):
 if arr1_1[i1].count([typ1 for x in range(0, 3)]) > 0:
 print('Win playear is: player ', idx1)
 return typ1
 return ''
def f():
 while f1()!='':
 for idx1, typ1 in enumerate(['X','O']):
 plys = ''
 str1 = f1()
 while True:
 plys = input('Player '+str(idx1+1)+' - please type a position (available position(s) are ' + str1 + '):')
 if str1.count(plys) > 0:
 break
 f2(plys, typ1)
 if f3(typ1, str(idx1+1)) != '':
 return False
 if f1() == '':
 print('End..')
 return True
f()
댓글 작성은 로그인이 필요합니다.
(注記) 상대에게 상처를 주기보다 서로에게 도움이 될 수 있는 댓글을 달아 주세요.

파이썬 3.6

"""
아이디어>
 1) grid의 한변의 크기(n)을 입력받아 (n x n) grid를 생성한 후, 각 플레이어에게 숫자(m)을 입력받아 grid내에서 동일한 숫자 요소가 있는지 확인하여 각 플레이어에게 해당되는 표기를 합니다.
 2) 이미 다른 플레이어의 표식이 표기되어 있는 경우는 별도 표기없이 다른 플레이어에게 턴을 넘김니다.
 3) 매 턴마다 가로(tic) / 세로(tac) / 대각선(toe)를 count하여, 승리조건을 달성하는 경우 결과를 출력하고 게임을 마칩니다. 
"""
def makegrid(n):
 line,grid = [],[]
 for i in range(n*3):
 if i%3 != 1:
 for h in range(n*2-1):
 if h%2 == 0:
 line.append(' ')
 else:
 line.append('*')
 else:
 for h in range(n*2-1):
 if h%2 == 0:
 line.append(str(((i//3)*n)+(h//2+1)))
 else:
 line.append('*')
 grid.append(line)
 line = []
 return grid
def game():
 count,p,i,grid,tic,tac,toe = 0, '',0,[],0,0,0
 grid = makegrid(n)
 for i in grid:
 print(' '.join(i))
 while count < n*n:
 count += 1
 if tic == 3 or tac == 3 or toe == 3:
 break
 if count%2 != 0:
 chk = 1
 else:
 chk = 2
 m = input("Player%d - please type a position (available position(s) are 1,2,3,4,5,6,7,8,9): "%chk)
 try:
 i = ((int(m)-1)//3)*3 + 1
 if chk == 1:
 p = 'X'
 else:
 p = '0'
 grid[i][grid[i].index(m)] = p
 except ValueError:
 pass
 for i in range(0,n*2-1,2): # 세로 체크
 for h in range(1,n*3,3):
 if grid[h][i] == p:
 tic += 1
 if tic == 3:
 break
 else:
 tic = 0
 for i in range(1,n*3,3): # 가로 체크
 for h in range(0,n*2-1,2):
 if grid[i][h] == p:
 tac += 1
 if tac == 3:
 break
 else:
 tac = 0 
 for i in [0,n*2-2]: # 대각선 체크
 if i == 0:
 for h in range(1,n*3,3):
 if grid[h][i] == p:
 toe += 1
 i += 2
 if toe == 3:
 break
 else:
 toe = 0
 else:
 for h in range(1,n*3,3):
 if grid[h][i] == p:
 toe += 1
 i -= 2
 if toe == 3:
 break
 else:
 toe = 0 
 for i in grid:
 print(' '.join(i))
 if tic == 3 or tac == 3 or toe == 3:
 print("Win player is: player%d"%chk)
 else:
 print("This game is draw")
if __name__ == "__main__":
 n = int(input('n = '))
 game()
  • 결과값
n = 3
 * * 
1 * 2 * 3
 * * 
 * * 
4 * 5 * 6
 * * 
 * * 
7 * 8 * 9
 * * 
Player1 - please type a position (available position(s) are 1,2,3,4,5,6,7,8,9): 1
Player2 - please type a position (available position(s) are 1,2,3,4,5,6,7,8,9): 5
Player1 - please type a position (available position(s) are 1,2,3,4,5,6,7,8,9): 7
Player2 - please type a position (available position(s) are 1,2,3,4,5,6,7,8,9): 7
Player1 - please type a position (available position(s) are 1,2,3,4,5,6,7,8,9): 2
Player2 - please type a position (available position(s) are 1,2,3,4,5,6,7,8,9): 3
Player1 - please type a position (available position(s) are 1,2,3,4,5,6,7,8,9): 4
 * * 
X * X * 0
 * * 
 * * 
X * 0 * 6
 * * 
 * * 
X * 8 * 9
 * * 
Win player is: player1
댓글 작성은 로그인이 필요합니다.
(注記) 상대에게 상처를 주기보다 서로에게 도움이 될 수 있는 댓글을 달아 주세요.
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9]
player1 = list()
player2 = list()
def show(b):
 print(' '*8+'*'+' '*15+'*')
 print(' '+'{0}'.format(b[0])+' '*6+'*'+' '*7+'{0}'.format(b[1])+' '*7+'*'+' '*7+'{0}'.format(b[2]))
 print(' ' * 8 + '*' + ' ' * 15 + '*')
 print(' ' * 8 + '*' + ' ' * 15 + '*')
 print(' ' + '{0}'.format(b[3]) + ' ' * 6 + '*' + ' ' * 7 + '{0}'.format(b[4]) + ' ' * 7 + '*' + ' ' * 7 + '{0}'.format(b[5]))
 print(' ' * 8 + '*' + ' ' * 15 + '*')
 print(' ' * 8 + '*' + ' ' * 15 + '*')
 print(' ' + '{0}'.format(b[6]) + ' ' * 6 + '*' + ' ' * 7 + '{0}'.format(b[7]) + ' ' * 7 + '*' + ' ' * 7 + '{0}'.format(b[8]))
 print(' ' * 8 + '*' + ' ' * 15 + '*')
while 1:
 show(b)
 print("Player1 - please type a position (available position(s) are {0}".format(a))
 n = int(input())
 player1.append(n)
 a.remove(n)
 b[n-1] = 'X'
 l1 = [(i in player1) for i in range(1, 10)]
 if any([l1[0] and l1[1] and l1[2], l1[3] and l1[4] and l1[5], l1[6] and l1[7] and l1[8], l1[0] and l1[3] and l1[6], l1[1] and l1[4] and l1[7],
 l1[2] and l1[5] and l1[8], l1[0] and l1[4] and l1[8], l1[2] and l1[4] and l1[6]]):
 show(b)
 print("Winner is player1")
 break
 show(b)
 print("Player2 - please type a position (available positions(s) are {0}".format(a))
 n = int(input())
 player2.append(n)
 a.remove(n)
 b[n-1] = 'O'
 l2 = [(i in player2) for i in range(1, 10)]
 if any([l2[0] and l2[1] and l2[2], l2[3] and l2[4] and l2[5], l2[6] and l2[7] and l2[8], l2[0] and l2[3] and l2[6], l2[1] and l2[4] and l2[7],
 l2[2] and l2[5] and l2[8], l2[0] and l2[4] and l2[8], l2[2] and l2[4] and l2[6]]):
 show(b)
 print("Winner is player2")
 break

2018年02月19日 23:01

김동하

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

풀이 작성

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

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

sort x 2
연관 문제
Dasol Lee, 2025年02月25日 14:39

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

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