python3,所需模块请自行补齐

# coding=utf8

import pygame
import random
from pygame.locals import *
import numpy as np
from collections import deque
import tensorflow as tf # http://blog.topspeedsnail.com/archives/10116
import cv2 # http://blog.topspeedsnail.com/archives/4755 BLACK = (0, 0, 0)
WHITE = (255, 255, 255) SCREEN_SIZE = [320, 400]
BAR_SIZE = [50, 5]
BALL_SIZE = [15, 15] # 神经网络的输出
MOVE_STAY = [1, 0, 0]
MOVE_LEFT = [0, 1, 0]
MOVE_RIGHT = [0, 0, 1] class Game(object):
def __init__(self):
pygame.init()
self.clock = pygame.time.Clock()
self.screen = pygame.display.set_mode(SCREEN_SIZE)
pygame.display.set_caption('Simple Game') self.ball_pos_x = SCREEN_SIZE[0] // 2 - BALL_SIZE[0] / 2
self.ball_pos_y = SCREEN_SIZE[1] // 2 - BALL_SIZE[1] / 2 self.ball_dir_x = -1 # -1 = left 1 = right
self.ball_dir_y = -1 # -1 = up 1 = down
self.ball_pos = pygame.Rect(
self.ball_pos_x, self.ball_pos_y, BALL_SIZE[0], BALL_SIZE[1]) self.bar_pos_x = SCREEN_SIZE[0] // 2 - BAR_SIZE[0] // 2
self.bar_pos = pygame.Rect(
self.bar_pos_x, SCREEN_SIZE[1] - BAR_SIZE[1], BAR_SIZE[0], BAR_SIZE[1]) # action是MOVE_STAY、MOVE_LEFT、MOVE_RIGHT
# ai控制棒子左右移动;返回游戏界面像素数和对应的奖励。(像素->奖励->强化棒子往奖励高的方向移动)
def step(self, action): if action == MOVE_LEFT:
self.bar_pos_x = self.bar_pos_x - 2
elif action == MOVE_RIGHT:
self.bar_pos_x = self.bar_pos_x + 2
else:
pass
if self.bar_pos_x < 0:
self.bar_pos_x = 0
if self.bar_pos_x > SCREEN_SIZE[0] - BAR_SIZE[0]:
self.bar_pos_x = SCREEN_SIZE[0] - BAR_SIZE[0] self.screen.fill(BLACK)
self.bar_pos.left = self.bar_pos_x
pygame.draw.rect(self.screen, WHITE, self.bar_pos) self.ball_pos.left += self.ball_dir_x * 2
self.ball_pos.bottom += self.ball_dir_y * 3
pygame.draw.rect(self.screen, WHITE, self.ball_pos) if self.ball_pos.top <= 0 or self.ball_pos.bottom >= (SCREEN_SIZE[1] - BAR_SIZE[1] + 1):
self.ball_dir_y = self.ball_dir_y * -1
if self.ball_pos.left <= 0 or self.ball_pos.right >= (SCREEN_SIZE[0]):
self.ball_dir_x = self.ball_dir_x * -1 reward = 0
if self.bar_pos.top <= self.ball_pos.bottom and (self.bar_pos.left < self.ball_pos.right and self.bar_pos.right > self.ball_pos.left):
reward = 1 # 击中奖励
elif self.bar_pos.top <= self.ball_pos.bottom and (self.bar_pos.left > self.ball_pos.right or self.bar_pos.right < self.ball_pos.left):
reward = -1 # 没击中惩罚 # 获得游戏界面像素
screen_image = pygame.surfarray.array3d(pygame.display.get_surface())
pygame.display.update()
# 返回游戏界面像素和对应的奖励
return reward, screen_image # learning_rate
LEARNING_RATE = 0.99
# 更新梯度
INITIAL_EPSILON = 1.0
FINAL_EPSILON = 0.05
# 测试观测次数
EXPLORE = 500000
OBSERVE = 50000
# 存储过往经验大小
REPLAY_MEMORY = 500000 BATCH = 100 # 输出层神经元数。代表3种操作-MOVE_STAY:[1, 0, 0] MOVE_LEFT:[0, 1, 0] MOVE_RIGHT:[0, 0, 1]
output = 3
input_image = tf.placeholder("float", [None, 80, 100, 4]) # 游戏像素
action = tf.placeholder("float", [None, output]) # 操作 # 定义CNN-卷积神经网络 参考:http://blog.topspeedsnail.com/archives/10451 def convolutional_neural_network(input_image):
weights = {'w_conv1': tf.Variable(tf.zeros([8, 8, 4, 32])),
'w_conv2': tf.Variable(tf.zeros([4, 4, 32, 64])),
'w_conv3': tf.Variable(tf.zeros([3, 3, 64, 64])),
'w_fc4': tf.Variable(tf.zeros([3456, 784])),
'w_out': tf.Variable(tf.zeros([784, output]))} biases = {'b_conv1': tf.Variable(tf.zeros([32])),
'b_conv2': tf.Variable(tf.zeros([64])),
'b_conv3': tf.Variable(tf.zeros([64])),
'b_fc4': tf.Variable(tf.zeros([784])),
'b_out': tf.Variable(tf.zeros([output]))} conv1 = tf.nn.relu(tf.nn.conv2d(input_image, weights['w_conv1'], strides=[
1, 4, 4, 1], padding="VALID") + biases['b_conv1'])
conv2 = tf.nn.relu(tf.nn.conv2d(conv1, weights['w_conv2'], strides=[
1, 2, 2, 1], padding="VALID") + biases['b_conv2'])
conv3 = tf.nn.relu(tf.nn.conv2d(conv2, weights['w_conv3'], strides=[
1, 1, 1, 1], padding="VALID") + biases['b_conv3'])
conv3_flat = tf.reshape(conv3, [-1, 3456])
fc4 = tf.nn.relu(tf.matmul(conv3_flat, weights['w_fc4']) + biases['b_fc4']) output_layer = tf.matmul(fc4, weights['w_out']) + biases['b_out']
return output_layer # 深度强化学习入门: https://www.nervanasys.com/demystifying-deep-reinforcement-learning/
# 训练神经网络 def train_neural_network(input_image):
predict_action = convolutional_neural_network(input_image) argmax = tf.placeholder("float", [None, output])
gt = tf.placeholder("float", [None]) action = tf.reduce_sum(tf.multiply(predict_action, argmax), reduction_indices=1)
cost = tf.reduce_mean(tf.square(action - gt))
optimizer = tf.train.AdamOptimizer(1e-6).minimize(cost) game = Game()
D = deque() _, image = game.step(MOVE_STAY)
# 转换为灰度值
image = cv2.cvtColor(cv2.resize(image, (100, 80)), cv2.COLOR_BGR2GRAY)
# 转换为二值
ret, image = cv2.threshold(image, 1, 255, cv2.THRESH_BINARY)
input_image_data = np.stack((image, image, image, image), axis=2) with tf.Session() as sess:
sess.run(tf.initialize_all_variables()) saver = tf.train.Saver() n = 0
epsilon = INITIAL_EPSILON
while True:
action_t = predict_action.eval(
feed_dict={input_image: [input_image_data]})[0] argmax_t = np.zeros([output], dtype=np.int)
if(random.random() <= INITIAL_EPSILON):
maxIndex = random.randrange(output)
else:
maxIndex = np.argmax(action_t)
argmax_t[maxIndex] = 1
if epsilon > FINAL_EPSILON:
epsilon -= (INITIAL_EPSILON - FINAL_EPSILON) / EXPLORE # for event in pygame.event.get(): macOS需要事件循环,否则白屏
# if event.type == QUIT:
# pygame.quit()
# sys.exit()
reward, image = game.step(list(argmax_t)) image = cv2.cvtColor(cv2.resize(
image, (100, 80)), cv2.COLOR_BGR2GRAY)
ret, image = cv2.threshold(image, 1, 255, cv2.THRESH_BINARY)
image = np.reshape(image, (80, 100, 1))
input_image_data1 = np.append(
image, input_image_data[:, :, 0:3], axis=2) D.append((input_image_data, argmax_t, reward, input_image_data1)) if len(D) > REPLAY_MEMORY:
D.popleft() if n > OBSERVE:
minibatch = random.sample(D, BATCH)
input_image_data_batch = [d[0] for d in minibatch]
argmax_batch = [d[1] for d in minibatch]
reward_batch = [d[2] for d in minibatch]
input_image_data1_batch = [d[3] for d in minibatch] gt_batch = [] out_batch = predict_action.eval(
feed_dict={input_image: input_image_data1_batch}) for i in range(0, len(minibatch)):
gt_batch.append(
reward_batch[i] + LEARNING_RATE * np.max(out_batch[i])) optimizer.run(feed_dict={
gt: gt_batch, argmax: argmax_batch, input_image: input_image_data_batch}) input_image_data = input_image_data1
n = n + 1 if n % 10000 == 0:
saver.save(sess, 'game.cpk', global_step=n) # 保存模型 print(n, "epsilon:", epsilon, " ", "action:",
maxIndex, " ", "reward:", reward) train_neural_network(input_image)

tensorflow训练打游戏ai的更多相关文章

  1. 游戏AI之初步介绍(0)

    目录 游戏AI是什么? 游戏AI和理论AI 智能的假象 (更新)游戏AI和机器学习 介绍一些游戏AI 4X游戏AI <求生之路>系列 角色扮演/沙盒游戏中的NPC 游戏AI 需要学些什么? ...

  2. 使用TensorFlow训练自己的语音识别AI

    这次来训练一个基于CNN的语音识别模型.训练完成后,我们将尝试将此模型用于Hotword detection. 人类是怎样听懂一句话的呢?以汉语为例,当听到"wo shi"的录音时 ...

  3. Unity 用ml-agents机器学习造个游戏AI吧(1)(Windows环境配置)

    前言:以前觉得机器学习要应用于游戏AI,还远得很. 最近看到一些资料后,突发兴致试着玩了玩Unity机器学习,才发觉机器学习占领游戏AI的可能性和趋势. Unity训练可爱柯基犬Puppo 机器学习训 ...

  4. 王亮:游戏AI探索之旅——从alphago到moba游戏

    欢迎大家前往腾讯云+社区,获取更多腾讯海量技术实践干货哦~ 本文由云加社区技术沙龙 发表于云+社区专栏 演讲嘉宾:王亮,腾讯AI高级研究员.2013年加入腾讯,从事大数据预测以及游戏AI研发工作.目前 ...

  5. 游戏AI系列内容 咋样才能做个有意思的AI呢

    游戏AI系列内容 咋样才能做个有意思的AI呢 写在前面的话 怪物AI怎么才能做的比较有意思.其实这个命题有点大,我作为一个仅仅进入游戏行业两年接触怪物AI还不到一年的程序员来说,来谈这个话题,我想我是 ...

  6. 趣说游戏AI开发:对状态机的褒扬和批判

    0x00 前言 因为临近年关工作繁忙,已经有一段时间没有更新博客了.到了元旦终于有时间来写点东西,既是积累也是分享.如题目所示,本文要来聊一聊在游戏开发中经常会涉及到的话题--游戏AI.设计游戏AI的 ...

  7. 使用行为树(Behavior Tree)实现游戏AI

    ——————————————————————— 谈到游戏AI,很明显智能体拥有的知识条目越多,便显得更智能,但维护庞大数量的知识条目是个噩梦:使用有限状态机(FSM),分层有限状态机(HFSM),决策 ...

  8. 如何建立一个完整的游戏AI

    http://blog.friskit.me/2012/04/how-to-build-a-perfect-game-ai/ 人工智能(Artificial Intelligence)在游戏中使用已经 ...

  9. 实现简易而强大的游戏AI——FSM,有限状态机

    http://blog.friskit.me/2012/05/introduction-of-fsm/ 在很久很久以前,受限于计算机性能和图形效果,游戏往往是以玩家为唯一主动对象的,玩家发出动作,游戏 ...

随机推荐

  1. mvc ---- ajax 提交 (ckeditor)富文本框 提示潜在危险 Request.Form

    ajax 提交 ckeditor 中的内容怎么提交都提交不了,折腾半天,后来终于找到问题 在你的方法头上加 [HttpPost] [ValidateInput(false)] public Actio ...

  2. Qt5.3.2_CentOS6.4_单步调试环境__20160306【勿删,繁琐】

    20160306 全程没有f/q ZC:使用的虚拟机环境是:博客园VMwareSkill 的 “CentOS6.4_x86_120g__20160306.rar” 需要调试器 gdb ,从“http: ...

  3. windows 网页打不开github网站

    gitbub是外网,经常会遇到访问不了的问题,并且有时能访问也网速好慢. 解决这个问题的方法是 更改hosts文件,地址:C:\Windows\System32\Drivers\etc 我在hosts ...

  4. export与export default exports与module.exports的用法

    转载:http://blog.csdn.net/zhou_xiao_cheng/article/details/52759632 本文原创地址链接:http://blog.csdn.net/zhou_ ...

  5. js插件---Bootstrap 树控件

    js插件---Bootstrap 树控件 一.总结 一句话总结:可以直接用gojs,或者搜索js,jquery的树控件,或者bootstrap树控件,一大堆 gojs 二.JS组件系列——Bootst ...

  6. English trip -- VC(情景课)4 D

    What do you see? I can see three men in the pictrue. one older man is a doctor, two younger men are ...

  7. LeetCode--053--最大子序和

    问题描述: 给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和. 示例: 输入: [-2,1,-3,4,-1,2,1,-5,4], 输出: 6 解释: ...

  8. 4-2 什么是WebSocket; Action Cable的使用。Rails guide-6.3视频教学,没有看!

    WebSocket WebSocket是一种在单个TCP连接上进行全双工通讯的协议.WebSocket通信协议于2011年被IETF定为标准RFC 6455,并由RFC7936补充规范.WebSock ...

  9. codeforces 536a//Tavas and Karafs// Codeforces Round #299(Div. 1)

    题意:一个等差数列,首项为a,公差为b,无限长.操作cz是区间里选择最多m个不同的非0元素减1,最多操作t次,现给出区间左端ll,在t次操作能使区间全为0的情况下,问右端最大为多少. 这么一个简单题吞 ...

  10. python-day33--Process类中的方法及属性

    p.daemon = True -->守护进程,守护进程不可以再有子进程,并且主进程死守护进程就死,要写在p.start()之前 p.join() ---> 主进程等子进程执行完 之后再结 ...