1.要安装的库
按住win+r输入cmd 回车确定
再输入 pip install pygame 下载pygame
2.源码
import pygame
import sys
import random
import time
# 设置窗口
pygame.init()
time_clock = pygame.time.Clock()
screen = pygame.display.set_mode((900, 900))
pygame.display.set_caption('双人对战井字棋')
# 颜色
black = [0, 0, 0]
white = [255, 255, 255]
red = [255, 0, 0]
blue = [0, 0, 255]
# 下棋坐标
chess_pos = []
j = 0
chess_pos1 = []
# 场上每个格子是否有棋
lattice = [0, 0, 0,
0, 0, 0,
0, 0, 0]
# 轮哪一方下棋
play_chess = 0
first = 0
# 赢的项
win_term = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]]
# 循环
while True:
# 按键判断
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# 画
screen.fill(white)
# 圈
for i in chess_pos:
pygame.draw.circle(screen, red, [i[0] + 150, i[1] + 150], 120, 5)
# 叉
for i in chess_pos1:
pygame.draw.line(screen, blue, [i[0] + 30, i[1] + 30], [i[0] + 270, i[1] + 270], 5)
pygame.draw.line(screen, blue, [i[0] + 270, i[1] + 30], [i[0] + 30, i[1] + 270], 5)
# 网格
for i in range(1, 3):
pygame.draw.line(screen, black, [i * 300, 0], [i * 300, 900])
for i in range(1, 3):
pygame.draw.line(screen, black, [0, i * 300], [900, i * 300])
pygame.display.flip()
# 鼠标信息
pos = pygame.mouse.get_pos()
pre = pygame.mouse.get_pressed()
# 下棋
if play_chess == 0:
first = random.randrange(0, 3)
if first == 1:
print("机器先下")
else:
print("你先下")
play_chess = first
elif play_chess == 1:
print("轮机器下了")
yn = False
j += 1
for i in win_term:
x = [lattice[i[1]], lattice[i[2]], lattice[i[0]]]
if lattice[i[0]] == 2 and lattice[i[1]] == 2 and not yn:
if lattice[i[2]] == 0:
lattice[i[2]] = 1
if i[2] == 0:
chess_pos.append([0, 600])
yn = True
elif i[2] == 1:
chess_pos.append([300, 600])