x01.AntWorld: An Python AI Game
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的更多相关文章
- Flutter · Python AI 弹幕播放器来袭
AI智能弹幕(也称蒙版弹幕):弹幕浮在视频的上方却永远不会挡住人物.起源于哔哩哔哩的web端黑科技,而后分别实现在IOS和Android的app端,如今被用于短视频.直播等媒体行业,用户体验提升显著. ...
- python AI(numpy,matplotlib)
http://blog.csdn.net/ywjun0919/article/details/8692018 apt-cache policy python-numpy sudo apt-get in ...
- 转载 | Python AI 教学│k-means聚类算法及应用
关注我们的公众号哦!获取更多精彩哦! 1.问题导入 假如有这样一种情况,在一天你想去某个城市旅游,这个城市里你想去的有70个地方,现在你只有每一个地方的地址,这个地址列表很长,有70个位置.事先肯定要 ...
- python AI换脸 用普氏分析法(Procrustes Analysis)实现人脸对齐
1.图片效果 2.原代码 # !/usr/bin/python # -*- coding: utf-8 -*- # Copyright (c) 2015 Matthew Earl # # Permis ...
- 使用Python创建AI比你想象的轻松
使用 Python 创建 AI 比你想象的轻松 可能对AI领域,主要开发阶段,成就,结果和产品使用感兴趣.有数百个免费源和教程描述使用Python的AI.但是,没有必要浪费你的时间看他们.这里是一个详 ...
- 小白眼中的AI之~Numpy基础
周末码一文,明天见矩阵- 其实Numpy之类的单讲特别没意思,但不稍微说下后面说实际应用又不行,所以大家就练练手吧 代码裤子: https://github.com/lotapp/BaseCode ...
- python开发_zlib_完整版_博主推荐
''' python中的zlib模块提供了压缩和解压缩的方法 实现功能: 读取一个文件的内容,然后把该文件的内容以字符串的形式返回 然后对返回回来的字符串进行压缩处理,然后写入到另一个文件中 同时,也 ...
- Python基础简介
一.目前各种语言的应用:java, 可以把特别小的项目做大,并且开源库比较多,C: 用在最底层,例如编写操作系统,运行速率快,开发效率低,C++:常坐游戏引擎Python:AI(人工智能) 简单.明确 ...
- python通过人脸识别全面分析好友,一起看透你的“朋友圈”
微信:一个提供即时通讯服务的应用程序,更是一种生活方式,超过数十亿的使用者,越来越多的人选择使用它来沟通交流. 不知从何时起,我们的生活离不开微信,每天睁开眼的第一件事就是打开微信,关注着朋友圈里好友 ...
随机推荐
- Java面向对象 IO (三)
Java面向对象 IO (三) 知识概要: (1)IO 流的操作规律 (2)异常日志信息IO处理 ...
- Java面向对象 包
Java面向对象 包 知识概要: (1)包的概念 (2)包的命名 (3)编译执行 (4)导入 (5)包的访问权限 包: 包(package)用于将完成不同功能 ...
- 在ubuntu16.04中一键创建LAMP环境
步骤 1 执行命令apt-get update. 步骤 2 执行命令apt-get install lamp-server^. 步骤 3 在安装过程中会跳出Mysql数据库root用户密码设置窗口,按 ...
- cmd启动,重启,停止IIS命令
直接使用CMD我们可以操作很多事情,比如启动IIS,重启IIS,停止IIS 重启IIS服务器,开始->运行->cmd (以下列出相关操作命令): iisreset /RESTART 停止后 ...
- 【学习】原生js学习笔记1:添加class和使input为不可用
<input type="checkbox" id="new_check" onChange="noUse()" checked> ...
- SqlBulkCopy效率低下原因分析
看到标题 应该会奇怪 SqlBulkCopy 为什么会效率低下 场景:接手项目 数据库SQLSERVER2008R2, 目前有一张流水表单表数据超过4亿,表中建有索引,有其他模块对这个表进行查询操作 ...
- jenkins、ant、selenium、testng搭建自动化测试框架
如果在你的理解中自动化测试就是在eclipse里面讲webdriver的包引入,然后写一些测试脚本,这就是你所说的自动化测试,其实这个还不能算是真正的自动化测试,你见过每次需要运行的时候还需要打开ec ...
- Xamarin.Forms 开发IOS、Android、UWP应用
C#语言特点,简单.快速.高效.本次我们通过C#以及Xaml来做移动开发. 1.开发工具visual studio 2015或visual studio 2017.当然visual studio 20 ...
- 使用bitset实现毫秒级查询
前言 因为业务要求api的一次请求响应时间在10ms以内,所以传统的数据库查询操作直接被排除(网络io和磁盘io).通过调研,最终使用了bieset,目前已经正常运行了很久 *** bitset介绍 ...
- centos7 最小安装无ifconfig
可能不会有人看到这篇文章,加入有幸被看到,建议读者从后往前看!最小化安装问题:1 没有ifconfig 命令,解决:yum install net-tools2 使用yum install n ...