-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfunctions.py
239 lines (201 loc) · 6.85 KB
/
functions.py
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 9 16:00:44 2018
@author: ainur
"""
import time
from pynput.keyboard import Key, Controller
import numpy as np
import os
import re
from pandas import DataFrame
from datetime import datetime
import mss.tools
import mss
try:
from PIL import Image
except ImportError:
import Image
try:
from tqdm import tqdm
except ImportError:
def tqdm(x,*args, **kwargs):
return x
def getflist(path='./data/numbers',exclude_prefixes =('__', '.')): # exclusion prefixes):
flist = list()
for (dirpath, dirnames, filenames) in os.walk(path):
flist += [os.path.join(dirpath, file) for file in filenames
if not file.startswith(exclude_prefixes)]
return(flist)
def getfit(flist, max_iter=500):
from sklearn.linear_model import SGDClassifier
ar=[]
Y=[]
for fl in flist:
temp=np.array(Image.open(fl).convert('L')).reshape(-1,)
ar.append(temp)
# re.search( '/(.*)/', fl).group(1) if fl doesnt start with ./
Y.append(re.search( '/.*/(.*)/', fl).group(1) )
ar=np.array(ar)
sgd_clf = SGDClassifier(max_iter=max_iter)
sgd_clf.fit(ar, Y)
return(sgd_clf)
#from itertools import product
def getkey(M):
keys=[Key.right, Key.down, Key.up, Key.left]
cols=['k1','k2','s','nanc', 's0']
solutions=DataFrame(columns=cols)
for k1 in [Key.right, Key.down, Key.up] :
temp=M.copy(deep=True)
temp2=nt(temp,k1)
if (not temp2.equals(M) ):
temp2=temp2.apply(np.log2)
temp2=temp2.sum().sum()
for k2 in keys:
temp=nt(nt(temp,k1),k2)
temp=temp.apply(np.log2)
stemp=temp.sum().sum()
counttemp=nancount(temp)
solutions=solutions.append(DataFrame([[k1,k2,stemp,counttemp, temp2]],
columns=cols),ignore_index=True)
solutions=solutions.loc[ solutions.s==solutions.s.min(),:]
solutions=solutions.loc[ solutions.nanc==solutions.nanc.min(),:]
solutions.loc[solutions.s0==solutions.s0.min(),:]
if len (solutions)==0:
k1=Key.left
else:
k1=solutions.iloc[0,0]
return(k1)
def mv(k):
keyboard = Controller()
keyboard.press(k)
keyboard.release(k)
return(True)
#next predicting
def nt (m, key):
if key==Key.down:
m=rotated(m)
elif key==Key.right:
m=rotated(rotated(m))
elif key==Key.up:
m=rotated(rotated(rotated(m)))
for i in range(4):
temp=m.loc[i, list(map(lambda x: ~np.isnan(x), m.loc[i,:] )) ]
temp=np.asarray(temp)
if len(temp)>1:
j=0
while j <(len(temp)-1) :
# print(i,j, temp)
if temp[j]==temp[j+1]:
temp=np.concatenate( (temp[0:j],float(2*temp[j]),temp[(j+2):] ), axis=None)
j=j+1
temp=np.asarray(temp).astype(float)
m.loc[i,:]=np.full(4,np.nan)
m.loc[i,:(len(temp)-1)]=temp
if key==Key.up:
m=rotated(m)
elif key==Key.right:
m=rotated(rotated(m))
elif key==Key.down:
m=rotated(rotated(rotated(m)))
return(m)
def rotated(df):
cols=df.columns
df=df.T.reset_index().reindex(columns=np.arange(3,-1,-1))
df.columns=cols
return(df )
from functools import reduce
def nancount(M):
return(np.count_nonzero(~np.isnan(reduce(lambda a, x: a + x, (M.values).tolist()))))
def getpredict(sgd_clf_score,score='', maxlength=15, sleep=5):
if score=='':
score=getscore(sleep=sleep)
color=[187, 173, 160]
colorcol=np.array([[color]*19]).astype('uint8')
ld=getld(score)
score=''
for j in ld:
temp=np.concatenate( (j, np.repeat( [colorcol], maxlength-len(j) , axis=1)[0]))
temp=np.reshape(arflat(temp), [-1,maxlength,3], order='F')
# Image.fromarray(temp).convert("RGB").save('temp.png')
# temp=cv2.imread('temp.png',0)
temp=np.array(Image.fromarray(temp).convert("L"))
score=score+(sgd_clf_score.predict(temp.reshape(1,-1))[0])
os.remove('temp.png')
return(score)
#pright=710
#ptop=185
#pwidth=100
#pheight=19
pright=910
ptop=185
pwidth=100
pheight=19
def getscore(sleep=5,pright=pright,ptop=ptop,pwidth=pwidth,pheight=pheight):
time.sleep(sleep)
with mss.mss() as sct:
# The screen part to capture
monitor = {"top": ptop, "left": pright-pwidth, "width": pwidth, "height": pheight}
output = "temp/"+str(datetime.now().time()).format(**monitor)
# Grab the data
sct_img = sct.grab(monitor)
# Save to the picture file
mss.tools.to_png(sct_img.rgb, sct_img.size, output=output)
print(output)
return(output)
#if the column consist of one color
def monocol(col):
for i in col:
for j in range(3):
if i[j]!=col[0][j]:
return (False)
return (True)
from itertools import chain
def arflat(temp):
temp=[k for k in temp]
temp= list(chain(*temp))
return(temp)
def getld(file, pheight=pheight):
img = Image.open(file)
arr = np.array(img)
temp=np.reshape(arflat(arr), [-1,len(arr),3], order='F')
digits=0
previous=monocol(temp[0])
layer=1
ld=[]
ld.append([])
while layer!=(len(temp)):
current=monocol(temp[layer])
if (current!=previous) & current:
digits=digits+1
ld.append([])
if not current:
ld[digits].append(temp[layer])
previous=current
layer=layer+1
del ld[digits]
return(ld)
def getGamePixels(imgsarray):
#различающиеся пиксели столбиков\строк в последовательных скринах
ty=[np.nonzero(imgsarray[i+1]-imgsarray[i])[0] for i in range(len(imgsarray)-1) ]
#самые частые пиксели
unique_elements, counts_elements = np.unique(np.hstack(ty), return_counts=True)
#создаем из этих данных датафрейм для дальнейшей работы
ty=DataFrame({'pix':unique_elements, 'count': counts_elements} )
#максимальное кол-во итераций, которое мы себе можем позволить ty['count'].max()
from pandas import concat
for i in range( ty['count'].max(), 0, -1):
temp=ty.loc[ty['count']>=i, :]
t=np.array(concat([temp, temp.iloc[[-1],:]] ).pix) - \
np.array(concat([temp.iloc[[0],:], temp] ).pix)
n=len(t[t>1])
# if n==4:
# if ( (n==4) & (len(imgsarray[0]==1050) ) ) :
# break
# if ( (n==3) & (len(imgsarray[0]==1680) ) ) :
if n==3:
break
if i==1:
print('Not enought')
return (ty.loc[ty['count']>=i, 'pix'].values)