python用pygame井字棋源代码
时间: 2023-07-12 20:49:21 浏览: 68
以下是一个简单的井字棋游戏的 Python 代码,使用 Pygame 模块实现:
```python
import pygame, sys
from pygame.locals import *
# 初始化 Pygame
pygame.init()
# 设置窗口大小和标题
WINDOW_SIZE = (500, 500)
screen = pygame.display.set_mode(WINDOW_SIZE)
pygame.display.set_caption('Tic Tac Toe')
# 设置颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
# 设置字体
font = pygame.font.Font(None, 36)
# 游戏变量
board = [[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]
player = 1
game_over = False
winner = None
# 绘制棋盘
def draw_board():
for i in range(1, 3):
pygame.draw.line(screen, BLACK, (i * 150, 0), (i * 150, 450), 5)
pygame.draw.line(screen, BLACK, (0, i * 150), (450, i * 150), 5)
# 绘制棋子
def draw_piece(row, col):
x = col * 150 + 75
y = row * 150 + 75
if player == 1:
pygame.draw.circle(screen, WHITE, (x, y), 60, 10)
else:
pygame.draw.line(screen, WHITE, (x - 60, y - 60), (x + 60, y + 60), 10)
pygame.draw.line(screen, WHITE, (x + 60, y - 60), (x - 60, y + 60), 10)
# 检查是否有胜者
def check_winner():
global game_over, winner
for i in range(3):
if board[i][0] == board[i][1] == board[i][2] != 0:
game_over = True
winner = board[i][0]
if board[0][i] == board[1][i] == board[2][i] != 0:
game_over = True
winner = board[0][i]
if board[0][0] == board[1][1] == board[2][2] != 0:
game_over = True
winner = board[0][0]
if board[0][2] == board[1][1] == board[2][0] != 0:
game_over = True
winner = board[0][2]
if all(all(row) for row in board) and not game_over:
game_over = True
# 显示游戏结果
def show_result():
if winner:
text = 'Player {} wins!'.format(winner)
else:
text = 'It is a tie!'
result = font.render(text, True, WHITE, BLACK)
result_rect = result.get_rect(center=(225, 225))
screen.blit(result, result_rect)
# 主循环
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == MOUSEBUTTONDOWN and not game_over:
row = int(event.pos[1] / 150)
col = int(event.pos[0] / 150)
if board[row][col] == 0:
board[row][col] = player
draw_piece(row, col)
check_winner()
if not game_over:
player = 3 - player
elif event.type == KEYDOWN:
if event.key == K_ESCAPE:
pygame.quit()
sys.exit()
# 清空画布
screen.fill(BLACK)
# 绘制棋盘和棋子
draw_board()
for row in range(3):
for col in range(3):
if board[row][col] != 0:
draw_piece(row, col)
# 显示游戏结果
if game_over:
show_result()
# 更新画面
pygame.display.update()
```
希望这个代码能够帮助到你!