21-point game with Python for auto-play Npubits

Source: Internet
Author: User
Tags button type urlencode python script
21-Point Main Page

---

( there is no link here, the user directly on the site first click 21 points, the address bar is the link.) )

Key points to be aware of

( key points used to fetch data when writing code )

1. Wait for the start

If the previous 21 points are not over (temporarily without the opponent on line), then can not start, need to wait until the end. If you need to wait, the main page contains the following content

<button type="submit" class="btn btn-default">刷新</button>
2. You can start

If you can start the game, the main page contains the following content

<button type="submit" class="btn btn-primary">开始游戏!</button>
3. Start at 21 points

Post data to the main page

game: hit,start: yes
4. Judging points

Determines the page content returned by the main page after each operation. The HTML style of the points is as follows:

<b>点数 = 16</b>
5. Continue to touch the card

Post data to the main page

game: hit
6. Stop touching the card

Post data to the main page

game: stop
Python Scripting Ideas
    1. Wait for the start.
    2. Start at 21 o '.
    3. Determine the number of points.
    4. If the points are greater than 20, return to the 1th step.
    5. If the points are greater than 17, go to the 8th step. (17 variable, just I think 17 point is big enough)
    6. If the point is less than or equal to 17, go to the 7th step.
    7. Continue to touch the card and return to the 3rd step.
    8. Stop touching the card and go back to the 1th step.

toulanboy-http://www.cnblogs.com/toulanboy/

Code Implementation 1. Key logic: Start-touch-stop
# (* * This does not provide a link, the user directly on the site first click 21 points, the Address bar link is. * *) URL = '----' #不停地玩21点while True: #先看之前的是否结束了 result = GetData (URL) time.sleep (5) # TOULANBOY-HTTP://WWW.CNBL ogs.com/toulanboy/if result = = 0: #如果还没结束, continue to refresh print "Before the end, wait for" elif result = = 1: #如果结束了, then start the game poi        NT = postdata (URL, startvalues) #发出 "Start Game" request print "started, current points =%d"% point #大于20点, the system will automatically end, so here I only need to touch the card less than 21 points                While points <= 20:if point >=: #我认为只要大于17点我满足了, so it is more than 17 stops to touch the card Time.sleep (1)            PostData (URL, stopvalues) #发出 "Stop Touch" request print "Stop touch card, current number =%d"% Point Break                else: #小于17点则继续摸牌 time.sleep (1) point = PostData (URL, hitvalues) #发出 "continue to touch the card" request Print "Touch again, current points =%d"% point print "This is the end, the current number of points =%d"% point else: #出现异常, stop the game.        Wait for the slag to look at the log to see where the problem. SendEmail ("xxx@qq.com", "Some errors occurred in Python script for Npubits", "Some errors occurred in PYthon script for Npubits ') break 
2. Use GET request to determine if you can start the game
#function - Get网页#若网页显示之前的没结束,则返回0#若网页显示可以开始新的一局,则返回1#其它情况返回-1def getData(url):    headers = {        'User-Agent' : '-',#建议设置        'cookie':'-'#我没做登陆,所以手动弄cookie        }    try:        response = requests.get(url, headers=headers)        indexHtmlCode = response.text        indexHtmlCode =  indexHtmlCode.encode('utf-8')                #判断是否有刷新按钮,若有,说明上局没结束        freshRegex = r'刷新</button>'        result = re.findall(freshRegex, indexHtmlCode)        if result:            return 0# toulanboy - http://www.cnblogs.com/toulanboy/                #判断是否有开始游戏按钮,若有,说明可以开始游戏        beginRegex = r'开始游戏!</button>'        result = re.findall(beginRegex, indexHtmlCode)        if result:            return 1        return -1    except Exception as e:        return -1
3. Start/touch/Stop action with POST request

toulanboy-http://www.cnblogs.com/toulanboy/

# # # Different actions need the same data # start the game startvalues = {"Game": "Hit", "Start": "Yes"}# continue to touch the card hitvalues = {"Game": "Hit"}# stop to touch the card Stopvalu Es = {"Game": "Stop"} #function-post page # If you start and touch a card, then return the number of Points # Page no points (stop touch operation will appear), then return 0# exception, return -1def postdata (URL, values): DD = Urllib.urlencode (values) headers = {"Content-length": Str (len (DD)), "Content-type": "application/x -www-form-urlencoded ", ' Cache-control ': ' max-age=0 ', #上述三个参数其实应该不用手动添加, it is possible that the request library will help us Add.            Pending verification. ' User-agent ': '-', #自己补充 ' cookie ': '-' #自己补充} try:response = Requests.post (URL, data=dd,he aders=headers) Indexhtmlcode = Response.text Indexhtmlcode = Indexhtmlcode.encode (' utf-8 ') # Toulanboy-htt p://www.cnblogs.com/toulanboy/# View the number of pages returned Pointregex = R ' points \s?=\s?        (\d*) < ' result = Re.findall (Pointregex, Indexhtmlcode) if Result:return int (result[0]) Else:return 0 except Exception as E:return-1
Full code

Added logging and email alerts in the complete code for ease of maintenance

#!/usr/bin/python# coding=utf-8# time: 2018-08-22# toulanboy# reason: Want to realize auto play Npubits 21 points game import Requestsimport Reimport Urllibimport time Import loggingimport smtplibfrom email.mime.text import mimetext# configuration log logging.basicconfig (Filename= ' My.Log ', format= ' [% (asctime) s-% (filename) s-% (levelname) s:% (message) s] ', level = Logging.info,filemode= ' a ', datefmt= '%y-%m-%d%i:%m:%s%p ') # # # Different actions need the same data # start the game startvalues = {"Game": "Hit", "Start": "Yes"}# continue to touch the card hitvalues = {"Gam E ":" Hit "}# stop Touch Card stopvalues = {" Game ":" Stop "}# toulanboy-http://www.cnblogs.com/toulanboy/#function-post Page # If you start and touch the card, Return number # Page no points (Stop touch action will appear), return 0# exception, return -1def postdata (URL, values): DD = Urllib.urlencode (values) headers = {" Content-length ": Str (len (DD))," Content-type ":" application/x-www-form-urlencoded ", ' Cache-control ': ' m Ax-age=0 ', #上述三个参数其实应该不用手动添加, it's possible that the request library will help us Add.            Pending verification. ' User-agent ': '-', #自己补充 ' cookie ': '-' #自己补充} try:response = Requests.post (URL, data=dd,headers=headers) Indexhtmlcode = Response.text Indexhtmlcode = Indexhtmlcode.encode (' Utf-8 ') # Extract Web Backbone, log in (convenient for later analysis) BODY = Re.findall (R ' <div\s?id=\ ' main\ ' \s?class=\ ' well\s?no-border-radius\ ' &GT;.*?&L T;/div> ', Indexhtmlcode, re. S) if Body:logging.info (Body[0]) Else:logging.info (indexhtmlcode) # View the point of the returned page Number Pointregex = R ' points \s?=\s?        (\d*) < ' result = Re.findall (Pointregex, Indexhtmlcode) if Result:return int (result[0]) Else:return 0 except Exception as E:logging.error (e) return-1#function-get page # If the page doesn't end before it appears , return 0# If the page display can start a new inning, then return to a # other case return -1def getData (URL): headers = {' user-agent ': '-', #建议设置 ' cookie ': '-' #我没做登        Land, so manual cookie} try:response = Requests.get (URL, headers=headers) Indexhtmlcode = Response.text Indexhtmlcode = Indexhtmlcode.encode (' utf-8 ') #判断是否有刷新按钮, if any, sayThe bureau's not over. Freshregex = R ' Refresh </button> ' result = Re.findall (Freshregex, Indexhtmlcode) if result: return 0 #判断是否有开始游戏按钮, if any, instructions can start game Beginregex = R ' Start game! </button> ' result = Re.findall (Beginregex, Indexhtmlcode) if Result:return 1 # if market        Loginregex = R ' You have not logged in </body> ' result = Re.findall (Loginregex, Indexhtmlcode) If Result:return 2 # If the cookie is not expired, you will need to print the current error message (record the returned web page source code) to make it easy to find the wrong Logging.error (INDEXHTMLC ODE) except Exception as E:logging.error (e) return-1# email (recipient, message subject, message body) def sendEmail (_to, subject, M Aintext): _user = "-" #登录的163邮箱 _pwd = "-" #163邮箱授权码 msg = Mimetext (mainText) #邮件正文 msg["Subject"] = Sub Ject #邮件主题 msg["from") = _user #发件人 msg["to"] = _to #收件人 try:s = smtplib. Smtp_ssl ("smtp.163.com", 465) S.login (_user, _pwd) #登录 S.SendMail (_user, _to, msg.as_string ()) #发送 s.quit () #退出登录 logging.info ("Mail sent successfully!")    Print "Mail sent successfully!" Except Smtplib. Smtpexception,e:logging.info ("message sent failed,%s"%e[0]) print "Mail send failed,%s"%e[0]# (* * There is no link here, the user directly on the site first click 21 points, the Address bar link is. * *) URL = '----' #不停地玩21点while True: #先看之前的是否结束了 result = GetData (URL) time.sleep (5) If result = = 0: #如果还没结束, then        Continue to refresh print "Before the end, waiting for" elif result = = 1: #如果结束了, then start game point = PostData (URL, startvalues) #发出 "Start Game" request        Logging.info ("started, current points =%d"% point) print "started, current number =%d" point #大于20点, the system will automatically end, so here I only need to be less than 21 points of the case to touch the card                While points <= 20:if point >=: #我认为只要大于17点我满足了, so it is more than 17 stops to touch the card Time.sleep (1) PostData (URL, stopvalues) #发出 "Stop Touch" request Logging.info ("Stop touch card, current points =%d"% point) print "Stop  Stop hand, current number =%d "% Point Break else: #小于17点则继续摸牌 Time.sleep (1) points = PostData (URL, Hitvalues) #发出 "continue to touch the card" request Logging.info ("Touch the card again, the current point =%d"% ") print" again touch the card, the current number =%d "% PO int Logging.info ("This game is over, current points =%d"% point) print "This is the end of the game, current points =%d"% point else: #出现异常, stop Game.        Wait for the slag to look at the log to see where the problem. SendEmail ("xxx@qq.com", "Some errors occurred in Python script for Npubits", "Some errors occurred in Python script for NP Ubits ") Break

toulanboy-http://www.cnblogs.com/toulanboy/

Complete.

Python has just learned a few fur, code habits may not be good, I hope the big guy to forgive.
If the big guy is willing to give advice, thank you very much.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.