吾爱破解 - LCG - LSG |安卓破解|病毒分析|www.52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 2494|回复: 15
收起左侧

[Python 转载] 人机对战井字棋

  [复制链接]
Lthero 发表于 2020-12-31 15:51
用pygame实现交互,程序比较简陋,有不足之处欢迎大家批评指正

AI的移动思想

逐个遍历每个空的格子,

如果某个格子落子后AI能赢就下,

如果对方能赢AI就堵住。

代码如下
[Python] 纯文本查看 复制代码
__author__ = 'lthero'

import pygame
from pygame import *
import random as ra

pygame.init()

white = (255, 255, 255)
black = (0, 0, 0)
size = width, height = 600, 600
screen = pygame.display.set_mode(size)
points = [[0, 0, 0],
          [0, 0, 0],
          [0, 0, 0]]
x = 0
y = 0
flag = 1
lst = []
lst_mine = []
lst_android = []
count = 0
text = pygame.font.SysFont('宋体', 50)
Play_score = 0
AI_score = 0


def draw_restart():
    steps = [(400, 450), (400, 500), (550, 500), (550, 450)]
    pygame.draw.polygon(screen, black, steps, 1)
    text_x = text.render("AGAIN?", 1, black)
    screen.blit(text_x, (410, 460))


def draw_img(player, x, y):
    # 玩家
    if player == 1:
        pygame.draw.circle(screen, black, (x, y), 40, 1)
    # 机器
    else:
        pygame.draw.rect(screen, black, ((x - 20, y - 20), (50, 50)), 1)


def draw_score():
    text_1 = pygame.font.SysFont('宋体', 30)
    text_player_score = text_1.render('PLAYER SCORE ' + str(Play_score), 1, black)
    text_AI_score = text_1.render('AI SCORE     ' + str(AI_score), 1, black)
    screen.blit(text_player_score, (410, 10))
    screen.blit(text_AI_score, (410, 40))


def draw_back():
    screen.fill(white)
    steps = [(100, 100), (100, 400), (400, 400), (400, 100)]
    pygame.draw.polygon(screen, black, steps, 1)
    pygame.draw.lines(screen, black, False, [(100, 200), (400, 200)])
    pygame.draw.lines(screen, black, False, [(100, 300), (400, 300)])
    pygame.draw.lines(screen, black, False, [(200, 100), (200, 400)])
    pygame.draw.lines(screen, black, False, [(300, 100), (300, 400)])


def check_win(tab):
    return ((points[0][0] == tab and points[0][1] == tab and points[0][2] == tab) or
            (points[1][0] == tab and points[1][1] == tab and points[1][2] == tab) or
            (points[2][0] == tab and points[2][1] == tab and points[2][2] == tab) or
            (points[0][0] == tab and points[1][0] == tab and points[2][0] == tab) or
            (points[0][1] == tab and points[1][1] == tab and points[2][1] == tab) or
            (points[0][2] == tab and points[1][2] == tab and points[2][2] == tab) or
            (points[0][0] == tab and points[1][1] == tab and points[2][2] == tab) or
            (points[0][2] == tab and points[1][1] == tab and points[2][0] == tab)
            )


def winner():
    # AI
    if check_win(100):
        return 100
    elif check_win(1):
        return -100


def is_full():
    fl = 0
    for i in range(3):
        for j in range(3):
            if points[i][j] != 0:
                fl += 1

    return fl


def AI_move():
    # 一步能赢
    for i in range(3):
        for j in range(3):
            if points[i][j] == 0:
                points[i][j] = 100
                if check_win(100):
                    return (i, j)
                else:
                    points[i][j] = 0
    # 堵上
    for i in range(3):
        for j in range(3):
            if points[i][j] == 0:
                points[i][j] = 1
                if check_win(1):
                    return (i, j)
                else:
                    points[i][j] = 0

    # 占中间
    if points[1][1] == 0:
        return (1, 1)

    # 占四角
    temp = []
    for i in (0, 2):
        for j in (0, 2):
            if points[i][j] == 0:
                temp.append((i, j))
    if len(temp) != 0:
        return ra.choice(temp)

    # 占四边
    for i in ((0, 1), (1, 0), (1, 2), (2, 1)):
        if points[i[0]][i[1]] == 0:
            temp.append((i[0], i[1]))
    if len(temp) != 0:
        return ra.choice(temp)


def draw_all():
    draw_back()
    draw_score()
    for i in lst:
        draw_img(i[0], i[1], i[2])
    if flag == 100:
        text_conent = text.render("AI win", 1, black)
        screen.blit(text_conent, (220, 50))
    elif flag == -100:
        text_conent = text.render("You win", 1, black)
        screen.blit(text_conent, (220, 50))
    elif flag == 123:
        text_conent = text.render("TIE", 1, black)
        screen.blit(text_conent, (220, 50))
    if flag == 123 or flag == 100 or flag == -100:
        draw_restart()


def play():
    global flag, AI_score, Play_score
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                exit()
            if event.type == MOUSEBUTTONDOWN:
                x, y = pygame.mouse.get_pos()
                if 400 < x < 550 and 450 < y < 500:
                    lst.clear()
                    for i in range(3):
                        for j in range(3):
                            points[i][j] = 0
                    flag = 1
                if 100 <= x <= 400 and 100 <= y <= 400:
                    x = (x - 100) // 100
                    y = (y - 100) // 100
                    l_x = x * 100 + 150
                    l_y = y * 100 + 150
                    # player
                    if flag == 1:
                        if is_full() != 9:
                            if points[x][y] == 0:
                                points[x][y] = 1
                                lst.append((1, l_x, l_y))
                                if winner() == -100:
                                    flag = -100
                                    Play_score += 1
                                    print('player win')
                                else:
                                    flag = -1
                        else:
                            flag = 123

            if flag == -1:
                if is_full() != 9:
                    # 人机动
                    xx, yy = AI_move()
                    l_x = xx * 100 + 150
                    l_y = yy * 100 + 150
                    points[xx][yy] = 100
                    lst.append((2, l_x, l_y))
                    if winner() == 100:
                        flag = 100
                        AI_score += 1
                        print('AI win')
                    else:
                        flag = 1
                else:
                    flag = 123

        draw_all()
        pygame.display.flip()


if __name__ == '__main__':
    play()

免费评分

参与人数 4吾爱币 +3 热心值 +4 收起 理由
wokl168 + 1 + 1 谢谢@Thanks!
Xu__An + 1 + 1 我很赞同!
bset_user_id + 1 我很赞同!
yixuezhuihan + 1 + 1 谢谢@Thanks!

查看全部评分

本帖被以下淘专辑推荐:

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

风子是我 发表于 2021-1-1 21:58
微信图片_20210101215759.png 我赢了

 楼主| Lthero 发表于 2021-1-1 16:13
一步一念一顾 发表于 2020-12-31 17:06
请问有象棋的人机对战AI算法吗

象棋。。应该有的,不过实现起来复杂
象棋百科全书,有兴趣可以学习下
http://www.xqbase.com/computer/stepbystep1.htm
yixuezhuihan 发表于 2020-12-31 15:54
danielc 发表于 2020-12-31 16:03
lthero,干得不错
一步一念一顾 发表于 2020-12-31 17:06
请问有象棋的人机对战AI算法吗
guxing5920 发表于 2020-12-31 17:06

谢谢分享...收藏了
2623666 发表于 2020-12-31 17:31
这个没玩过呢  尝鲜一下
钢铁侠_123 发表于 2020-12-31 17:47
那这样的话。。那不就没赢的希望了吗
mokson 发表于 2020-12-31 18:41
有个图片看,更完美吧。
dr-pan 发表于 2020-12-31 18:49
没玩过,不过可以 尝鲜一下
hshcompass 发表于 2020-12-31 20:18
谢谢分享。
先收藏,慢慢学习。
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则 警告:本版块禁止灌水或回复与主题无关内容,违者重罚!

快速回复 收藏帖子 返回列表 搜索

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2024-5-4 20:45

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表