环境:python
使用的第三方库:pygame
若为安装pygame请在终端输入"pip install pygame"安装pygame后再运行程序
废话不多说直接上代码(有注释!!!)
import pygame, sys # 声明 导入需要的模块 from pygame.locals import * from math import
pi pygame.init()# 初始化pygame screen = pygame.display.set_mode((700,700))#
设置窗口的大小,单位为像素 pygame.display.set_caption('井字棋')# 设置窗口的标题 # 定义基础颜色 BLACK = ( 0, 0
, 0) WHITE = (255, 255, 255) RED = (255, 0, 0) GREEN = ( 0, 255, 0) BLUE = ( 0,
0, 255) # 九个格子的位置(写死,有更好的方法请告诉我(肯定有)) box1=[50,50,195,195] box2=[50,250,195,195]
box3=[50,450,195,195] box4=[250,50,195,195] box5=[250,250,195,195] box6=[250,
450,195,195] box7=[450,50,195,195] box8=[450,250,195,195] box9=[450,450,195,195]
# 放进一个大的格子数组中 boxes=[box1,box2,box3,box4,box5,box6,box7,box8,box9] # 绘制黑色作为背景
screen.fill(BLACK) # 绘制棋盘 for i in range(0,9): pygame.draw.rect(screen, WHITE,
boxes[i], 3) # 棋子标识 1为圈 ,0为叉 status = 1 # 已经下了几颗棋子 number = 0 #
棋盘和棋子,0为空,1为圈,2为叉 nine = [[0,0,0],[0,0,0],[0,0,0]] # 判断是否有一方胜出 def isWin(q): #
遍历每一种胜出的条件 if nine[0][0] == q and nine[0][1] == q and nine[0][2] == q: drawWin(q
) elif nine[1][0] == q and nine[1][1] == q and nine[1][2] == q: drawWin(q) elif
nine[2][0] == q and nine[2][1] == q and nine[2][2] == q: drawWin(q) elif nine[0]
[0] == q and nine[1][0] == q and nine[2][0] == q: drawWin(q) elif nine[0][1] ==
qand nine[1][1] == q and nine[2][1] == q: drawWin(q) elif nine[0][2] == q and
nine[1][2] == q and nine[2][2] == q: drawWin(q) elif nine[0][0] == q and nine[1]
[1] == q and nine[2][2] == q: drawWin(q) elif nine[2][0] == q and nine[1][1] ==
qand nine[0][2] == q: drawWin(q) # 平局 elif number == 9 : drawDraw() else: return
False # 胜出一方提示 def drawWin(q): if q == 1: font = pygame.font.Font(
'BankgothicMB.ttf', 45) text = font.render('Circle WIN!!!', True, RED) screen.
blit(text, (210, 300)) elif q == 2: font = pygame.font.Font('BankgothicMB.ttf',
45) text = font.render('X WIN!!!', True, RED) screen.blit(text, (260, 300)) #
平局提示 def drawDraw(): font = pygame.font.Font('BankgothicMB.ttf', 40) text = font
.render('THE GAME HAS DRAWN!', True, RED) screen.blit(text, (85, 300)) while
True: # 程序主循环 for event in pygame.event.get(): if event.type == QUIT: pygame.
quit() sys.exit() elif event.type == MOUSEBUTTONDOWN: pos = pygame.mouse.get_pos
() # 判断鼠标点击在哪个格子上 x = (pos[0]-50) // 200 y = (pos[1]-50) // 200 # 筛选掉已经下过的格子 if
nine[x][y] == 0 and status == 1 : # 画圈 pygame.draw.arc(screen, GREEN,[x*200+75,y
*200+75, 150, 150], 0, 2*pi, 5) nine[x][y]=1 number +=1 # 当下到第五颗棋时开始判断是否有一方胜出 if
number>4: isWin(1) status = 0 # 叉方,逻辑同上 elif nine[x][y] == 0 and status == 0 :
# 画叉 pygame.draw.line(screen, BLUE, [x*200+75, y*200+75], [x*200+225, y*200+225]
, 6) pygame.draw.line(screen, BLUE, [x*200+225, y*200+75], [x*200+75, y*200+225]
, 6) nine[x][y]=2 number +=1 if number>4: isWin(2) status = 1 else : pass pygame
.display.update()# 绘制屏幕内容

技术
下载桌面版
GitHub
Gitee
SourceForge
百度网盘(提取码:draw)
云服务器优惠
华为云优惠券
腾讯云优惠券
阿里云优惠券
Vultr优惠券
站点信息
问题反馈
邮箱:[email protected]
吐槽一下
QQ群:766591547
关注微信