pycharm五子棋游戏代码
时间: 2023-06-25 11:02:20 浏览: 165
以下是一个简单的五子棋游戏代码,使用PyCharm开发:
```python
import pygame
import sys
# 初始化pygame
pygame.init()
# 设置游戏界面大小、背景颜色、标题
size = width, height = 600, 600
bg_color = 255, 255, 255
caption = "Five in a row"
screen = pygame.display.set_mode(size)
pygame.display.set_caption(caption)
# 棋盘大小、行列数、棋子半径等参数
board_size = 500
board_left, board_top = (width - board_size) // 2, (height - board_size) // 2
grid_size = board_size // 15
piece_radius = grid_size // 2 - 2
# 初始化棋盘和棋子颜色
board_color = 0, 0, 0
piece_colors = [(0, 0, 0), (255, 255, 255)]
# 创建棋盘表格
def create_board():
return [[0] * 15 for _ in range(15)]
# 绘制棋盘
def draw_board():
screen.fill(bg_color)
pygame.draw.rect(screen, board_color, (board_left, board_top, board_size, board_size), 2)
for i in range(15):
x = board_left + i * grid_size
y1, y2 = board_top, board_top + board_size
pygame.draw.line(screen, board_color, (x, y1), (x, y2), 1)
pygame.draw.line(screen, board_color, (y1, x), (y2, x), 1)
# 绘制特殊点
points = [(3, 3), (3, 11), (7, 7), (11, 3), (11, 11)]
for row, col in points:
x = board_left + col * grid_size
y = board_top + row * grid_size
pygame.draw.circle(screen, board_color, (x, y), 5, 0)
# 绘制棋子
def draw_piece(row, col, color):
x = board_left + col * grid_size
y = board_top + row * grid_size
pygame.draw.circle(screen, piece_colors[color], (x, y), piece_radius)
# 判断胜利条件
def check_win(board, row, col):
color = board[row][col]
directions = [(0, 1), (1, 0), (1, 1), (1, -1)]
for dx, dy in directions:
count = 1
for i in range(1, 5):
r, c = row + i * dx, col + i * dy
if r < 0 or r >= 15 or c < 0 or c >= 15 or board[r][c] != color:
break
count += 1
for i in range(1, 5):
r, c = row - i * dx, col - i * dy
if r < 0 or r >= 15 or c < 0 or c >= 15 or board[r][c] != color:
break
count += 1
if count >= 5:
return True
return False
# 玩家下棋
def player_move(board, color):
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
x, y = event.pos
if board_left <= x < board_left + board_size and board_top <= y < board_top + board_size:
col = (x - board_left) // grid_size
row = (y - board_top) // grid_size
if board[row][col] == 0:
board[row][col] = color
draw_piece(row, col, color)
if check_win(board, row, col):
return True
return False
# AI下棋
def ai_move(board, color):
# TODO: 实现AI下棋算法
pass
# 游戏主循环
def main():
board = create_board()
draw_board()
pygame.display.flip()
turn = 0
while True:
if turn % 2 == 0:
if player_move(board, 0):
print("Black wins!")
break
else:
if ai_move(board, 1):
print("White wins!")
break
turn += 1
pygame.display.flip()
if __name__ == "__main__":
main()
```
注意:这只是一个简单的五子棋游戏代码,其中的AI下棋算法部分需要自己实现。
阅读全文