python五子棋100行小游戏代码
时间: 2023-07-22 17:39:23 浏览: 101
以下是一个简单的 Python 五子棋小游戏代码,共计 100 行左右:
```python
import pygame
# 初始化 Pygame
pygame.init()
# 游戏窗口大小
SCREEN_WIDTH = 640
SCREEN_HEIGHT = 640
# 棋盘大小
BOARD_SIZE = 15
LINE_WIDTH = 2
GRID_SIZE = 40
# 棋子大小
PIECE_RADIUS = 18
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)
# 创建游戏窗口
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("五子棋")
# 创建棋盘
board = [[0] * BOARD_SIZE for _ in range(BOARD_SIZE)]
# 定义当前下棋方
current_player = 1
# 判断是否游戏结束
game_over = False
def draw_board():
# 绘制棋盘背景
screen.fill(BLACK)
# 绘制棋盘网格线
for i in range(BOARD_SIZE):
pygame.draw.line(screen, WHITE, (GRID_SIZE, (i + 1) * GRID_SIZE), ((BOARD_SIZE - 1) * GRID_SIZE, (i + 1) * GRID_SIZE), LINE_WIDTH)
pygame.draw.line(screen, WHITE, ((i + 1) * GRID_SIZE, GRID_SIZE), ((i + 1) * GRID_SIZE, (BOARD_SIZE - 1) * GRID_SIZE), LINE_WIDTH)
# 绘制棋子
for i in range(BOARD_SIZE):
for j in range(BOARD_SIZE):
if board[i][j] == 1:
pygame.draw.circle(screen, WHITE, ((i + 1) * GRID_SIZE, (j + 1) * GRID_SIZE), PIECE_RADIUS)
elif board[i][j] == 2:
pygame.draw.circle(screen, BLUE, ((i + 1) * GRID_SIZE, (j + 1) * GRID_SIZE), PIECE_RADIUS)
def check_win(player):
# 判断横向是否有五个棋子相连
for i in range(BOARD_SIZE):
for j in range(BOARD_SIZE - 4):
if board[i][j] == player and board[i][j + 1] == player and board[i][j + 2] == player and board[i][j + 3] == player and board[i][j + 4] == player:
return True
# 判断纵向是否有五个棋子相连
for i in range(BOARD_SIZE - 4):
for j in range(BOARD_SIZE):
if board[i][j] == player and board[i + 1][j] == player and board[i + 2][j] == player and board[i + 3][j] == player and board[i + 4][j] == player:
return True
# 判断右上斜向是否有五个棋子相连
for i in range(BOARD_SIZE - 4):
for j in range(4, BOARD_SIZE):
if board[i][j] == player and board[i + 1][j - 1] == player and board[i + 2][j - 2] == player and board[i + 3][j - 3] == player and board[i + 4][j - 4] == player:
return True
# 判断右下斜向是否有五个棋子相连
for i in range(BOARD_SIZE - 4):
for j in range(BOARD_SIZE - 4):
if board[i][j] == player and board[i + 1][j + 1] == player and board[i + 2][j + 2] == player and board[i + 3][j + 3] == player and board[i + 4][j + 4] == player:
return True
return False
# 游戏循环
while True:
# 处理游戏事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.MOUSEBUTTONDOWN and not game_over:
# 获取鼠标点击位置
x, y = pygame.mouse.get_pos()
# 计算点击的棋子坐标
i = int(x / GRID_SIZE) - 1
j = int(y / GRID_SIZE) - 1
# 如果该位置没有棋子,则下子
if board[i][j] == 0:
board[i][j] = current_player
# 判断是否胜利
if check_win(current_player):
print("Player %d wins!" % current_player)
game_over = True
# 切换下棋方
current_player = 3 - current_player
# 绘制棋盘和棋子
draw_board()
# 更新屏幕内容
pygame.display.flip()
```
注:该代码仅供参考,可能存在一些问题和不足之处,需要根据实际需求进行修改和完善。
阅读全文