python人机对战井字棋 欢迎来挑战(难度极高)

这篇博客介绍了如何使用Python的pygame库开发一款难度极高的井字棋游戏,玩家可以与计算机进行对战。首先,需要通过pip安装pygame库,然后详细解析了源码的实现过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 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])
                  
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值