不废话,直接上码,跟神经网络一点关系都没有,这37行代码只能保证电脑的对敌牺牲率是1:10左右,如果想手动操控,注释掉autopilot后边的代码即可。

哪个大神有兴趣可以用tensorflow或者serpentai来玩一下这个游戏。

# coding=utf8

from random import randint as rint

import pygame
from pygame.locals import * class MySprite(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.master_image = None
self.frame = 0
self.old_frame = -1
self.frame_width = 1
self.frame_height = 1
self.first_frame = 0
self.last_frame = 0
self.columns = 1
self.last_time = 0
self.direction = 0
self.velocity = Point(0.0, 0.0) # X property
def _getx(self):
return self.rect.x def _setx(self, value):
self.rect.x = value X = property(_getx, _setx) # Y property
def _gety(self):
return self.rect.y def _sety(self, value):
self.rect.y = value Y = property(_gety, _sety) # position property
def _getpos(self):
return self.rect.topleft def _setpos(self, pos):
self.rect.topleft = pos position = property(_getpos, _setpos) def load(self, filename, width, height, columns):
self.master_image = pygame.image.load(filename).convert_alpha()
self.frame_width = width
self.frame_height = height
self.rect = Rect(0, 0, width, height)
self.columns = columns
# try to auto-calculate total frames
rect = self.master_image.get_rect()
self.last_frame = (rect.width // width) * (rect.height // height) - 1 def update(self, current_time, rate=30):
# update animation frame number
if current_time > self.last_time + rate:
self.frame += 1
if self.frame > self.last_frame:
self.frame = self.first_frame
self.last_time = current_time # build current frame only if it changed
if self.frame != self.old_frame:
frame_x = (self.frame % self.columns) * self.frame_width
frame_y = (self.frame // self.columns) * self.frame_height
rect = Rect(frame_x, frame_y, self.frame_width, self.frame_height)
self.image = self.master_image.subsurface(rect)
self.old_frame = self.frame def __str__(self):
return str(self.frame) + "," + str(self.first_frame) + \
"," + str(self.last_frame) + "," + str(self.frame_width) + \
"," + str(self.frame_height) + "," + str(self.columns) + \
"," + str(self.rect) # Point class class Point(object):
def __init__(self, x, y):
self.__x = x
self.__y = y # X property
def getx(self): return self.__x def setx(self, x): self.__x = x x = property(getx, setx) # Y property
def gety(self): return self.__y def sety(self, y): self.__y = y y = property(gety, sety) def __str__(self):
return "{X:" + "{:.0f}".format(self.__x) + \
",Y:" + "{:.0f}".format(self.__y) + "}" pygame.init()
playerHealth = 100
keys = [False, False, False, False]
skybg = pygame.image.load("resources/images/skybg.jpg")
missile = pygame.image.load("resources/images/bullet2.png")
screen = pygame.display.set_mode((1024, 600))
pygame.display.set_caption("SkyFight")
timer = pygame.time.Clock()
# warship sprite
warship_group = pygame.sprite.Group()
# enemy sprite
chopper_group = pygame.sprite.Group()
# player sprite
player_group = pygame.sprite.Group()
player = MySprite()
player.load("resources/images/playerchopper.png", 173, 58, 4)
player.position = 0, 350
player_group.add(player)
# player missile sprite
missile_group = pygame.sprite.Group()
# enemy missile sprite
enemy_missile_group = pygame.sprite.Group()
# warship missile group
warship_missile_group = pygame.sprite.Group()
# flame sprite
flame_group = pygame.sprite.Group() def addNewFlame(position):
flame = MySprite()
flame.load("resources/images/flame.png", 64, 64, 4)
flame.position = position
flame_group.add(flame) # warship flame
warship_flame_group = pygame.sprite.Group() def addNewWarshipFlame(position):
warship_flame = MySprite()
warship_flame.load("resources/images/warship_flame.png", 64, 64, 4)
warship_flame.position = position
warship_flame_group.add(warship_flame) badtimer = 100
badtimer1 = 0
missile_launched = 0
missile_hit = 0
missile_hit_warship = 0
total_enemy_showedup = 0
enemy_missile_launched = 0
warship_health = 10
# to make autopilot missile launch interval
tickstart = []
tickstart.append(pygame.time.get_ticks())
# player move speed
player_move_speed = 5
while True:
# start game ticks
timer.tick(60)
ticks = pygame.time.get_ticks()
screen.fill(0)
# draw background sky
screen.blit(skybg, (0, 0))
# add warship sprite (only one warship on the screen)
if len(warship_group) == 0:
warship = MySprite()
warship.load("resources/images/warship.png", 350, 70, 1)
warship.position = 1024, 500
warship_group.add(warship)
# adjust warship to come close to player
if warship.X < player.X + 200:
warship.X += 1
elif warship.X > player.X + 200:
warship.X -= 1
# draw warship
warship_group.update(ticks)
warship_group.draw(screen) # warship launch missile
for warship in warship_group:
if len(warship_missile_group) == 0:
if warship.X < 800:
warship_missile = MySprite()
warship_missile.load("resources/images/warship_missile.png", 32, 121, 1)
warship_missile.position = warship.X + 160, warship.Y - 60
warship_missile_group.add(warship_missile) # guide missile & change missile position
for warship_missilex in warship_missile_group:
warship_missilex.Y -= 1
if warship_missilex.Y < -121:
warship_missile_group.remove(warship_missilex)
# warship missile & enemy collision detect
collision = None
collision = pygame.sprite.spritecollideany(
warship_missilex, chopper_group)
if collision != None:
if pygame.sprite.collide_circle_ratio(0.65)(warship_missilex, collision):
chopper_group.remove(collision)
flameposition = warship_missilex.position
addNewFlame(flameposition)
# warship missile & enemy missile collision detect
collision = None
collision = pygame.sprite.spritecollideany(
warship_missilex, enemy_missile_group)
if collision != None:
if pygame.sprite.collide_circle_ratio(0.65)(warship_missilex, collision):
enemy_missile_group.remove(collision)
flameposition = warship_missilex.position
addNewFlame(flameposition)
# warship missile & player missile collision detect
collision = None
collision = pygame.sprite.spritecollideany(
warship_missilex, missile_group)
if collision != None:
if pygame.sprite.collide_circle_ratio(0.65)(warship_missilex, collision):
missile_group.remove(collision)
flameposition = warship_missilex.position
addNewFlame(flameposition)
# warship missile & player collision detect
collision = None
collision = pygame.sprite.spritecollideany(
warship_missilex, player_group)
if collision != None:
if pygame.sprite.collide_circle_ratio(0.65)(warship_missilex, collision):
playerHealth -= 10
warship_missile_group.remove(warship_missilex)
flameposition = warship_missilex.position
addNewFlame(flameposition) # add random enenmy chopper
badtimer -= 1
if badtimer == 0:
chopper = MySprite()
chopper.load("resources/images/enemychopper.png", 173, 60, 4)
chopper.position = 1024, rint(0, 400)
chopper_group.add(chopper)
total_enemy_showedup += 1
badtimer = 150 - (badtimer1 * 2)
if badtimer1 >= 35:
badtimer1 = 35
else:
badtimer1 += 5
# change enemy chopper position
for chopper in chopper_group:
chopper.X -= 2
if chopper.X < -173:
chopper_group.remove(chopper)
# enemy chopper launch missile
if chopper.X % 500 == 0:
enemy_missile_launched += 1
enemy_missile = MySprite()
enemy_missile.load("resources/images/missile.png", 64, 16, 1)
enemy_missile.position = chopper.X, chopper.Y + 25
enemy_missile_group.add(enemy_missile)
# change enemy missile position
for enemy_missilex in enemy_missile_group:
enemy_missilex.X -= 4
if enemy_missilex.X < -64:
enemy_missile_group.remove(enemy_missilex)
# enemy missile & player collision detect
collision = None
collision = pygame.sprite.spritecollideany(
enemy_missilex, player_group)
if collision != None:
if pygame.sprite.collide_circle_ratio(0.65)(enemy_missilex, collision):
enemy_missile_group.remove(enemy_missilex)
playerHealth -= 1
flameposition = player.X + 70, player.Y
addNewFlame(flameposition)
# enemy missile & player missile collision detect (to remove enemy/player missile & add flame)
collision = None
collision = pygame.sprite.spritecollideany(
enemy_missilex, missile_group)
if collision != None:
if pygame.sprite.collide_circle_ratio(0.65)(enemy_missilex, collision):
missile_group.remove(collision)
enemy_missile_group.remove(enemy_missilex)
flameposition = enemy_missilex.X, enemy_missilex.Y - 30
addNewFlame(flameposition) # draw enemy chopper spritew
chopper_group.update(ticks)
chopper_group.draw(screen)
# draw player
player_group.update(ticks)
player_group.draw(screen) # change player missile position
for missilex in missile_group:
missilex.velocity.x += 0.5
missilex.X += missilex.velocity.x
if missilex.X > 1056:
missile_group.remove(missilex)
# player missile & enemy chopper collision detect
collision = None
collision = pygame.sprite.spritecollideany(missilex, chopper_group)
if collision != None:
if pygame.sprite.collide_circle_ratio(1)(missilex, collision):
missile_hit += 1
chopper_group.remove(collision)
missile_group.remove(missilex)
flameposition = missilex.X + \
80, missilex.Y - 30
addNewFlame(flameposition)
# player missile & enemy warship collision detect
collision = None
collision = pygame.sprite.spritecollideany(missilex, warship_group)
if collision != None:
if pygame.sprite.collide_circle_ratio(0.65)(missilex, collision):
missile_hit_warship += 1
warship_health -= 1
missile_group.remove(missilex)
warshipflameposition = missilex.X + \
rint(1, 100), missilex.Y - 20
addNewWarshipFlame(warshipflameposition)
# random flame after warship is destroyed
if warship_health == 0:
for i in xrange(20):
position = warship.X + \
rint(-10, 300), warship.Y + \
rint(-20, 100)
addNewFlame(position)
warship_health = 10
warship_group.remove(collision) # enemy collision with player
collision = None
collision = pygame.sprite.spritecollideany(player, chopper_group)
if collision != None:
if pygame.sprite.collide_circle_ratio(0.65)(player, collision):
chopper_group.remove(collision)
playerHealth -= 1
flameposition = player.X + 70, player.Y
addNewFlame(flameposition) # draw player missiles
missile_group.update(ticks)
missile_group.draw(screen) # draw enemy missiles
enemy_missile_group.update(ticks)
enemy_missile_group.draw(screen) # draw warship missile
warship_missile_group.update(ticks)
warship_missile_group.draw(screen) # draw flame
for x in flame_group:
if x.frame == x.last_frame:
flame_group.remove(x)
flame_group.update(ticks)
flame_group.draw(screen) # draw warship flame
for x in warship_flame_group:
if x.frame == x.last_frame:
warship_flame_group.remove(x)
warship_flame_group.update(ticks)
warship_flame_group.draw(screen) # game statistics
font = pygame.font.SysFont(None, 25)
text1 = font.render("Player Health: " +
str(playerHealth), True, (255, 0, 0))
screen.blit(text1, (0, 480))
text2 = font.render("Missile Launched: " +
str(missile_launched), True, (255, 0, 0))
screen.blit(text2, (0, 500))
text3 = font.render("Missile Hit: " +
str(missile_hit), True, (255, 0, 0))
screen.blit(text3, (0, 520))
if not missile_launched == 0:
hitrate = float(missile_hit) / float(missile_launched) * 100
text4 = font.render("Hit Rate: " +
str(hitrate) + "%", True, (255, 0, 0))
else:
text4 = font.render("Hit Rate: " +
"0%", True, (255, 0, 0))
screen.blit(text4, (0, 540))
text5 = font.render("Total Enemies: " +
str(total_enemy_showedup), True, (255, 0, 0))
screen.blit(text5, (0, 560))
text6 = font.render("Enemy Missile Launched: " +
str(enemy_missile_launched), True, (255, 0, 0))
screen.blit(text6, (0, 580)) pygame.display.update() key = pygame.key.get_pressed()
if key[pygame.K_ESCAPE]:
exit()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == K_w:
keys[0] = True
elif event.key == K_a:
keys[1] = True
elif event.key == K_s:
keys[2] = True
elif event.key == K_d:
keys[3] = True
if event.type == pygame.KEYUP:
if event.key == pygame.K_w:
keys[0] = False
elif event.key == pygame.K_a:
keys[1] = False
elif event.key == pygame.K_s:
keys[2] = False
elif event.key == pygame.K_d:
keys[3] = False
# add missile sprite
if event.type == pygame.MOUSEBUTTONDOWN:
pressed_array = pygame.mouse.get_pressed()
for index in range(len(pressed_array)):
if pressed_array[index]:
if index == 0:
missile_launched += 1
missile = MySprite()
missile.load("resources/images/bullet2.png", 32, 16, 1)
missile.position = player.X + \
120, player.Y + 35
missile_group.add(missile)
if event.type == pygame.QUIT:
pygame.quit()
exit() # move player sprite
if keys[0]:
if not player.Y < 0:
player.Y -= player_move_speed
elif keys[1]:
if not player.X < 0:
player.X -= player_move_speed
if keys[2]:
if not player.Y > 500:
player.Y += player_move_speed
elif keys[3]:
if not player.X > 1024:
player.X += player_move_speed # print player.position # auto pilot
if not len(chopper_group) == 0:
enemy = chopper_group.sprites()[0]
posdiffy = enemy.Y - player.Y
# print posdiffy
if posdiffy < -10:
for em in enemy_missile_group:
if abs(em.X - player.X) < 100 and -100 < (em.Y - player.Y) < 0:
keys[0] = False
keys[2] = False
break
else:
keys[0] = True
keys[2] = False
elif posdiffy > 10:
for em in enemy_missile_group:
if abs(em.X - player.X) < 100 and 0 < (em.Y - player.Y) < 100:
keys[0] = False
keys[2] = False
break
else:
keys[0] = False
keys[2] = True
elif -10 <= posdiffy <= 10:
keys[0] = False
keys[2] = False
missile_launched += 1
if len(missile_group) < 2:
if ticks - tickstart[0] > 200:
tickstart.pop(0)
tickstart.append(ticks)
missile = MySprite()
missile.load("resources/images/bullet2.png", 32, 16, 1)
missile.position = player.X + \
120, player.Y + 35
missile_group.add(missile)

资源下载地址:

http://download.csdn.net/download/jailman/10160613

37行代码实现一个简单的打游戏AI的更多相关文章

  1. 通过 Mesos、Docker 和 Go,使用 300 行代码创建一个分布式系统

    [摘要]虽然 Docker 和 Mesos 已成为不折不扣的 Buzzwords ,但是对于大部分人来说它们仍然是陌生的,下面我们就一起领略 Mesos .Docker 和 Go 配合带来的强大破坏力 ...

  2. 100行代码实现最简单的基于FFMPEG+SDL的视频播放器(SDL1.x)【转】

    转自:http://blog.csdn.net/leixiaohua1020/article/details/8652605 版权声明:本文为博主原创文章,未经博主允许不得转载.   目录(?)[-] ...

  3. 通过Mesos、Docker和Go,使用300行代码创建一个分布式系统

    [摘要]虽然 Docker 和 Mesos 已成为不折不扣的 Buzzwords ,但是对于大部分人来说它们仍然是陌生的,下面我们就一起领略 Mesos .Docker 和 Go 配合带来的强大破坏力 ...

  4. 用JavaCV改写“100行代码实现最简单的基于FFMPEG+SDL的视频播放器 ”

    FFMPEG的文档少,JavaCV的文档就更少了.从网上找到这篇100行代码实现最简单的基于FFMPEG+SDL的视频播放器.地址是http://blog.csdn.net/leixiaohua102 ...

  5. 无聊的人用JS实现了一个简单的打地鼠游戏

    直入正题,用JS实现一个简单的打地鼠游戏 因为功能比较简单就直接裸奔JS了,先看看效果图,或者 在线玩玩 吧 如果点击颜色比较深的那个(俗称坏老鼠),将扣分50:如果点击颜色比较浅的那个(俗称好老鼠) ...

  6. Unity 2D游戏开发高速入门第1章创建一个简单的2D游戏

    Unity 2D游戏开发高速入门第1章创建一个简单的2D游戏 即使是如今,非常多初学游戏开发的同学.在谈到Unity的时候.依旧会觉得Unity仅仅能用于制作3D游戏的. 实际上.Unity在2013 ...

  7. 【转】100行代码实现最简单的基于FFMPEG+SDL的视频播放器

    FFMPEG工程浩大,可以参考的书籍又不是很多,因此很多刚学习FFMPEG的人常常感觉到无从下手.我刚接触FFMPEG的时候也感觉不知从何学起. 因此我把自己做项目过程中实现的一个非常简单的视频播放器 ...

  8. Html5游戏开发-145行代码完成一个RPG小Demo

    lufy前辈写过<[代码艺术]17行代码的贪吃蛇小游戏>一文,忽悠了不少求知的兄弟进去阅读,阅读量当然是相当的大.今天我不仿也搞一个这样的教程,目地不在于忽悠人,而在于帮助他人. 先看de ...

  9. 37行代码构建无状态组件通信工具-让恼人的Vuex和Redux滚蛋吧!

    状态管理的现状 很多前端开发者认为,Vuex和Redux是用来解决组件间状态通信问题的,所以大部分人仅仅是用于达到状态共享的目的.但是通常Redux是用于解决工程性问题的,用于分离业务与视图,让结构更 ...

随机推荐

  1. 51nod 1693 水群(神奇的最短路!)

    http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1693 题意: 思路: 这个思路真是神了.. 对于每个点$i$,它需要和$ ...

  2. codevs 1081 线段树练习 2 线段树

    题目描述 Description 给你N个数,有两种操作 1:给区间[a,b]的所有数都增加X 2:询问第i个数是什么? 输入描述 Input Description 第一行一个正整数n,接下来n行n ...

  3. python 将列表中的字符串转为数字

    本文实例讲述了Python中列表元素转为数字的方法.分享给大家供大家参考,具体如下: 有一个数字字符的列表: numbers = ['1', '5', '10', '8'] 想要把每个元素转换为数字: ...

  4. eclipse 里,打开的文件的各个标签,标题乱码。

    Eclipse Mars 版本有这个问题. 提交到社区了,也还是没有人回答.Eclipse看来是没落了. https://www.eclipse.org/forums/index.php/t/1072 ...

  5. LncRNA

    简介:长链非编码RNA(Long non-coding RNA, lncRNA)通过多种机制发挥其生物学功能, 这些机制包括基因印记.染色质重塑.细胞周期调控.剪接调控.mRNA降解和翻译调控等.ln ...

  6. IntelliJ IDEA 进行多线程调试

      idea的断点有不同的模式,只有当Thread模式下才能调试多线程   断点设置步骤: 1.在断点上右键 2.选择Thread,然后点Done(建议选择Thread后点击make default把 ...

  7. Android设计模式之单例模式

    定义 单例模式是一种常用的软件设计模式.在它的核心结构中只包含一个被称为单例的特殊类.通过单例模式可以保证系统中一个类只有一个实例 . 单例模式是设计模式中最简单的形式之一.这一模式的目的是使得类的一 ...

  8. android--------自定义控件ListView实现下拉刷新和上拉加载

    开发项目过程中基本都会用到listView的下拉刷新和上滑加载更多,为了方便重写的ListView来实现下拉刷新,同时添加了上拉自动加载更多的功能. Android下拉刷新可以分为两种情况: 1.获取 ...

  9. Oracle 11g 物理Dataguard日常操作维护(二)

    Oracle 11g 物理Dataguard日常操作维护(二) 2017年8月25日 14:34 3.3 3.3.1 查看备库进程状态 SYS(125_7)@fpyj123> select pr ...

  10. Leetcode 106

    /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode ...