GDTheuTrich

mainai

Apr 26th, 2023
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 11.00 KB | None | 0 0
  1. import datetime
  2. import glob
  3. import os
  4. import random
  5. import shutil
  6. import time
  7.  
  8. import cv2
  9. import mss
  10. import numpy as np
  11. import pandas as pd
  12. import tensorflow as tf
  13. from ImageClassf import ImageClassf
  14. from PIL import Image
  15. from PIL import ImageGrab
  16. from PIL import ImageOps
  17. from play import *
  18. from tensorflow.keras.layers import Conv2D
  19. from tensorflow.keras.layers import Dense
  20. from tensorflow.keras.layers import Dropout
  21. from tensorflow.keras.layers import Flatten
  22. from tensorflow.keras.layers import MaxPooling2D
  23. from tensorflow.keras.models import load_model
  24.  
  25. np.set_printoptions(suppress=True)
  26.  
  27. log_dir = "logs/fit/" + datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
  28.  
  29. Epsilon = 1 # Random probability
  30. Epsilon_Minimum_Value = 0.001 # epsilon의 최소값
  31. nbActions = 2 # Number of actions (jump, wait)
  32. EPOCH = 1001 # Game repeat count
  33. Hidden_Size = 100 # Hidden layer count
  34. Max_Memory = 5000 # Maximum number of game contents remembered
  35. batch_Size = 50 # Number of data bundles in training
  36. Grid_Size = 10 # Grid size
  37. nb_States = Grid_Size * Grid_Size # State count
  38. Discount = 0.9 # discount Value
  39. Learning_Rate = 0.2 # Learning_Rate
  40.  
  41. Reword_List = []
  42.  
  43. Replay_Meomry = 100000
  44.  
  45. reword = 0
  46.  
  47. RANDOM_STATE = 2020
  48.  
  49. tf.random.set_seed(RANDOM_STATE)
  50.  
  51. # Funciton
  52.  
  53. def load_model():
  54. try:
  55. bin_img_clssf = load_model("Model\\" + str(os.listdir("Model")[-1]))
  56. # bin_img_clssf = ImageClassf()
  57. print("Model load 성공")
  58. except:
  59. bin_img_clssf = ImageClassf()
  60. print("Model load 실패")
  61. return bin_img_clssf
  62.  
  63.  
  64. def average_hash(fname, size=16):
  65. img = Image.open(fname)
  66. img = img.convert("L")
  67. img = img.resize((960, 540), Image.ANTIALIAS)
  68. pixel_data = img.getdata()
  69. pixels = np.array(pixel_data)
  70. pixels = pixels.reshape((960, 540))
  71. avg = pixels.mean()
  72. diff = 1 * (pixels > avg)
  73. print(diff)
  74.  
  75.  
  76. # Full resolution of the emulator
  77. Game_Scr_pos = {"left": 16, "top": 54, "height": 483, "width": 789}
  78.  
  79. # Where to click the button on the emulator.
  80. Game_Src_Click_pos = [379, 283]
  81.  
  82.  
  83. def ImportImageDataSet():
  84. return tf.keras.preprocessing.image_dataset_from_directory(
  85. f"Photo/isPlay",
  86. validation_split=0.2,
  87. subset="training",
  88. shuffle=True,
  89. seed=RANDOM_STATE,
  90. label_mode="categorical",
  91. image_size=(640, 360),
  92. ), tf.keras.preprocessing.image_dataset_from_directory(
  93. f"Photo/isPlay",
  94. validation_split=0.2,
  95. subset="validation",
  96. shuffle=True,
  97. seed=RANDOM_STATE,
  98. label_mode="categorical",
  99. image_size=(640, 360),
  100. )
  101.  
  102.  
  103.  
  104. def VideoAnalyze(Video):
  105. Vidcap = cv2.VideoCapture(Video)
  106. success, image = Vidcap.read()
  107. count = 0
  108. while success:
  109. # save frame as JPEG file
  110. cv2.imwrite("frame%d.jpg" % count, image)
  111. success, image = Vidcap.read()
  112. print("Read a new frame: ", success)
  113. count += 1
  114.  
  115.  
  116. def PlayWithLearning():
  117. BringWindow()
  118. # load_model('Model\\20201218-003432model.h5')
  119. isGamePlay = load_model(f"Model/" + str(os.listdir("Model")[-1]))
  120. print(f"Model/" + str(os.listdir("Model")[-1]))
  121. # last_select = []
  122. isStart = 0
  123.  
  124. for a_epoch in range(EPOCH):
  125. with mss.mss() as sct:
  126. Game_Scr = np.array(sct.grab(Game_Scr_pos))[:, :, :3]
  127. """Below is a test to see if you are capturing the screen of the emulator."""
  128. # cv2.imshow('Game_Src', Game_Scr)
  129. # cv2.waitKey(1)
  130.  
  131. Game_Scr_numpy = np.resize(Game_Scr, (1, 640, 360, 3))
  132.  
  133. if ((tf.math.argmax(isGamePlay.predict(Game_Scr_numpy), axis=1)
  134. == 1) == True) is True:
  135. rnd = random.randint(1, 10)
  136. if isStart < 1:
  137. if not os.path.exists("tmp"):
  138. # os.makedirs('tmp')
  139. os.makedirs("tmp\\stay")
  140. os.makedirs("tmp\\up")
  141. try:
  142. dqn = load_model("Model\\Play\\game_play.h5")
  143. # dqn = ImageClassf
  144. is_load_model = True
  145. print("Model load 성공")
  146. except:
  147. # dqn = Q_net.QNet()
  148. is_load_model = False
  149. print("Model load 실패")
  150. play_time = time.time()
  151. print("Play...")
  152.  
  153. isStart += 1
  154.  
  155. if is_load_model is True:
  156. if rnd in [1, 2]:
  157. save_path = "stay"
  158. print("RAND Stay")
  159. elif rnd in [3, 4]:
  160. save_path = "up"
  161. Jump()
  162. print("RAND Up")
  163. else:
  164. tmp = tf.math.argmax(dqn.predict(Game_Scr_numpy),
  165. axis=1)
  166.  
  167. if tmp == 1:
  168. save_path = "stay"
  169. print("Stay")
  170. else:
  171. save_path = "up"
  172. Jump()
  173. print("Up")
  174. else:
  175. if rnd < 6:
  176. save_path = "stay"
  177. print("stay")
  178. elif rnd >= 6:
  179. save_path = "up"
  180. Jump()
  181. print("up")
  182. else:
  183. print("It's a problem")
  184. cv2.imwrite(f"tmp\\{save_path}\\{int(time.time())}.png",
  185. Game_Scr)
  186.  
  187. elif ((tf.math.argmax(isGamePlay.predict(Game_Scr_numpy), axis=1)
  188. == 1) == True) == False and isStart < 1:
  189. print("Go!")
  190.  
  191. elif ((tf.math.argmax(isGamePlay.predict(Game_Scr_numpy), axis=1)
  192. == 1) == True) == False and isStart > 1:
  193. play_time = time.time() - play_time
  194. print("What are you doing?")
  195.  
  196. # try:
  197. # for - in range(2):
  198. # print((os.listdir('tmp\\stay') + os.listdir('tmp\\up')).sort()[-1])
  199. # os.remove('tmp\\up\\' + os.listdir('tmp\\stay') + os.listdir('tmp\\up').sort(reverse=True)[-1])
  200. # os.remove('tmp\\stay\\' + os.listdir('tmp\\stay') + os.listdir('tmp\\up').sort(reverse=True)[-1])
  201. # os.remove('tmp\\stay\\' + os.listdir('tmp\\stay')[-1])
  202. # os.remove('tmp\\up\\' + os.listdir('tmp\\up')[-1])
  203. # for i in range(1):
  204. # if save_path == 'stay':
  205. # os.remove('tmp\\stay\\' + os.listdir('tmp\\stay')[-1])
  206. # elif save_path == 'up':
  207. # os.remove('tmp\\up\\' + os.listdir('tmp\\up')[-1])
  208. # except:
  209. # pass
  210.  
  211. # try:
  212. game_play = tf.keras.preprocessing.image_dataset_from_directory(
  213. "tmp",
  214. shuffle=True,
  215. seed=RANDOM_STATE,
  216. label_mode="categorical",
  217. image_size=(640, 360),
  218. )
  219.  
  220. # to Numpy
  221. print("TF Data to Numpy")
  222. for kkk in game_play.as_numpy_iterator():
  223. tmp = kkk
  224. x, y = kkk
  225. del tmp, kkk, game_play
  226.  
  227. # x = np.concatenate([x, ], axis=1)
  228. print(x.shape, y.shape)
  229. Q_net.QNet(
  230. x,
  231. tf.keras.activations.tanh(
  232. tf.nn.softmax([float(play_time), 85.0])),
  233. y,
  234. )
  235.  
  236. # dqn.fit(x, callbacks=[tf.keras.callbacks.TensorBoard(log_dir="logs/fit/play/" + datetime.datetime.now().strftime("%Y%m%d-%H%M%S"), histogram_freq=1)])
  237. # dqn.predict(x)
  238. # dqn.save('Model\\Play\\game_play.h5')
  239. # except:
  240. # pass
  241.  
  242. isStart = 0
  243. # shutil.rmtree("tmp")
  244. # time.sleep(0)
  245.  
  246. Retry()
  247. else:
  248. print(
  249. "This may issue is an issue where AI is slow to detect the image on the screen."
  250. )
  251. # time.sleep(0.42)
  252.  
  253.  
  254. def GamePlay():
  255. np.set_printoptions(suppress=True)
  256.  
  257. model = load_model()
  258.  
  259. while True:
  260. with mss.mss() as sct:
  261. Game_Scr = np.array(sct.grab(Game_Scr_pos))[:, :, :3]
  262.  
  263. # Below is a test to see if you are capturing the screen of the emulator.
  264. # cv2.imshow('Game_Src', Game_Scr)
  265. # cv2.waitKey(0)
  266.  
  267. Game_Scr = cv2.resize(Game_Scr,
  268. dsize=(960, 540),
  269. interpolation=cv2.INTER_AREA)
  270. x = np.array(Game_Scr).reshape(-1, 1)
  271.  
  272. size = (224, 224)
  273. image = ImageOps.fit(Game_Scr, size, Image.ANTIALIAS)
  274.  
  275. Result = []
  276. Result = model.predict(x)
  277. if Result == 0:
  278. print("Play")
  279. else:
  280. print("Miss")
  281.  
  282.  
  283. if __name__ == "__main__":
  284. physical_devices = tf.config.list_physical_devices("GPU")
  285. tf.config.experimental.set_memory_growth(physical_devices[0], True)
  286.  
  287. First_State = int(
  288. input("""If you want to analyze your video?
  289. press 1.
  290.  
  291. or real time play game and real time screen analyze.
  292. press 2.
  293.  
  294. If learning Geometry Dash 'Play Game' and 'Nothing' image
  295. Press 3.
  296.  
  297. If you gaming from real time
  298. Press 4
  299. """))
  300.  
  301. if First_State == 1:
  302. Video = input("Please enter a video path and video name.")
  303. VideoAnalyze(Video)
  304.  
  305. elif First_State == 2:
  306. PlayWithLearning()
  307.  
  308. elif First_State == 4:
  309. GamePlay()
  310.  
  311. elif First_State == 3:
  312. train_dataset, validation_dataset = ImportImageDataSet()
  313.  
  314. # train_dataset = train_dataset.cache().shuffle(30).prefetch(buffer_size=tf.data.experimental.AUTOTUNE)
  315. print("Load Dataset")
  316.  
  317. # print(train_dataset.class_names)
  318. print(train_dataset)
  319.  
  320. # cv2.imshow('Game_Src', cv2.imread(train_dataset.take(1)))
  321. # cv2.waitKey(1)
  322.  
  323. tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=log_dir,
  324. histogram_freq=1)
  325.  
  326. bin_img_clssf = load_model()
  327.  
  328. history = bin_img_clssf.fit(
  329. train_dataset,
  330. validation_data=validation_dataset,
  331. epochs=2,
  332. batch_size=64,
  333. callbacks=[tensorboard_callback],
  334. )
  335.  
  336. bin_img_clssf.save("Model\\" +
  337. datetime.datetime.now().strftime("%Y%m%d-%H%M%S") +
  338. "model.h5")
  339.  
Add Comment
Please, Sign In to add comment