五子棋是一種經典的策略性棋類游戲,規則簡單但變化豐富。本文將介紹如何使用Python實現一個簡單的人人對戰的五子棋游戲。我們將使用pygame
庫來創建游戲的圖形界面,并實現基本的游戲邏輯。
首先,確保你已經安裝了pygame
庫。如果沒有安裝,可以使用以下命令進行安裝:
pip install pygame
我們首先創建一個游戲窗口,并設置棋盤的大小和背景顏色。
import pygame
# 初始化pygame
pygame.init()
# 設置窗口大小
WINDOW_WIDTH = 600
WINDOW_HEIGHT = 600
window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("五子棋")
# 設置棋盤大小
BOARD_SIZE = 15
CELL_SIZE = WINDOW_WIDTH // BOARD_SIZE
# 設置顏色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
BACKGROUND_COLOR = (200, 150, 100)
# 繪制棋盤
def draw_board():
window.fill(BACKGROUND_COLOR)
for i in range(BOARD_SIZE):
pygame.draw.line(window, BLACK, (i * CELL_SIZE, 0), (i * CELL_SIZE, WINDOW_HEIGHT), 2)
pygame.draw.line(window, BLACK, (0, i * CELL_SIZE), (WINDOW_WIDTH, i * CELL_SIZE), 2)
pygame.display.update()
# 主循環
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
draw_board()
pygame.quit()
接下來,我們需要實現棋子的落子功能。我們將使用一個二維數組來表示棋盤的狀態,并在玩家點擊鼠標時更新棋盤。
# 初始化棋盤
board = [[0 for _ in range(BOARD_SIZE)] for _ in range(BOARD_SIZE)]
# 繪制棋子
def draw_piece(row, col, player):
if player == 1:
color = BLACK
else:
color = WHITE
pygame.draw.circle(window, color, (col * CELL_SIZE + CELL_SIZE // 2, row * CELL_SIZE + CELL_SIZE // 2), CELL_SIZE // 2 - 5)
pygame.display.update()
# 處理鼠標點擊事件
def handle_click(pos):
x, y = pos
row = y // CELL_SIZE
col = x // CELL_SIZE
if board[row][col] == 0:
board[row][col] = current_player
draw_piece(row, col, current_player)
return True
return False
# 主循環
current_player = 1
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.MOUSEBUTTONDOWN:
if handle_click(event.pos):
current_player = 3 - current_player # 切換玩家
draw_board()
pygame.quit()
最后,我們需要實現一個函數來判斷是否有玩家獲勝。我們將檢查棋盤上的每一行、每一列以及兩條對角線,看看是否有五個連續的相同棋子。
def check_winner(row, col):
directions = [(1, 0), (0, 1), (1, 1), (1, -1)]
for dr, dc in directions:
count = 1
for i in range(1, 5):
r = row + dr * i
c = col + dc * i
if 0 <= r < BOARD_SIZE and 0 <= c < BOARD_SIZE and board[r][c] == board[row][col]:
count += 1
else:
break
for i in range(1, 5):
r = row - dr * i
c = col - dc * i
if 0 <= r < BOARD_SIZE and 0 <= c < BOARD_SIZE and board[r][c] == board[row][col]:
count += 1
else:
break
if count >= 5:
return True
return False
# 主循環
current_player = 1
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.MOUSEBUTTONDOWN:
if handle_click(event.pos):
if check_winner(row, col):
print(f"玩家 {current_player} 獲勝!")
running = False
current_player = 3 - current_player # 切換玩家
draw_board()
pygame.quit()
通過以上步驟,我們實現了一個簡單的人人對戰的五子棋游戲。你可以在此基礎上進一步優化,例如添加悔棋功能、計時器、對戰等。希望這篇文章能幫助你理解如何使用Python實現一個簡單的五子棋游戲。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。