百万英雄类答题游戏的程序员打开方式

百万英雄类答题游戏的程序员打开方式

看了《程序员如何玩转《冲顶大会》?》大受启发,刚好前几天研究了下微信跳一跳的辅助,正好可以用上。

思路很明确,把答案截图pull过来,通过OCR识别成文字后再放到百度搜索。记过几番尝试后,一些容易搜索的问题还是是可以搜索答案的。

目前它是手动的,也就是说每次答案出现,手动执行脚本返回答案。同样由于个别题目原因(如某个词有多少笔画),不是每次都能搜出来。这时就考验你的手速和运气了。

实现语言python,用到的类库如下:

  1. PIL
  2. pytesseract(图片识别库)
  3. BeautifulSoup(页面解析)

文字识别引擎需单独安装,参见Python人工智能之图片识别,Python3一行代码实现图片文字识别以及mac上文字识别 Tesseract-OCR for mac

主体代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import os
from PIL import Image
import pytesseract
from urllib.request import urlopen
import urllib.request
from bs4 import BeautifulSoup

DEFAULT_WIDTH = 720
DEFAULT_HEIGHT = 1280


def main():
# 720*1280分辨率坐标
left_top_x = 30
left_top_y = 200
right_bottom_x = 680
right_bottom_y = 380

# 1. 截图
os.system('adb shell screencap -p /sdcard/answer.png')
os.system('adb pull /sdcard/answer.png answer.png')

# 2. 截取题目并文字识别
image = Image.open('answer.png')
crop_img = image.crop((left_top_x, left_top_y, right_bottom_x, right_bottom_y))
crop_img.save('crop.png')
text = pytesseract.image_to_string(crop_img, lang='chi_sim')
print(text)

# 3. 去百度知道搜索
text = text[2:] # 把题号去掉
# text = '一亩地大约是多少平米'
wd = urllib.request.quote(text)
url = 'https://zhidao.baidu.com/search?ct=17&pn=0&tn=ikaslist&rn=10&fr=wwwt&word={}'.format(
wd)
print(url)
result = urlopen(url)
body = BeautifulSoup(result.read(), 'html5lib')
good_result_div = body.find(class_='list-header').find('dd')
second_result_div = body.find(class_='list-inner').find(class_='list')
if good_result_div is not None:
good_result = good_result_div.get_text()
print(good_result.strip())

if second_result_div is not None:
second_result = second_result_div.find('dl').find('dd').get_text()
print(second_result.strip())


if __name__ == '__main__':
main()

文字识别需经训练,训练越多结果越准。

我把代码放到github上了,可围观hq-answer-assist

要想实现更智能化,有个思路是不停的截图(1秒一次),一旦截到答题页(可以用答题页的色差来做),做文字识别后百度,将百度后的结果与选项做比较,哪个出现次数最多哪个就是最佳答案,这里可以加个判断,如果特别确定直接模拟点击事件选答案,不确定就手工。

有同学提到分析请求,也是个思路,后续可以研究。

欢迎探讨其他更好的实现方式。

分享到:
0%