1. 学习了一下 AI 五子棋,顺手改作 19 路的棋盘,便于围棋通用。render.py 主要修改如下:

# 常量部分:
IMAGE_PATH = 'img/'
StoneSize = 32
WIDTH = 650
HEIGHT = 732
ColSize = 33
RowSize = 34.44
H_Pad = (HEIGHT- RowSize * 19) / 2 + (RowSize - StoneSize) / 2 + 1
W_Pad = (WIDTH - ColSize * 19) / 2 + (ColSize - StoneSize) / 2 + 1
Pad = ColSize - StoneSize, RowSize - StoneSize
PIECE = StoneSize # 坐标转换部分:
def coordinate_transform_map2pixel(self, i, j):
# 从 chessMap 里的逻辑坐标到 UI 上的绘制坐标的转换
return j * (PIECE+Pad[0]) + W_Pad, i * (PIECE+Pad[1]) + H_Pad def coordinate_transform_pixel2map(self, x, y):
# 从 UI 上的绘制坐标到 chessMap 里的逻辑坐标的转换
i , j = int((y-H_Pad) / (PIECE+Pad[1])), int((x-W_Pad) / (PIECE+Pad[0])) if i < 0 or i >= N or j < 0 or j >= N:
return None, None
else:
return i, j

2. 发现 pygame 还不错,便从网上搜索到《Beginning Game Development With Python And Pygame》,其中蚂蚁游戏的 AI 表现甚好,主要代码如下:

import pygame, os, sys
from pygame.locals import *
from random import randint
from pygame.math import Vector2 BaseDir = os.path.dirname(os.path.abspath(__file__))
ImgPath = BaseDir + '/res/' ScreenSize = (640, 480)
NestLocation = (320, 240)
AntCount = 20
NestSize = 100.0 class State(object):
def __init__(self, name):
self.name = name
def do_actions(self):
pass
def check_conditions(self):
pass
def entry_actions(self):
pass
def exit_actions(self):
pass class StateMachine(object):
def __init__(self):
self.states = {}
self.active_state = None
def add_state(self, state):
self.states[state.name] = state
def think(self):
if self.active_state is None:
return
self.active_state.do_actions()
new_state_name = self.active_state.check_conditions()
if new_state_name is not None:
self.set_state(new_state_name)
def set_state(self, new_state_name):
if self.active_state is not None:
self.active_state.exit_actions()
self.active_state = self.states[new_state_name]
self.active_state.entry_actions() class World(object):
def __init__(self):
self.entities = {}
self.entity_id = 0
self.background = pygame.surface.Surface(ScreenSize).convert()
self.background.fill((255,255,255))
pygame.draw.circle(self.background, (200,255,200), NestLocation, int(NestSize))
def add_entity(self, entity):
self.entities[self.entity_id] = entity
entity.id = self.entity_id
self.entity_id += 1
def remove_entity(self, entity):
del self.entities[entity.id]
def get(self, entity_id):
if entity_id in self.entities:
return self.entities[entity_id]
else:
return None
def process(self, time_passed):
time_passed_seconds = time_passed / 1000.0
entities = list(self.entities.values())
for entity in entities:
entity.process(time_passed_seconds)
def render(self, surface):
surface.blit(self.background, (0,0))
for entity in self.entities.values():
entity.render(surface)
def got_close_entity(self, name, location, range=100.0):
location = Vector2(*location)
for entity in self.entities.values():
if entity.name == name:
distance = location.distance_to(entity.location)
if distance < range:
return entity
return None class GameEntity(object):
def __init__(self, world, name, image):
self.world = world
self.name = name
self.image = image
self.location = Vector2(0, 0)
self.destination = Vector2(0, 0)
self.speed = 0
self.brain = StateMachine()
self.id = 0
def render(self, surface):
x,y = self.location
w,h = self.image.get_size()
surface.blit(self.image, (x-w/2, y-h/2))
def process(self, time_passed):
self.brain.think()
if self.speed > 0 and self.location != self.destination:
vec_to_destination = self.destination - self.location
distance_to_destination = vec_to_destination.length()
travel_distance = min(distance_to_destination, time_passed * self.speed)
self.location += travel_distance * vec_to_destination.normalize() class Leaf(GameEntity):
def __init__(self, world, image):
GameEntity.__init__(self, world, "leaf", image) class Spider(GameEntity):
def __init__(self, world, image):
GameEntity.__init__(self, world, "spider", image)
self.dead_image = pygame.transform.flip(image, 0, 1)
self.health = 25
self.speed = 50.0 + randint(-20,20)
def bitten(self):
self.health -= 1
if self.health <= 0:
self.speed = 0
self.image = self.dead_image
self.speed = 140
def render(self, surface):
GameEntity.render(self, surface)
x,y = self.location
w,h = self.image.get_size()
bar_x = x - 12
bar_y = y + h/2
surface.fill((255,0,0), (bar_x, bar_y, 25, 4))
surface.fill((0,255,0), (bar_x, bar_y, self.health, 4))
def process(self, time_passed):
x,y = self.location
if x > ScreenSize[0] + 2:
self.world.remove_entity(self)
return
GameEntity.process(self, time_passed) class Ant(GameEntity):
def __init__(self, world, image):
GameEntity.__init__(self, world, "ant", image)
exploring_state = AntStateExploring(self)
seeking_state = AntStateSeeking(self)
delivering_state = AntStateDelivering(self)
hunting_state = AntStateHunting(self)
self.brain.add_state(exploring_state)
self.brain.add_state(seeking_state)
self.brain.add_state(delivering_state)
self.brain.add_state(hunting_state)
self.carry_image = None
def carry(self, image):
self.carry_image = image
def drop(self, surface):
if self.carry_image:
x,y = self.location
w,h = self.carry_image.get_size()
surface.blit(self.carry_image, (x-w, y-h/2))
self.carry_image = None
def render(self, surface):
GameEntity.render(self, surface)
if self.carry_image:
x,y = self.location
w,h = self.carry_image.get_size()
surface.blit(self.carry_image, (x-w, y-h/2)) class AntStateExploring(State):
def __init__(self, ant):
State.__init__(self, "exploring")
self.ant = ant
def random_destination(self):
w,h = ScreenSize
self.ant.destination = Vector2(randint(0, w), randint(0, h))
def do_actions(self):
if randint(1,20) == 1:
self.random_destination()
def check_conditions(self):
leaf = self.ant.world.got_close_entity("leaf", self.ant.location)
if leaf is not None:
self.ant.leaf_id = leaf.id
return "seeking"
spider = self.ant.world.got_close_entity("spider", NestLocation, NestSize)
if spider is not None:
if self.ant.location.distance_to(spider.location) < 100:
self.ant.spider_id = spider.id
return "hunting"
return None
def entry_actions(self):
self.ant.speed = 120 + randint(-30, 30)
self.random_destination() class AntStateSeeking(State):
def __init__(self, ant):
State.__init__(self, "seeking")
self.ant = ant
self.leaf_id = None
def check_conditions(self):
leaf = self.ant.world.get(self.ant.leaf_id)
if leaf is None:
return "exploring"
if self.ant.location.distance_to(leaf.location) < 5:
self.ant.carry(leaf.image)
self.ant.world.remove_entity(leaf)
return "delivering"
return None
def entry_actions(self):
leaf = self.ant.world.get(self.ant.leaf_id)
if leaf is not None:
self.ant.destination = leaf.location
self.ant.speed = 160 + randint(-20,20) class AntStateDelivering(State):
def __init__(self, ant):
State.__init__(self, "delivering")
self.ant = ant
def check_conditions(self):
if Vector2(*NestLocation).distance_to(self.ant.location) < NestSize:
if randint(1, 10) == 1:
self.ant.drop(self.ant.world.background)
return "exploring"
return None
def entry_actions(self):
self.ant.speed = 60
random_offset = Vector2(randint(-20,20), randint(-20,20))
self.ant.destination = Vector2(*NestLocation) + random_offset class AntStateHunting(State):
def __init__(self, ant):
State.__init__(self, "hunting")
self.ant = ant
self.got_kill = False
def do_actions(self):
spider = self.ant.world.get(self.ant.spider_id)
if spider is None:
return
self.ant.destination = spider.location
if self.ant.location.distance_to(spider.location) < 15:
if randint(1,5) == 1:
spider.bitten()
if spider.health <= 0:
self.ant.carry(spider.image)
self.ant.world.remove_entity(spider)
self.got_kill = True
def check_conditions(self):
if self.got_kill:
return "delivering"
spider = self.ant.world.get(self.ant.spider_id)
if spider is None:
return "exploring"
if spider.location.distance_to(NestLocation) > NestSize * 3:
return "exploring"
return None
def entry_actions(self):
self.speed = 160 + randint(0,50)
def exit_actions(self):
self.got_kill = False def run():
pygame.init()
screen = pygame.display.set_mode(ScreenSize, 0, 32)
world = World()
w,h = ScreenSize
clock = pygame.time.Clock() ant_image = pygame.image.load(ImgPath + "ant.png").convert_alpha()
leaf_image = pygame.image.load(ImgPath + "leaf.png").convert_alpha()
spider_image = pygame.image.load(ImgPath + "spider.png").convert_alpha() for ant_nr in range(AntCount):
ant = Ant(world, ant_image)
ant.location = Vector2(randint(0,w), randint(0,h))
ant.brain.set_state("exploring")
world.add_entity(ant) while True:
for e in pygame.event.get():
if e.type == QUIT:
return
time_passed = clock.tick(30)
if randint(1,10) == 1:
leaf = Leaf(world, leaf_image)
leaf.location = Vector2(randint(0,w), randint(0,h))
world.add_entity(leaf)
if randint(1,100) == 1:
spider = Spider(world, spider_image)
spider.location = Vector2(-50, randint(0,h))
spider.destination = Vector2(w+50, randint(0,h))
world.add_entity(spider)
world.process(time_passed)
world.render(screen) pygame.display.update() if __name__ == '__main__':
run()

Ant world

运行效果图如下:

完整源代码下载:http://download.csdn.net/download/china_x01/10125074

x01.AntWorld: An Python AI Game的更多相关文章

  1. Flutter · Python AI 弹幕播放器来袭

    AI智能弹幕(也称蒙版弹幕):弹幕浮在视频的上方却永远不会挡住人物.起源于哔哩哔哩的web端黑科技,而后分别实现在IOS和Android的app端,如今被用于短视频.直播等媒体行业,用户体验提升显著. ...

  2. python AI(numpy,matplotlib)

    http://blog.csdn.net/ywjun0919/article/details/8692018 apt-cache policy python-numpy sudo apt-get in ...

  3. 转载 | Python AI 教学│k-means聚类算法及应用

    关注我们的公众号哦!获取更多精彩哦! 1.问题导入 假如有这样一种情况,在一天你想去某个城市旅游,这个城市里你想去的有70个地方,现在你只有每一个地方的地址,这个地址列表很长,有70个位置.事先肯定要 ...

  4. python AI换脸 用普氏分析法(Procrustes Analysis)实现人脸对齐

    1.图片效果 2.原代码 # !/usr/bin/python # -*- coding: utf-8 -*- # Copyright (c) 2015 Matthew Earl # # Permis ...

  5. 使用Python创建AI比你想象的轻松

    使用 Python 创建 AI 比你想象的轻松 可能对AI领域,主要开发阶段,成就,结果和产品使用感兴趣.有数百个免费源和教程描述使用Python的AI.但是,没有必要浪费你的时间看他们.这里是一个详 ...

  6. 小白眼中的AI之~Numpy基础

      周末码一文,明天见矩阵- 其实Numpy之类的单讲特别没意思,但不稍微说下后面说实际应用又不行,所以大家就练练手吧 代码裤子: https://github.com/lotapp/BaseCode ...

  7. python开发_zlib_完整版_博主推荐

    ''' python中的zlib模块提供了压缩和解压缩的方法 实现功能: 读取一个文件的内容,然后把该文件的内容以字符串的形式返回 然后对返回回来的字符串进行压缩处理,然后写入到另一个文件中 同时,也 ...

  8. Python基础简介

    一.目前各种语言的应用:java, 可以把特别小的项目做大,并且开源库比较多,C: 用在最底层,例如编写操作系统,运行速率快,开发效率低,C++:常坐游戏引擎Python:AI(人工智能) 简单.明确 ...

  9. python通过人脸识别全面分析好友,一起看透你的“朋友圈”

    微信:一个提供即时通讯服务的应用程序,更是一种生活方式,超过数十亿的使用者,越来越多的人选择使用它来沟通交流. 不知从何时起,我们的生活离不开微信,每天睁开眼的第一件事就是打开微信,关注着朋友圈里好友 ...

随机推荐

  1. 合并Spark社区代码的正确姿势

    原创文章,转载请保留出处 最近刚刚忙完Spark 2.2.0的性能测试及Bug修复,社区又要发布2.1.2了,国庆期间刚好有空,过了一遍2.1.2的相关JIRA,发现有不少重要修复2.2.0也能用上, ...

  2. Opencv处理鼠标事件-OpenCV步步精深

    在图片上双击过的位置绘制一个 圆圈 鼠标事件就是和鼠标有关的,比如左键按下,左键松开,右键按下,右键松开,双击右键等等. 我们可以通过鼠标事件获得与鼠标对应的图片上的坐标.我们通过以下函数来调用查看所 ...

  3. 【学习】文本框输入监听事件oninput

    真实项目中遇到的,需求是:一个文本框,一个按钮,当文本框输入内容时,按钮可用,当删除内容时,按钮不可用. 刚开始用的focus和blur, $(".pay-text").focus ...

  4. 最火的Android开源项目(一)

    摘要:对于开发者而言,了解当下比较流行的开源项目很是必要.利用这些项目,有时能够让你达到事半功倍的效果.为此,CSDN特整理了GitHub上最受欢迎的Android及iOS开源项目,本文详细介绍了20 ...

  5. (@WhiteTaken)设计模式学习——组合模式

    下面来学习一下组合模式. 组合模式概念是什么呢.从别的地方抄来了一些理论. 理论:将对象组合成树形结构以表示"部分-整体"的层次结构.Composite模式使得用户对单个对象和组合 ...

  6. WebService的简单运用添加删除

    WebService是一种跨编程语言和跨操作系统平台的远程调用技术,简单来说就是将数据存储到项目的文件夹下 .NET中基于DOM核心类 XmlDocument 表示一个XML文档 XmlNode表示X ...

  7. 自学spring AOP

    本人是一个编程新手也是第一次写博客 这篇文章是我结合网上的资料和一些书籍学的 如果有不对之处请留言告知 本文介绍了AOP的两个知识点 1: 代理 代理有两种 我先写:Java静态代理 1:建立一个接口 ...

  8. javascript 之异常处理try catch finally--05

    语法结构 try catch finally是ECMAScript-262 第三版提供异常处理机制的标准,语法结构如下: try{ //可能会发生的错误代码 } catch(error){ //错误处 ...

  9. JavaScript的function参数的解释

    在js里面写function时其参数在内部表示为一个数组.也就是说:我们定义一个function,里面的参数和将来调用这个function时传入的实参是毫无关系的,如果我们要定义一个function ...

  10. IOC杂谈(一)初识IOC

    初衷 发现学习东西不单只是看,用,还有很重要一点就是记录,不然过个几个月再用到相同的知识时,你会发现你已经丢得差不多了,故此开始在博客园记录的同时也与各位同行分享知识. 正题 关于IOC,在刚工作时就 ...