PageRenderTime 57ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/breedingpitradial.py

https://github.com/josomebody/evotank
Python | 473 lines | 432 code | 28 blank | 13 comment | 132 complexity | 176aa3189a8ff35766a6cfa20c12908d MD5 | raw file
  1. import signal
  2. from classes import *
  3. def breedingpit():
  4. random.seed()
  5. print 'Initializing pygame'
  6. pygame.init()
  7. robots = []
  8. pickups = []
  9. bullets = []
  10. protobullet = projectile()
  11. protobot = robot()
  12. you = player()
  13. thisgame = gamedetails()
  14. print "Loading config file..."
  15. configfile = open('config', 'r')
  16. thisgame = pickle.load(configfile)
  17. configfile.close
  18. if thisgame.numbots < 4:
  19. thisgame.numbots = 4
  20. print "Opening display 640x480 full-screen"
  21. screen = pygame.display.set_mode((640, 480), FULLSCREEN)
  22. pygame.display.set_caption('EvoTank')
  23. pygame.mouse.set_visible(False)
  24. gameconsole = console()
  25. print "Loading images..."
  26. font = pygame.font.SysFont("Terminal", 14)
  27. background = pygame.image.load('images/bg.png').convert()
  28. armorpic = pygame.image.load('images/armor.png').convert_alpha()
  29. ammopic = pygame.image.load('images/ammo.png').convert_alpha()
  30. fuelpic = pygame.image.load('images/fuel.png').convert_alpha()
  31. heattx = font.render('HEAT', True, (255, 255, 255))
  32. armortx = font.render('ARMOR', True, (255, 255, 255))
  33. fueltx = font.render('FUEL', True, (255, 255, 255))
  34. ammotx = font.render('AMMO', True, (255, 255, 255))
  35. throttlex = font.render('THROTTLE', True, (255, 255, 255))
  36. picname = 'images/bullet0.png'
  37. bulletpic = pygame.image.load(picname).convert_alpha()
  38. picname = 'images/goodtank0.png'
  39. goodtankpic = pygame.image.load(picname).convert_alpha()
  40. picname = 'images/badtank0.png'
  41. badtankpic = pygame.image.load(picname).convert_alpha()
  42. gameconsole.write("Loading sounds...")
  43. bang = pygame.mixer.Sound('sounds/bang.wav')
  44. clank = pygame.mixer.Sound('sounds/clank.wav')
  45. ping = pygame.mixer.Sound('sounds/ping.wav')
  46. diesound = pygame.mixer.Sound('sounds/die.wav')
  47. lowammosound = pygame.mixer.Sound('sounds/ammo.wav')
  48. lowarmorsound = pygame.mixer.Sound('sounds/armor.wav')
  49. lowfuelsound = pygame.mixer.Sound('sounds/fuel.wav')
  50. overheatsound = pygame.mixer.Sound('sounds/heat.wav')
  51. latersound = pygame.mixer.Sound('sounds/later.wav')
  52. letsgosound = pygame.mixer.Sound('sounds/letsgo.wav')
  53. pygame.mixer.music.load('sounds/breedingpit.ogg')
  54. pygame.mixer.music.set_volume(.5)
  55. pygame.mixer.music.play(-1)
  56. gameconsole.write("Building robots...")
  57. for i in range(thisgame.numbots):
  58. botpath = 'bot' + str(i)
  59. print botpath
  60. if os.path.exists(botpath):
  61. f = open(botpath, 'r')
  62. protobot = pickle.load(f)
  63. else:
  64. gameconsole.write('creating new bot')
  65. protobot.randomizedna()
  66. protobot.showdna()
  67. f = open(botpath, 'w')
  68. pickle.dump(protobot, f)
  69. protobot.dead = 0
  70. protobot.hitstilmating = 5
  71. protobot.state = 0
  72. protobot.armor = maxarmor
  73. protobot.fuel = maxfuel
  74. protobot.ammo = maxammo
  75. protobot.offspring = robot()
  76. robots.append(protobot)
  77. f.close
  78. print robots[i].name
  79. print "*********"
  80. robots[i].showdna()
  81. print "*********"
  82. #initialize game coordinates and shit
  83. ptypes = ['fuel', 'armor', 'ammo']
  84. for i in range(36):
  85. if len(pickups) < 36:
  86. protopickup = pickup()
  87. protopickup.x = random.randrange(640 - pickupsize)
  88. protopickup.y = random.randrange(480 - pickupsize)
  89. protopickup.pickuptype = ptypes[random.randrange(3)]
  90. pickups.append(protopickup)
  91. you.x = random.randrange(640 - tanksize)
  92. you.y = random.randrange(480 - tanksize)
  93. you.rotate = random.randrange(8)
  94. for i in range(len(robots)):
  95. robots[i].x = random.randrange(640 - tanksize)
  96. robots[i].y = random.randrange(480 - tanksize)
  97. robots[i].rotate = random.randrange(8)
  98. robots[i].hits = 0
  99. robotstats = []
  100. robotstatspic = []
  101. bulletcount = 0
  102. lowfuelflag = 0
  103. lowammoflag = 0
  104. lowarmorflag = 0
  105. overheatflag = 0
  106. fps = [0]
  107. fpsavg = 0
  108. frametime = 0
  109. showfps = 1
  110. showconsole = 1
  111. showmeters = 1
  112. code_entry = []
  113. tooslow = 0
  114. dropframe = 0
  115. framedelay = 0
  116. firstframe = 1
  117. #main gameloop
  118. framestarttime = pygame.time.get_ticks()
  119. while 1:
  120. signal.signal(signal.SIGALRM, handler)
  121. signal.alarm(5)
  122. pygame.event.pump()
  123. if fpsavg > 70:
  124. framedelay = (1000 - 1000 / frametime) / 60
  125. #first of all, check for births
  126. for i in range(len(robots)):
  127. if robots[i].gestation == 1:
  128. robots.append(robots[i].givebirth())
  129. gameconsole.write(robots[i].name + ' has given birth to ' + robots[len(robots) - 1].name)
  130. #generate new pickups
  131. if random.randrange(500) == 1:
  132. if len(pickups) < 32:
  133. protopickup = pickup()
  134. protopickup.x = random.randrange(640 - pickupsize)
  135. protopickup.y = random.randrange(480 - pickupsize)
  136. protopickup.pickuptype = ptypes[random.randrange(3)]
  137. gameconsole.write('spawning new pickup of type ' + protopickup.pickuptype)
  138. pickups.append(protopickup)
  139. #draw everybody
  140. if fpsavg < 20:
  141. tooslow = tooslow + 1
  142. if tooslow > 3:
  143. print 'Dropped frame (fps: ' + str(fps[len(fps) - 1]) + ') (average fps for last 100 frames:' + str(fpsavg) + ')'
  144. dropframe = 1
  145. tooslow = 0
  146. else:
  147. tooslow = 0
  148. dropframe = 0
  149. if dropframe == 1:
  150. console.write('frame dropped (' + str(frametime) + ')')
  151. gameconsole.blit(screen, font)
  152. else:
  153. screen.blit(background, (0, 0))
  154. for i in range(len(pickups)):
  155. if pickups[i].pickuptype == 'fuel':
  156. screen.blit(fuelpic, (pickups[i].x, pickups[i].y))
  157. if pickups[i].pickuptype == 'ammo':
  158. screen.blit(ammopic, (pickups[i].x, pickups[i].y))
  159. if pickups[i].pickuptype == 'armor':
  160. screen.blit(armorpic, (pickups[i].x, pickups[i].y))
  161. for i in range(len(bullets)):
  162. drawable = pygame.transform.rotate(bulletpic, 0 - bullets[i].rotate * 45)
  163. screen.blit(drawable, (bullets[i].x, bullets[i].y))
  164. for i in range(len(robots)):
  165. drawable = pygame.transform.rotate(badtankpic, 0 - robots[i].rotate * 45)
  166. screen.blit(drawable, (robots[i].x, robots[i].y))
  167. drawable = pygame.transform.rotate(goodtankpic, 0 - you.rotate * 45)
  168. screen.blit(drawable, (you.x, you.y))
  169. del robotstats[:]
  170. del robotstatspic[:]
  171. for i in range(len(robots)):
  172. robotag = robots[i].name + ' '
  173. if robots[i].state == 10:
  174. robotag = robotag + '(***mating w/ ' + robots[i].partner + '***)'
  175. if robots[i].state == 11:
  176. robotag = robotag + '(***gestating***)'
  177. robotstats.append(robotag)
  178. for i in range(len(robotstats)):
  179. robotstatspic.append(font.render(robotstats[i], True, (255, 0, 0)))
  180. for i in range(len(robots)):
  181. screen.blit(robotstatspic[i], (robots[i].x, robots[i].y))
  182. if showconsole == 1:
  183. gameconsole.blit(screen, font)
  184. if showmeters == 1:
  185. pygame.draw.rect(screen, (64, 0, 0), (0, 470, you.heat / 20, 10))
  186. pygame.draw.rect(screen, (0, 0, 64), (210, 470, you.armor, 10))
  187. pygame.draw.rect(screen, (0, 64, 0), (320, 470, (you.fuel / 50), 10))
  188. pygame.draw.rect(screen, (32, 32, 64), (430, 470, you.ammo, 10))
  189. if you.velocity < -1:
  190. pygame.draw.rect(screen, (64, 64, 0), (550, 470, 25, 10))
  191. if you.velocity < 0:
  192. pygame.draw.rect(screen, (64, 64, 0), (575, 470, 25, 10))
  193. if you.velocity > 0:
  194. pygame.draw.rect(screen, (64, 64, 0), (600, 470, 25, 10))
  195. if you.velocity > 1:
  196. pygame.draw.rect(screen, (64, 64, 0), (625, 470, 25, 10))
  197. screen.blit(heattx, (0, 470))
  198. screen.blit(armortx, (210, 470))
  199. screen.blit(fueltx, (320, 470))
  200. screen.blit(ammotx, (430, 470))
  201. screen.blit(throttlex, (565, 470))
  202. if showfps == 1:
  203. fpsstring = 'fps: ' + str(fpsavg)
  204. fpspic = font.render(fpsstring, True, (255, 128, 0))
  205. screen.blit(fpspic, (640 - len(fpsstring) * 7, 0))
  206. dropframe = 0
  207. if firstframe == 1:
  208. letsgopic = font.render('LET\'S GO!', True, (255, 255, 255))
  209. screen.blit(letsgopic, (257, 233))
  210. pygame.display.flip()
  211. letsgosound.play(0)
  212. firstframe = 0
  213. pygame.display.flip()
  214. #everybody gets a turn
  215. for event in pygame.event.get():
  216. if event.type == KEYDOWN:
  217. if event.key == K_q:
  218. gameconsole.write('SELF-DESTRUCT')
  219. you.armor = 0
  220. elif event.key == K_f:
  221. if showfps == 0:
  222. showfps = 1
  223. elif showfps == 1:
  224. showfps = 0
  225. else:
  226. showfps = 0
  227. elif event.key == K_c:
  228. if showconsole == 0:
  229. showconsole = 1
  230. else:
  231. showconsole = 0
  232. elif event.key == K_m:
  233. if showmeters == 0:
  234. showmeters = 1
  235. else:
  236. showmeters = 0
  237. elif (event.key == K_UP) or (event.key == K_DOWN) or (event.key == K_LEFT) or (event.key == K_RIGHT) or (event.key == K_SPACE):
  238. you.control(event.key, bullets, bang)
  239. else:
  240. code_entry.append(event.key)
  241. for i in range(len(robots)):
  242. robots[i].letsgo(bullets, pickups, robots, you, bang, i)
  243. #move everybody
  244. if dropframe != 1:
  245. for i in range(len(bullets)):
  246. bullets[i].move()
  247. for i in range(len(robots)):
  248. robots[i].move()
  249. you.move() #if your machine is going too slow, you get bullet-time!
  250. #and now the expensive part: collision checks and shit
  251. if dropframe != 1:
  252. for i in range(len(bullets)):
  253. if bullets[i].offscreen() == 1:
  254. bullets[i].dead = 1
  255. for i in range(len(bullets)):
  256. if (detect_collision(bullets[i], bulletsize, you, tanksize) == 1) and (bullets[i].originator != you.name):
  257. you.armor = you.armor - 5
  258. for j in range(len(robots)):
  259. if bullets[i].originator == robots[j].name:
  260. robots[j].hits = robots[j].hits + 1
  261. robots[j].hitstilmating = robots[j].hitstilmating - 1
  262. if robots[j].hitstilmating < 0:
  263. robots[j].hitstilmating = 5
  264. gameconsole.write((robots[j].name + ' scored hit #' + str(robots[j].hits)))
  265. bullets[i].dead = 1
  266. clank.play(0)
  267. for i in range(len(bullets)):
  268. for j in range(len(robots)):
  269. if (detect_collision(bullets[i], bulletsize, robots[j], tanksize) == 1) and (bullets[i].originator != robots[j].name):
  270. robots[j].armor = robots[j].armor - 5
  271. bullets[i].dead = 1
  272. clank.play(0)
  273. for i in range(len(pickups)):
  274. if detect_collision(pickups[i], pickupsize, you, tanksize) == 1:
  275. if you.cangetpickup(pickups[i].pickuptype):
  276. you.getpickup(pickups[i].pickuptype)
  277. pickups[i].dead = 1
  278. ping.play(0)
  279. for i in range(len(pickups)):
  280. for j in range(len(robots)):
  281. if detect_collision(pickups[i], pickupsize, robots[j], tanksize) == 1:
  282. if robots[j].cangetpickup(pickups[i].pickuptype):
  283. robots[j].getpickup(pickups[i].pickuptype)
  284. pickups[i].dead = 1
  285. ping.play(0)
  286. for i in range(len(robots)):
  287. if detect_collision(robots[i], tanksize, you, tanksize) == 1:
  288. bounce(robots[i], you)
  289. clank.play(0)
  290. for j in range(len(robots)):
  291. if i != j:
  292. if detect_collision(robots[i], tanksize, robots[j], tanksize) == 1:
  293. bounce(robots[i], robots[j])
  294. clank.play(0)
  295. #and now for the sad part: coping with death
  296. if you.armor <= 0:
  297. diesound.play(0)
  298. #figure out which bot did the best
  299. scores = []
  300. for i in range(len(robots)):
  301. iscore = computescore(robots[i])
  302. scores.append(iscore)
  303. winner = 0
  304. for i in range(len(scores)):
  305. if scores[i] > scores[winner]:
  306. winner = i
  307. gameconsole.write("SCORES:")
  308. for i in range(len(robots)):
  309. gameconsole.write(robots[i].name + ": " + str(scores[i]))
  310. gameconsole.write(robots[winner].name + " is the winner with a score of" + str(scores[winner]))
  311. for i in range(len(robots)):
  312. gameconsole.write('saving ' + robots[i].name + ' in file bot' + str(i))
  313. f = open('bot' + str(i), 'w')
  314. pickle.dump(robots[i], f)
  315. f.close
  316. thisgame.numbots = len(robots)
  317. gameconsole.write('saving configfile for ' + str(thisgame.numbots) + ' robots')
  318. configfile = open('config', 'w')
  319. pickle.dump(thisgame, configfile)
  320. configfile.close
  321. screen.blit(background,(0,0))
  322. gameconsole.write('you got pwned. continue? y/N')
  323. gameconsole.blit(screen, font)
  324. pygame.display.flip()
  325. pygame.time.wait(1000)
  326. choicekey = 0
  327. signal.alarm(0)
  328. while choicekey != K_y:
  329. for event in pygame.event.get():
  330. if event.type == KEYDOWN:
  331. choicekey = event.key
  332. if event.key == K_y:
  333. signal.alarm(5)
  334. you.armor = 100
  335. firstframe = 1
  336. gameconsole.write('continuing after getting pwned')
  337. elif event.key == K_n:
  338. latersound.play(0)
  339. pygame.time.wait(1500)
  340. return 0
  341. for i in range(len(robots)):
  342. if robots[i].armor <=0:
  343. robots[i].dead = 1
  344. gameconsole.write(robots[i].name + ' died.')
  345. if len(robots) == 1:
  346. gameconsole.write(robots[0].name + " is the only survivor with a score of " + str(computescore(robots[i])))
  347. robots[0].armor = maxarmor
  348. f = open('bot0', 'w')
  349. pickle.dump(robots[0], f)
  350. gameconsole.write('saving ' + robots[0].name + ' in file bot0')
  351. f.close
  352. protobot = robots[0]
  353. protobot.mutate()
  354. protobot.name = generatename()
  355. protobot.x = random.randrange(640 - tanksize)
  356. protobot.y = random.randrange(480 - tanksize)
  357. robots.append(protobot)
  358. f = open('bot1', 'w')
  359. pickle.dump(protobot, f)
  360. gameconsole.write('saving ' + protobot.name + ' in file bot1')
  361. f.close
  362. thisgame.numbots = 1
  363. gameconsole.write('saving configfile for ' + str(thisgame.numbots) + ' robots')
  364. configfile = open('config', 'w')
  365. pickle.dump(thisgame, configfile)
  366. configfile.close
  367. gameconsole.write('do you wanna start over? y/n')
  368. screen.blit(background, (0, 0))
  369. gameconsole.blit(screen, font)
  370. pygame.display.flip()
  371. choicekey = 0
  372. signal.alarm(0)
  373. while choicekey != K_y:
  374. for event in pygame.event.get():
  375. if event.type == KEYDOWN:
  376. choicekey = event.key
  377. if event.key == K_y:
  378. return 1
  379. elif event.key == K_n:
  380. latersound.play(0)
  381. pygame.time.wait(1500)
  382. return 0
  383. if len(robots) < 1: #if there's a mass extinction somehow, just don't propagate and this generation gets another chance.
  384. print "Mass extinction."
  385. return 0
  386. #and getting rid of the bodies
  387. if dropframe != 1:
  388. for i in range(len(robots)):
  389. if i < len(robots):
  390. if robots[i].dead == 1:
  391. del robots[i]
  392. diesound.play(0)
  393. for i in range(len(bullets)):
  394. if i < len(bullets):
  395. if bullets[i].dead == 1:
  396. del bullets[i]
  397. for i in range(len(pickups)):
  398. if i < len(pickups):
  399. if pickups[i].dead ==1:
  400. del pickups[i]
  401. #and playing game warning sounds
  402. if you.armor < 50:
  403. if lowarmorflag == 0:
  404. lowarmorsound.play(0)
  405. lowarmorflag = 1
  406. else:
  407. lowarmorflag = 0
  408. if you.ammo < 10:
  409. if lowammoflag == 0:
  410. lowammosound.play(0)
  411. lowammoflag = 1
  412. else:
  413. lowammoflag = 0
  414. if you.fuel < 1000:
  415. if lowfuelflag == 0:
  416. lowfuelsound.play(0)
  417. lowfuelflag = 1
  418. else:
  419. lowfuelflag = 0
  420. if you.heat > 1000:
  421. if overheatflag == 0:
  422. overheatsound.play(0)
  423. overheatflag = 1
  424. elif you.heat < 950:
  425. overheatflag = 0
  426. #get the fps so we can act accordingly
  427. if (framedelay > 1) and (framedelay < 16):
  428. pygame.time.wait(framedelay)
  429. frametime = pygame.time.get_ticks() - framestarttime
  430. if frametime > 0: #you never know. if a frame is executed in less than 1 ms, don't worry about it
  431. fps.append(1000 / frametime)
  432. if len(fps) > 100:
  433. del fps[0]
  434. fpsavg = sum(fps) / len(fps)
  435. framestarttime = pygame.time.get_ticks()
  436. signal.alarm(0)
  437. def handler(signum, frame):
  438. print "CRASH! Frame got stuck!"
  439. raise SystemExit
  440. def main():
  441. startagain = 1
  442. while startagain == 1:
  443. startagain = breedingpit()
  444. raise SystemExit
  445. main()