PageRenderTime 62ms CodeModel.GetById 29ms RepoModel.GetById 1ms app.codeStats 0ms

/breedingpit.py

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