【Python游戏开发】制作经典游戏五子棋,附完整教程及源码!

五子棋是一种源自中国的传统棋类游戏,起源可以追溯到古代。它是一种两人对弈的游戏,使用棋盘和棋子进行。棋盘通常是一个 15×15 的网格,棋子分为黑白两色,双方轮流在棋盘上落子。游戏的目标是通过在棋盘上落子,使自己的五个棋子在横向、纵向或斜向形成连续的线路,从而获胜。
五子棋被认为是一种智力游戏,它要求玩家在竞技中思考对手的走法并制定自己的策略。由于规则简单、易于上手,五子棋在中国以及世界各地都很受欢迎,并且有许多不同的变种和玩法。笔者选择了一个最原始最简易的一个简易五子棋的程序,采用文本界面操作。

源码获取:

在这里插入图片描述



主要源代码展示:

# 检查水平方向
count = 0
for i in range(max(0, col - 4), min(15, col + 5)):
    if board[row][i] == player:
        count += 1
        if count == 5:
            return True
    else:
        count = 0

# 检查垂直方向
count = 0
for i in range(max(0, row - 4), min(15, row + 5)):
    if board[i][col] == player:
        count += 1
        if count == 5:
            return True
    else:
        count = 0

# 检查斜向(\)方向
count = 0
for i in range(-4, 5):
    r = row + i
    c = col + i
    if r < 0 or r >= 15 or c < 0 or c >= 15:
        continue
    if board[r][c] == player:
        count += 1
        if count == 5:
            return True
    else:
        count = 0

# 检查斜向(/)方向
count = 0
for i in range(-4, 5):
    r = row + i
    c = col - i
    if r < 0 or r >= 15 or c < 0 or c >= 15:
        continue
    if board[r][c] == player:
        count += 1
        if count == 5:
            return True
    else:
        count = 0

return False


board = [["." for _ in range(15)] for _ in range(15)]
players = ["X", "O"]
current_player = 0
print_board(board)

while True:
    print(f"Player {players[current_player]}'s turn:")
    try:
        row = int(input("Enter row (0-14): "))
        col = int(input("Enter col (0-14): "))
        if row < 0 or row >= 15 or col < 0 or col >= 15 or board[row][col] != ".":
            raise ValueError
    except ValueError:
        print("Invalid input. Try again.")
        continue

    board[row][col] = players[current_player]
    print_board(board)
    if check_win(board, row, col, players[current_player]):
        print(f"Player {players[current_player]} wins!")
        break

    current_player = (current_player + 1) % 2
通过改进,新增了可使用鼠标交互的效果,相比较于原始的代码,大大提高了游戏体验性,并且使游戏界面更加易于操作,在游戏体验上大大增加也玩性。

原始代码:

import pygame  
import sys

游戏设置

CELL\_SIZE = 40  
BOARD\_SIZE = 15  
WINDOW\_WIDTH = CELL\_SIZE \* BOARD\_SIZE  
WINDOW\_HEIGHT = CELL\_SIZE \* BOARD\_SIZE  
LINE\_COLOR = (0, 0, 0)  
BG\_COLOR = (139, 69, 19) # 棕色背景

初始化游戏

pygame.init()  
screen = pygame.display.set\_mode((WINDOW\_WIDTH, WINDOW\_HEIGHT))  
pygame.display.set\_caption(“五子棋”)  
clock = pygame.time.Clock()  
board = \[\[’ ’ for \_ in range(BOARD\_SIZE)\] for \_ in range(BOARD\_SIZE)\]  
current\_player = ‘X’  
game\_over = False

def draw\_board():  
screen.fill(BG\_COLOR)  
for i in range(BOARD\_SIZE):  
pygame.draw.line(screen, LINE\_COLOR, (CELL\_SIZE // 2, CELL\_SIZE // 2 + i \* CELL\_SIZE),  
(WINDOW\_WIDTH - CELL\_SIZE // 2, CELL\_SIZE // 2 + i \* CELL\_SIZE))  
pygame.draw.line(screen, LINE\_COLOR, (CELL\_SIZE // 2 + i \* CELL\_SIZE, CELL\_SIZE // 2),  
(CELL\_SIZE // 2 + i \* CELL\_SIZE, WINDOW\_HEIGHT - CELL\_SIZE // 2))

def draw\_piece(row, col, player):  
x = col \* CELL\_SIZE + CELL\_SIZE // 2  
y = row \* CELL\_SIZE + CELL\_SIZE // 2  
if player == ‘X’:  
pygame.draw.circle(screen, (0, 0, 0), (x, y), CELL\_SIZE // 3)  
else:  
pygame.draw.circle(screen, (255, 255, 255), (x, y), CELL\_SIZE // 3)

def check\_win(row, col):  
directions = \[(1, 0), (0, 1), (1, 1), (1, -1)\]  
for d in directions:  
count = 1  
for i in range(1, 5):  
if 0 <= row + i \* d\[0\] < BOARD\_SIZE and 0 <= col + i \* d\[1\] < BOARD\_SIZE and  
board\[row + i \* d\[0\]\]\[col + i \* d\[1\]\] == current\_player:  
count += 1  
else:  
break  
for i in range(1, 5):  
if 0 <= row - i \* d\[0\] < BOARD\_SIZE and 0 <= col - i \* d\[1\] < BOARD\_SIZE and  
board\[row - i \* d\[0\]\]\[col - i \* d\[1\]\] == current\_player:  
count += 1  
else:  
break  
if count >= 5:  
return True  
return False

def display\_winner(player):  
font = pygame.font.Font(None, 36)  
if player == ‘X’:  
text = font.render(“Black wins!”, True, (255, 0, 0))  
else:  
text = font.render(“White wins!”, True, (255, 0, 0))  
text\_rect = text.get\_rect(center=(WINDOW\_WIDTH // 2, WINDOW\_HEIGHT // 2))  
screen.blit(text, text\_rect)

游戏循环

while True:  
for event in pygame.event.get():  
if event.type == pygame.QUIT:  
pygame.quit()  
sys.exit()  
elif event.type == pygame.MOUSEBUTTONDOWN and not game\_over:  
x, y = event.pos  
col = x // CELL\_SIZE  
row = y // CELL\_SIZE  
if 0 <= row < BOARD\_SIZE and 0 <= col < BOARD\_SIZE and board\[row\]\[col\] == ’ ':  
board\[row\]\[col\] = current\_player  
draw\_piece(row, col, current\_player)  
if check\_win(row, col):
print(f"Player {current_player} wins!")
                game_over = True
            current_player = 'O' if current_player == 'X' else 'X'
            draw_board()
for row in range(BOARD_SIZE):
    for col in range(BOARD_SIZE):
        if board[row][col] != ' ':
            draw_piece(row, col, board[row][col])

if game_over:
    display_winner(current_player)

pygame.display.flip()
clock.tick(30)
import pygame  
import sys

游戏设置

CELL\_SIZE = 40  
BOARD\_SIZE = 15  
WINDOW\_WIDTH = CELL\_SIZE \* BOARD\_SIZE  
WINDOW\_HEIGHT = CELL\_SIZE \* BOARD\_SIZE  
LINE\_COLOR = (0, 0, 0)  
BG\_COLOR = (139, 69, 19) # 棕色背景

初始化游戏

pygame.init()  
screen = pygame.display.set\_mode((WINDOW\_WIDTH, WINDOW\_HEIGHT))  
pygame.display.set\_caption(“五子棋”)  
clock = pygame.time.Clock()  
board = \[\[’ ’ for \_ in range(BOARD\_SIZE)\] for \_ in range(BOARD\_SIZE)\]  
current\_player = ‘X’  
game\_over = False

def draw\_board():  
screen.fill(BG\_COLOR)  
for i in range(BOARD\_SIZE):  
pygame.draw.line(screen, LINE\_COLOR, (CELL\_SIZE // 2, CELL\_SIZE // 2 + i \* CELL\_SIZE),  
(WINDOW\_WIDTH - CELL\_SIZE // 2, CELL\_SIZE // 2 + i \* CELL\_SIZE))  
pygame.draw.line(screen, LINE\_COLOR, (CELL\_SIZE // 2 + i \* CELL\_SIZE, CELL\_SIZE // 2),  
(CELL\_SIZE // 2 + i \* CELL\_SIZE, WINDOW\_HEIGHT - CELL\_SIZE // 2))

def draw\_piece(row, col, player):  
x = col \* CELL\_SIZE + CELL\_SIZE // 2  
y = row \* CELL\_SIZE + CELL\_SIZE // 2  
if player == ‘X’:  
pygame.draw.circle(screen, (0, 0, 0), (x, y), CELL\_SIZE // 3)  
else:  
pygame.draw.circle(screen, (255, 255, 255), (x, y), CELL\_SIZE // 3)

def check\_win(row, col):  
directions = \[(1, 0), (0, 1), (1, 1), (1, -1)\]  
for d in directions:  
count = 1  
for i in range(1, 5):  
if 0 <= row + i \* d\[0\] < BOARD\_SIZE and 0 <= col + i \* d\[1\] < BOARD\_SIZE and  
board\[row + i \* d\[0\]\]\[col + i \* d\[1\]\] == current\_player:  
count += 1  
else:  
break  
for i in range(1, 5):  
if 0 <= row - i \* d\[0\] < BOARD\_SIZE and 0 <= col - i \* d\[1\] < BOARD\_SIZE and  
board\[row - i \* d\[0\]\]\[col - i \* d\[1\]\] == current\_player:  
count += 1  
else:  
break  
if count >= 5:  
return True  
return False

def display\_winner(player):  
font = pygame.font.Font(None, 36)  
if player == ‘X’:  
text = font.render(“Black wins!”, True, (255, 0, 0))  
else:  
text = font.render(“White wins!”, True, (255, 0, 0))  
text\_rect = text.get\_rect(center=(WINDOW\_WIDTH // 2, WINDOW\_HEIGHT // 2))  
screen.blit(text, text\_rect)

游戏循环

while True:  
for event in pygame.event.get():  
if event.type == pygame.QUIT:  
pygame.quit()  
sys.exit()  
elif event.type == pygame.MOUSEBUTTONDOWN and not game\_over:  
x, y = event.pos  
col = x // CELL\_SIZE  
row = y // CELL\_SIZE  
if 0 <= row < BOARD\_SIZE and 0 <= col < BOARD\_SIZE and board\[row\]\[col\] == ’ ':  
board\[row\]\[col\] = current\_player  
draw\_piece(row, col, current\_player)  
if check\_win(row, col):  
print(f"Player {current\_player} wins!")  
game\_over = True  
current\_player = ‘O’ if current\_player == ‘X’ else ‘X’
draw_board()
for row in range(BOARD_SIZE):
    for col in range(BOARD_SIZE):
        if board[row][col] != ' ':
            draw_piece(row, col, board[row][col])

if game_over:
    display_winner(current_player)

pygame.display.flip()
clock.tick(30)

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述


结语:

  • 它通过简洁明了的语法和逻辑结构,提高了代码的可读性和可维护性。通过引入交互性更强的用户输入方式,使得玩家可以更直观地参与游戏,增强了游戏的可玩性和用户体验。总的来说,这段 Python 在保持游戏逻辑不变的情况下,提升了代码的质量和可玩性,为开发者和玩家带来了更好的体验。
    图片

总结

  • 最后希望你编程学习上不急不躁,按照计划有条不紊推进,把任何一件事做到极致,都是不容易的,加油,努力!相信自己!

文末福利

  • 最后这里免费分享给大家一份Python全套学习资料,希望能帮到那些不满现状,想提升自己却又没有方向的朋友,也可以和我一起来学习交流呀。

包含编程资料、学习路线图、源代码、软件安装包等!【[点击这里]】领取!

  • ① Python所有方向的学习路线图,清楚各个方向要学什么东西
  • ② 100多节Python课程视频,涵盖必备基础、爬虫和数据分析
  • ③ 100多个Python实战案例,学习不再是只会理论
  • ④ 华为出品独家Python漫画教程,手机也能学习

可以扫描下方二维码领取【保证100%免费

在这里插入图片描述

  • 17
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的 Python 五子棋游戏源码: ```python import numpy as np BOARD_SIZE = 15 # 棋盘大小 EMPTY = 0 # 空棋子 BLACK = 1 # 黑棋子 WHITE = 2 # 白棋子 class Board: def __init__(self): self.board = np.zeros((BOARD_SIZE, BOARD_SIZE), dtype=int) self.current_player = BLACK def place(self, x, y): if self.board[x][y] == EMPTY: self.board[x][y] = self.current_player self.current_player = WHITE if self.current_player == BLACK else BLACK return True else: return False def check_win(self): for i in range(BOARD_SIZE): for j in range(BOARD_SIZE): if self.board[i][j] != EMPTY: # 横向 if j <= BOARD_SIZE - 5: if self.board[i][j] == self.board[i][j+1] == self.board[i][j+2] == self.board[i][j+3] == self.board[i][j+4]: return self.board[i][j] # 纵向 if i <= BOARD_SIZE - 5: if self.board[i][j] == self.board[i+1][j] == self.board[i+2][j] == self.board[i+3][j] == self.board[i+4][j]: return self.board[i][j] # 左上到右下 if i <= BOARD_SIZE - 5 and j <= BOARD_SIZE - 5: if self.board[i][j] == self.board[i+1][j+1] == self.board[i+2][j+2] == self.board[i+3][j+3] == self.board[i+4][j+4]: return self.board[i][j] # 右上到左下 if i >= 4 and j <= BOARD_SIZE - 5: if self.board[i][j] == self.board[i-1][j+1] == self.board[i-2][j+2] == self.board[i-3][j+3] == self.board[i-4][j+4]: return self.board[i][j] return EMPTY class Game: def __init__(self): self.board = Board() def start(self): while True: self.print_board() x, y = input(f"请 {self.board.current_player} 玩家下棋(x,y):").split(',') x, y = int(x), int(y) if 0 <= x < BOARD_SIZE and 0 <= y < BOARD_SIZE: if self.board.place(x, y): winner = self.board.check_win() if winner != EMPTY: self.print_board() print(f"{winner} 玩家获胜!") break else: print("此处已经有棋子了,请重新下棋!") else: print("坐标范围不正确,请重新输入!") def print_board(self): print(" ", end="") for i in range(BOARD_SIZE): print(i, end=" ") print() for i in range(BOARD_SIZE): print(i, end=" ") for j in range(BOARD_SIZE): if self.board.board[i][j] == BLACK: print("●", end=" ") elif self.board.board[i][j] == WHITE: print("○", end=" ") else: print("+", end=" ") print() if __name__ == '__main__': game = Game() game.start() ``` 使用方法: - 下载源码并保存到本地; - 在终端或命令行窗口中进入源码所在目录; - 输入 `python gomoku.py` 命令运行程序; - 根据提示输入坐标下棋。 注意:此程序为简单版本,可能存在一些小问题,欢迎大家提出改进意见。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值