Skip to content

Instantly share code, notes, and snippets.

@aesophor
Last active April 21, 2021 02:43
Show Gist options
  • Save aesophor/40f7502513e681489076c34dbb7b6eae to your computer and use it in GitHub Desktop.
Save aesophor/40f7502513e681489076c34dbb7b6eae to your computer and use it in GitHub Desktop.
五子棋 OAO
#!/usr/bin/env python3
# --*-- encoding: utf-8 --*--
import sys
import random
# 常數
empty = 0
player = 1
computer = 2
# 5x5 棋盤
board = [[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]]
def show_board():
for row in board:
print(row)
def get_available_positions():
positions = []
for y in range(5):
for x in range(5):
if board[y][x] == 0:
positions.append((y, x))
return positions
def all_elements_are(_list, value):
return len(set(_list)) == 1 and _list[0] == value
def transpose(matrix):
# 讓行列互換,但不會動到原本的棋盤
# 這邊是為了檢查勝負用。
# https://stackoverflow.com/questions/4937491/matrix-transpose-in-python
return [*zip(*matrix)]
def maybe_get_winner():
# 檢查橫的
for row in board:
if all_elements_are(row, player):
return player
elif all_elements_are(row, computer):
return computer
# 檢查直的
for row in transpose(board):
if all_elements_are(row, player):
return player
elif all_elements_are(row, computer):
return computer
# 檢查斜的 (左上到右下)
elements = []
for i in range(5):
elements.append(board[i][i])
if all_elements_are(elements, player):
return player
elif all_elements_are(elements, computer):
return computer
# 檢查斜的 (右上到左下)
elements.clear()
for i in range(5):
elements.append(board[i][4 - i])
if all_elements_are(elements, player):
return player
elif all_elements_are(elements, computer):
return computer
return empty
def put(y, x, role):
if board[y][x] != empty:
print('這個地方被下過了!')
sys.exit(0)
board[y][x] = role
def main():
# 一些紀錄遊戲狀態的變數
player_turn = True
print('歡迎來到五子棋遊戲 ʕ•͡ᴥ•ʔ,您的棋子是白色')
while True:
if player_turn:
show_board()
y, x = map(int, input('要下哪裡呢:'))
put(y, x, player)
else:
positions = get_available_positions()
if (len(positions) == 0):
print('都被下滿了,遊戲結束')
sys.exit(0)
computer_choice = random.randint(0, len(positions) - 1)
y, x = positions[computer_choice]
put(y, x, computer)
winner = maybe_get_winner()
if winner == player:
show_board()
print('玩家贏了')
sys.exit(0)
elif winner == computer:
show_board()
print('電腦贏了')
sys.exit(0)
# 玩家下完換電腦,電腦下完換玩家
player_turn = not player_turn
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment