当前位置:网站首页>[AI card player] for the first time to see such an "exciting" landowner, the key factor for a high winning rate is

[AI card player] for the first time to see such an "exciting" landowner, the key factor for a high winning rate is

2022-06-10 23:58:00 Programmer pear

Preface

author :“ Programmer pear ”

** The article brief introduction **: This article mainly makes a AI The landlords' automatic card player .

** Article source code access **: In order to thank everyone who pays attention to me, the project source code of each article is distributed free of charge

Enjoy drops

Click here for the blue line font , If you need any source code, remember to say the title and name ! I can also !

Welcome friends give the thumbs-up 、 Collection 、 Leaving a message.
 

Text

As a national recreational game , Landlords never lack attention .

  Xiaobian likes fighting landlords in his spare time , Open a small black , I still remember when I was in college, one dormitory could have two tables ~ ha-ha

Ha .jpg As a little fan , Xiaobian will take you to write a paragraph today AI Card player ! From then on, you will win a lot of money “ Wealth ”, Reach the peak of life !

One 、 Effect display

  The effect of the card player ——

Two 、 Code steps

Third party library configuration

torch==1.9.0
GitPython==3.0.5
gitdb2==2.0.6
PyAutoGUI==0.9.50
PyQt5==5.13.0
PyQt5-sip==12.8.1
Pillow>=5.2.0
opencv-python
rlcard

1) Thinking analysis

UI Design layout ——

 Show three cards 
 Show AI Character play data area , Home licensing data area , The next licensing data area , The winning area of this game 
AI Player's hand area 
AI The dealer starts to stop 

Hand and play data identification ——

 At the beginning of the game, according to the screen position , Screenshot recognition AI Player's hand and three cards 
 Confirm the relationship between the three , Identify the roles of landlords and farmers , Confirm the relationship between teammates and opponents 
 Identify the cards played by the three players in each round , Refresh the display area 

AI Licensing scheme output ——

 Load training good AI Model , Initialize the game environment 
 Each round is judged , According to the previous licensing data, the optimal licensing decision is given 
 Automatically refresh the player's remaining hand and the prediction of the winning rate of the game 

2) Code parsing

It uses pyqt5, Carry out simple UI Layout design , The core code is as follows :

def retranslateUi(self, Form):
    _translate = QtCore.QCoreApplication.translate
    Form.setWindowTitle(_translate("Form", "AI Happy game "))
    self.WinRate.setText(_translate("Form", " odds :--%"))
    self.InitCard.setText(_translate("Form", " Start "))
    self.UserHandCards.setText(_translate("Form", " Hand "))
    self.LPlayedCard.setText(_translate("Form", " Home licensing area "))
    self.RPlayedCard.setText(_translate("Form", " The next licensing area "))
    self.PredictedCard.setText(_translate("Form", "AI Playing area "))
    self.ThreeLandlordCards.setText(_translate("Form", " Three cards "))
    self.Stop.setText(_translate("Form", " stop it "))

The effect is as follows :

  distinguish AI Player's hand and three cards .

We can intercept the fixed position of the game screen , Into the trained YOLOv5 The Internet , To identify the current AI Player's hand and three cards

a hand . The core code is as follows :

def find_three_landlord_cards(self, pos):
        three_landlord_cards_real = ""
        img = pyautogui.screenshot(region=pos)
        three_landlord_cards_real=detect_cards(img)
        return three_landlord_cards_real
 
def find_my_cards(self, pos):
        user_hand_cards_real = ""
        img = pyautogui.screenshot(region=pos) 
        # img2 = color.rgb2gray(img)
        user_hand_cards_real=detect_cards(img)
        return user_hand_cards_real
def detect_cards(img):
    path="datas\cards.png"
    img.save(path)
    raw_cards=detect(source=path)
    replace_cards=[replace_num[i] if i in replace_num else i for i in raw_cards]
    list_cards = sorted(replace_cards, key=lambda x: ranks_value[x])
    cards=("".join(list_cards))
    return cards
 
def detect()
    # Initialize
    set_logging()
    # device = select_device(device)
    device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")# If you have any gpu If available, use gpu
    # half &= device.type != 'cpu'  # half precision only supported on CUDA
    w = weights[0] if isinstance(weights, list) else weights
    classify, pt, onnx = False, w.endswith('.pt'), w.endswith('.onnx')  # inference type
    stride, names = 64, [f'class{i}' for i in range(1000)]  # assign defaults
    if pt:
        model = attempt_load(weights, map_location=device)  # load FP32 model
        stride = int(model.stride.max())  # model stride
        names = model.module.names if hasattr(model, 'module') else model.names  # get class names
        if half:
            model.half()  # to FP16
        if classify:  # second-stage classifier
            modelc = load_classifier(name='resnet50', n=2)  # initialize
            modelc.load_state_dict(torch.load('resnet50.pt', map_location=device)['model']).to(device).eval()
    elif onnx:
        check_requirements(('onnx', 'onnxruntime'))
        import onnxruntime
        session = onnxruntime.InferenceSession(w, None)
    dataset = LoadImages(source, img_size=imgsz, stride=stride)
    bs = 1  # batch_size
    vid_path, vid_writer = [None] * bs, [None] * bs
    t0 = time.time()
 
    imgsz = check_img_size(imgsz, s=stride)  # check image size
    for path, img, im0s, vid_cap in dataset:
        if pt:
            img = torch.from_numpy(img).to(device)
            img = img.half() if half else img.float()  # uint8 to fp16/32
        elif onnx:
            img = img.astype('float32')
        img /= 255.0  # 0 - 255 to 0.0 - 1.0
        if len(img.shape) == 3:
            img = img[None]  # expand for batch dim
        # Inference
        t1 = time_sync()
        if pt:
            pred = model(img, augment=augment, visualize=visualize)[0]
        elif onnx:
            pred = torch.tensor(session.run([session.get_outputs()[0].name], {session.get_inputs()[0].name: img}))
        # NMS
        pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det)
        t2 = time_sync()
        # Second-stage classifier (optional)
        if classify:
            pred = apply_classifier(pred, modelc, img, im0s)
        # Process predictions
        for i, det in enumerate(pred):  # detections per image
            p, s, im0, frame = path, '', im0s.copy(), getattr(dataset, 'frame', 0)
            p = Path(p)  # to Path
            gn = torch.tensor(im0.shape)[[1, 0, 1, 0]]  # normalization gain whwh
            imc = im0.copy() if save_crop else im0  # for save_crop
            if len(det):
                # Rescale boxes from img_size to im0 size
                det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()
                
                lists=[]
                # Print results
                for c in det[:, -1].unique():
                    n = (det[:, -1] == c).sum()  # detections per class
                    for i in range(n):
                        lists.append(names[int(c)])
        return lists

Effect display :

 

The landlord 、 The landlord's house 、 The landlord's family :

Similarly, we can take a screenshot of the game , Identify the icon of the landlord , Confirm the landlord role . The core code is as follows :

#  Find the landlord role 
def find_landlord(self, landlord_flag_pos):
    for pos in landlord_flag_pos:
        result = pyautogui.locateOnScreen('pics/landlord_words.png', region=pos, confidence=self.LandlordFlagConfidence)
        if result is not None:
            return landlord_flag_pos.index(pos)
    return None

Effect display :

So we can get players AI Hand , Other players hand cards ( forecast ), The landlord has three cards , The relationship between the three roles , Playing cards smoothly

order .

play 、 Don't out 、 Wait state :

Similarly, we can take a screenshot of the game , Identify other people's playing areas , Judge the card playing status . The core code is as follows :

labels=[' wait for ',' play ',' Don't out ']
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")# If you have any gpu If available, use gpu
model = models.resnet50(pretrained=False)
fc_inputs = model.fc.in_features
model.fc = nn.Sequential(
    nn.Linear(fc_inputs, 256),
    nn.ReLU(),
    nn.Dropout(0.4),
    nn.Linear(256, config.NUM_CLASSES),
    nn.LogSoftmax(dim=1)
)
pthfile=config.TRAINED_BEST_MODEL
checkpoint = torch.load(pthfile)
model.load_state_dict(checkpoint['model'])
# optimizer.load_state_dict(checkpoint['optimizer'])
start_epoch = checkpoint['epoch']
# test(model, test_load)
model.to(device).eval()
def detect_pass(pos):
    
    img = pyautogui.screenshot(region=pos) 
    # path="datas\state.png"
    time =datetime.datetime.now().strftime(TIMESTAMP)
    path="datas\states\state"+'_'+time+'.png'
    img.save(path)
    # path="datas/states/state_20210807160852.png"
    src = cv2.imread(path) # aeroplane.jpg
    image = cv2.resize(src, (224, 224))
    image = np.float32(image) / 255.0
    image[:,:,] -= (np.float32(0.485), np.float32(0.456), np.float32(0.406))
    image[:,:,] /= (np.float32(0.229), np.float32(0.224), np.float32(0.225))
    image = image.transpose((2, 0, 1))
    input_x = torch.from_numpy(image).unsqueeze(0).to(device)
    pred = model(input_x)
    pred_index = torch.argmax(pred, 1).cpu().detach().numpy()
    pred_index=int(pred_index)
    print(pred_index)
    return pred_index

  Effect display :

  Come here , Whole AI The card playing process of landlords has been basically completed .

summary

When all environment configurations are complete , After the coordinate position of each area is confirmed to be correct , Now we can run the program directly , Test the effect

~ First we run AI Dealer program , Open the happy Landlords game interface , Enter the game . When the player is in position , Hand out

、 BI , After the landlord's identity is confirmed , We can click the start button in the picture , Give Way AI To help us fight the landlord .

If you like it, remember to ask me for the source code !

Follow Xiaobian for more wonderful content ! Remember to click on the portal

Remember Sanlian ! If you need packaged source code + Free sharing of materials ! Portal

原网站

版权声明
本文为[Programmer pear]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/161/202206102242248038.html