본문 바로가기
공부하며놀자/프로그래밍

[python]파이썬 기초 연습 console tic tac toe 게임. (3목 5목 오목 삼목)

by 테너토너 2019. 3. 1.

파이썬 기초 공부


from itertools import cycle
def win(current_game):
def check_winner(check, type_win):
if check.count(check[0]) == len(check) and check[0] != 0:
print(f"Player {check[0]} is the winner : {type_win}")
return True
return False
#Diagnol Back-slash
diags = []
test_reverse = reversed(range(len(current_game)))
for col, row in enumerate(test_reverse):
diags.append(current_game[row][col])
if check_winner(diags, "Diagnol(\\)"):
return True
#Diagnol Slash
diags = []
for idx in range(len(current_game)):
diags.append(current_game[idx][idx])
if check_winner(diags, "Diagnol(/)"):
return True
#Row
rows = []
for idx, enums in enumerate(current_game):
rows = list(enums)
if check_winner(rows, "Diagnol(-)"):
return True
#Col
for col in range(len(current_game)):
cols = []
for row in range(len(current_game)):
cols.append(current_game[row][col])
if check_winner(cols, "Diagnol(|)"):
return True
return False
def game_board(game_map, player=0, row=0, col=0, just_display=False):
try:
if game_map[row][col] != 0:
print(f"[{row}][{col}] is already occupied. Find another spot!")
return False, game_map
s = " " + " ".join([str(i) for i in range(game_size)])
print(s)
if not just_display:
game_map[row][col] = player
for count, row in enumerate(game):
print(count, row)
return True, game_map
except IndexError as e:
print("Error : make sure you input row/clumn as 0 1 and 2? ", e)
return False, game_map
except Exception as e:
print("Something went very wrong", e)
return False, game_map
play = True
while play:
players = cycle([1,2])
game_size = int(input("size of rectangular board size. ex)3x3, 4x4, etc.."))
print(f"gamesize: {game_size}")
game = [[0 for i in range(game_size)] for i in range(game_size)]
game_won = False
_, game = game_board(game, just_display=True)
while not game_won:
current_player = next(players)
print(f"Current player : {current_player}")
played = False
while not played:
row_choice = int(input("What row do you want to play? (0, 1, 2): "))
colum_choice = int(input("What column do you want to play? (0, 1, 2): "))
played, game = game_board(game, current_player, row_choice, colum_choice)
if win(game):
game_won = True
again = input("The game is over, would you like to play again? (y/n) : ")
if again.lower() == 'y':
print("restarting")
else:
print("Byeeee")
play = False


반응형

댓글