PageRenderTime 53ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/Main.py

http://satdash.googlecode.com/
Python | 1016 lines | 948 code | 44 blank | 24 comment | 15 complexity | 772a30cd19eafc4d4ba3e096ba891356 MD5 | raw file
  1. '''
  2. Satellite Dash v0.1
  3. '''
  4. import sys, pygame, random, math
  5. from pygame.locals import *
  6. from random import *
  7. import Lib
  8. from Lib import *
  9. import Config
  10. from Config import config
  11. # constants
  12. global assets
  13. global objects
  14. global particles
  15. global game
  16. # game parameters
  17. game = None
  18. # hash of all assets
  19. assets = dict()
  20. # list of all objects - objects, debris etc
  21. objects = list()
  22. # list of all particles
  23. particles = list()
  24. # cursor class (ccur)
  25. class Cursor(Animation):
  26. imageNormal = None
  27. imagePressed = None
  28. isPressed = 0
  29. position = list()
  30. startTime = 0
  31. # grabbed satellite
  32. grabbed = None
  33. # grabbed animation
  34. animGrabbed = None
  35. def __init__(self, iNormal, iPressed):
  36. self.imageNormal = iNormal
  37. self.imagePressed = iPressed
  38. self.image = self.imageNormal
  39. self.numFrames = 1
  40. self.position = pygame.mouse.get_pos()
  41. self.rect = self.image.get_rect()
  42. self.frameDelay = config['animationCursorDelay']
  43. # paint mouse cursor
  44. def paint(self, screen):
  45. pos = pygame.mouse.get_pos()
  46. self.rect.centerx = pos[0]
  47. self.rect.centery = pos[1]
  48. if self.isPressed:
  49. Animation.paint(self, screen)
  50. else:
  51. screen.blit(self.image, self.rect)
  52. # paint pixel trail from cursor to grabbed satellite
  53. def paintTrail(self, screen):
  54. pos = pygame.mouse.get_pos()
  55. ln = math.floor(0.15 * math.sqrt((self.grabbed.fx - pos[0]) * \
  56. (self.grabbed.fx - pos[0]) + \
  57. (self.grabbed.fy - pos[1]) *
  58. (self.grabbed.fy - pos[1])))
  59. dx = self.grabbed.fx - pos[0]
  60. dy = self.grabbed.fy - pos[1]
  61. m = max(abs(dx), abs(dy)) / 5
  62. dx /= m
  63. dy /= m
  64. xbase = pos[0]
  65. ybase = pos[1]
  66. for i in xrange(0, int(ln)):
  67. xbase += dx
  68. ybase += dy
  69. self.paintTrailRandom(screen, xbase, ybase)
  70. self.paintTrailRandom(screen, xbase, ybase)
  71. self.paintTrailRandom(screen, xbase, ybase)
  72. def paintTrailRandom(self, screen, xbase, ybase):
  73. x = xbase - 20 + random() * 40
  74. y = ybase - 20 + random() * 40
  75. c = choice(config['trailColors'])
  76. col = Color(c[0], c[1], c[2])
  77. screen.set_at((int(x), int(y)), col)
  78. # set pressed state
  79. def setPressed(self, state):
  80. self.isPressed = state
  81. self.position = pygame.mouse.get_pos()
  82. if self.isPressed:
  83. self.image = self.imagePressed
  84. self.numFrames = 4
  85. self.startTime = pygame.time.get_ticks()
  86. # check for satellite to grab
  87. for o in objects:
  88. o.checkGrabbed()
  89. # satellite grabbed, make animation
  90. if self.grabbed != None:
  91. self.animGrabbed = Animation()
  92. self.animGrabbed.image = assets['satSelected']
  93. self.animGrabbed.numFrames = 2
  94. else:
  95. self.image = self.imageNormal
  96. self.numFrames = 1
  97. self.startTime = 0
  98. self.animGrabbed = None
  99. self.grabbed = None
  100. # update state
  101. def update(self, ticks):
  102. # check for grab release
  103. if self.isPressed and ticks - self.startTime > config['grabTime']:
  104. self.setPressed(0)
  105. self.grabbed = None;
  106. self.position = pygame.mouse.get_pos()
  107. if self.grabbed != None:
  108. # update mouse delta
  109. dx = self.position[0] - self.grabbed.fx
  110. dy = self.position[1] - self.grabbed.fy
  111. # print 'd:', dx, dy
  112. # normalize dx,dy
  113. m = max(abs(dx), abs(dy))
  114. fdx = 0
  115. fdy = 0
  116. if m > 0:
  117. fdx = config['maxObjectSpeed'] * float(dx) / float(m)
  118. fdy = config['maxObjectSpeed'] * float(dy) / float(m)
  119. # print 'd:', dx, dy, 'f:', fdx, fdy, ' m:', m
  120. if fdx != 0:
  121. if abs(fdx) > abs(dx):
  122. fdx = dx
  123. self.grabbed.dirx = fdx
  124. if fdy != 0:
  125. if abs(fdy) > abs(dy):
  126. fdy = dy
  127. self.grabbed.diry = fdy
  128. pass
  129. pass
  130. pass
  131. # world object class (cwo) - satellites, debris, etc
  132. class WorldObject(Animation):
  133. # object type
  134. type = ''
  135. # life
  136. life = 1
  137. # current direction
  138. dx = 0.0
  139. dy = 0.0
  140. # float x,y
  141. fx = 0
  142. fy = 0
  143. # goal direction
  144. dirx = 0.0
  145. diry = 0.0
  146. # collision timeout parameters
  147. collideTime = 0
  148. isCollided = 0
  149. # object alive?
  150. isDead = 0
  151. # object was grabbed at some point
  152. isTouched = 0
  153. def __init__(self, type, onEdge = 0):
  154. self.__dict__['type'] = type
  155. if self.type == 'satellite':
  156. self.image = assets['satellite']
  157. self.life = config['satelliteLife']
  158. elif self.type == 'debris':
  159. self.image = assets['rock']
  160. self.life = 1
  161. # check for collision
  162. while 1:
  163. # spawn objects on screen edges during the game
  164. if not onEdge:
  165. x = randint(0, config['screenWidth'])
  166. y = randint(0, config['screenHeight'])
  167. else:
  168. x = randint(0, config['screenWidth'])
  169. y = randint(0, config['screenHeight'])
  170. if random() > 0.5:
  171. if random() > 0.5:
  172. x = 0
  173. else:
  174. x = config['screenWidth'] - 1
  175. else:
  176. if random() > 0.5:
  177. y = 0
  178. else:
  179. y = config['screenHeight'] - 1
  180. r = self.image.get_rect()
  181. if (self.numFrames > 1):
  182. r.width = 32
  183. r.height = 32
  184. self.__dict__['rect'] = Rect(x, y, r.width, r.height)
  185. ok = 1
  186. for o2 in objects:
  187. if self.rect.colliderect(o2.rect):
  188. ok = 0
  189. if ok:
  190. break
  191. pass
  192. self.__dict__['dirx'] = config['objectSpeed'] * random() - 1
  193. self.__dict__['diry'] = config['objectSpeed'] * random() - 1
  194. self.__dict__['fx'] = self.rect.centerx
  195. self.__dict__['fy'] = self.rect.centery
  196. pass
  197. # setting attributes
  198. def __setattr__(self, name, value):
  199. if name == 'fx':
  200. self.__dict__['fx'] = value
  201. self.rect.centerx = value
  202. elif name == 'fy':
  203. self.__dict__['fy'] = value
  204. self.rect.centery = value
  205. else:
  206. self.__dict__[name] = value
  207. pass
  208. # paint this (cwop)
  209. def paint(self, screen):
  210. Animation.paint(self, screen)
  211. # show satellite movement direction
  212. if self.type == 'satellite' and config['debugShowDir']:
  213. r = Rect(self.rect.left, self.rect.top, 15, 15)
  214. r.centerx += 32 + self.dx * 10
  215. r.centery += 32 + self.dy * 10
  216. screen.blit(assets['dir'], r)
  217. # this object grabbed
  218. if cursor.grabbed == self:
  219. cursor.animGrabbed.rect.x = self.rect.left
  220. cursor.animGrabbed.rect.y = self.rect.top
  221. Animation.paint(cursor.animGrabbed, screen)
  222. pass
  223. # check for grabbing this object
  224. def checkGrabbed(self):
  225. # only satellites can be grabbed
  226. if self.type != 'satellite':
  227. return 0
  228. r = cursor.rect
  229. rect = Rect(cursor.position[0], cursor.position[1], \
  230. r.width, r.height)
  231. if self.rect.colliderect(rect):
  232. cursor.grabbed = self
  233. self.isTouched = 1
  234. if config['playSound']:
  235. assets['sndGrab'].stop()
  236. assets['sndGrab'].play()
  237. return 1
  238. return 0
  239. pass
  240. # get $val damage from $obj (cwod)
  241. def damage(self, obj, val):
  242. # remove hp
  243. self.life -= val
  244. # change image
  245. img = ''
  246. if self.type == 'satellite':
  247. img = 'satellite'
  248. if self.life == config['satelliteLife'] - 1:
  249. img = 'satelliteDamaged1'
  250. elif self.life == config['satelliteLife'] - 2:
  251. img = 'satelliteDamaged2'
  252. elif self.type == 'debris':
  253. img = 'rock'
  254. self.image = assets[img]
  255. # object alive
  256. if self.life > 0:
  257. return
  258. # death
  259. self.isDead = 1
  260. # clean grabbed state from cursor
  261. if cursor.grabbed == self:
  262. cursor.setPressed(0)
  263. if self.type == 'satellite' or obj.type == 'satellite':
  264. points = 0
  265. # more points if both objects satellites
  266. if self.type == 'satellite' and obj.type == 'satellite':
  267. points = game.level
  268. elif self.type == 'satellite':
  269. points = 1
  270. if points > 0:
  271. game.addPoints(points)
  272. # create text
  273. e = Particle('text', '', self.rect.centerx, \
  274. self.rect.centery - 10, 0, - 0.25)
  275. e.setText('+' + str(points))
  276. particles.append(e)
  277. # create explosion
  278. if self.type == 'satellite':
  279. e = Particle('image', assets['explosion'], \
  280. self.rect.left, self.rect.top, self.dx, self.dy)
  281. elif self.type == 'debris':
  282. e = Particle('image', assets['rockExplosion'], \
  283. self.rect.left, self.rect.top, self.dx, self.dy)
  284. e.frameDelay = config['animationRockExplosionDelay']
  285. e.lifeTime = config['rockExplosionLifeTime']
  286. particles.append(e)
  287. # delete object
  288. try:
  289. objects.remove(self)
  290. except:
  291. pass
  292. pass
  293. # check for collisions between two objects
  294. def checkCollision(self, o):
  295. if self == o or not self.rect.colliderect(o.rect):
  296. return
  297. # one of objects is already collided, waiting for timeout
  298. if self.isCollided or o.isCollided:
  299. return
  300. # get 1 damage
  301. self.damage(o, 1)
  302. o.damage(self, 1)
  303. # play appropriate sound
  304. if config['playSound']:
  305. if self.isDead or o.isDead:
  306. assets['sndExplosion'].play()
  307. else:
  308. assets['sndHit'].play()
  309. # bounce, change dir
  310. dirx = self.dirx - o.dirx
  311. diry = self.diry - o.diry
  312. o.dirx = dirx
  313. o.diry = diry
  314. self.dirx = - dirx
  315. self.diry = - diry
  316. # print 'self:', self.dirx, self.diry, 'o:', o.dirx, o.diry
  317. # waitForEvent()
  318. # move both in that dir
  319. if not self.isDead:
  320. self.fx += self.dirx
  321. self.fy += self.diry
  322. if not o.isDead:
  323. o.fx += o.dirx
  324. o.fy += o.diry
  325. # set collision timeout for both objects
  326. self.isCollided = 1
  327. self.collideTime = pygame.time.get_ticks()
  328. o.isCollided = 1
  329. o.collideTime = pygame.time.get_ticks()
  330. # if self == cursor.grabbed or o == cursor.grabbed:
  331. # cursor.setPressed(0)
  332. pass
  333. # update state (object movement) (cwou)
  334. def update(self, prevTicks, ticks):
  335. msec = ticks - prevTicks
  336. # remove collision timeout
  337. if self.isCollided and ticks - self.collideTime > config['collisionTimeout']:
  338. self.isCollided = 0
  339. # slightly randomize movement
  340. self.dirx += - 0.1 + 0.2 * random()
  341. self.diry += - 0.1 + 0.2 * random()
  342. # correct movement speed if not grabbed
  343. if cursor.grabbed != self and \
  344. math.hypot(self.dirx, self.diry) > config['objectSpeed']:
  345. # normalize to speed
  346. m = max(abs(self.dirx), abs(self.diry))
  347. self.dirx /= m
  348. self.diry /= m
  349. self.dirx *= config['objectSpeed']
  350. self.diry *= config['objectSpeed']
  351. # change slightly delta to dir
  352. self.dx += (self.dirx - self.dx) / 10.0
  353. self.dy += (self.diry - self.dy) / 10.0
  354. # change position by delta
  355. self.fx += 3 * float(self.dx) / float(msec)
  356. self.fy += 3 * float(self.dy) / float(msec)
  357. # check boundaries
  358. if self.fx >= config['screenWidth']:
  359. self.fx = 1
  360. if self.fx <= 0:
  361. self.fx = config['screenWidth'] - 1
  362. if self.fy >= config['screenHeight']:
  363. self.fy = 1
  364. if self.fy <= 0:
  365. self.fy = config['screenHeight'] - 1
  366. # spawn trail sprite if damaged
  367. if self.type == 'satellite' and \
  368. self.life < config['satelliteLife'] and \
  369. ((self.life > 1 and random() < 0.01) or \
  370. (self.life == 1 and random() < 0.03)):
  371. e = Particle('image', assets['explosion'], self.fx, self.fy, 0, 0)
  372. e.setTrail()
  373. particles.append(e)
  374. pass
  375. pass
  376. pass
  377. # particle class (cpart)
  378. class Particle(Animation):
  379. type = ''
  380. text = ''
  381. startTime = 0
  382. lifeTime = config['explosionLifeTime']
  383. # float x,y
  384. fx = 0.0
  385. fy = 0.0
  386. # movement delta
  387. dx = 0.0
  388. dy = 0.0
  389. # trail parameters
  390. isTrail = 0
  391. trailLength = 0
  392. trailSpawnTime = 0
  393. def __init__(self, type, img, x, y, dx, dy):
  394. self.startTime = pygame.time.get_ticks()
  395. self.type = type
  396. if self.type == 'image':
  397. self.fx = x
  398. self.fy = y
  399. self.setImage(img)
  400. # normalize dir
  401. m = max(abs(dx), abs(dy))
  402. if m > 0:
  403. self.dx = 0.5 * dx / m
  404. self.dy = 0.5 * dy / m
  405. elif self.type == 'text':
  406. self.fx = x
  407. self.fy = y
  408. self.dx = dx
  409. self.dy = dy
  410. pass
  411. # set image
  412. def setImage(self, img):
  413. self.image = img
  414. self.frameDelay = config['animationExplosionDelay']
  415. self.rect = Rect(self.fx, self.fy, self.image.get_rect().height, \
  416. self.image.get_rect().height)
  417. self.fx = self.rect.centerx
  418. self.fy = self.rect.centery
  419. pass
  420. # set text
  421. def setText(self, text):
  422. self.text = text
  423. self.rect = Rect(self.fx - 10, self.fy - 10, 0, 0)
  424. pass
  425. # paint this
  426. def paint(self, screen):
  427. global font
  428. if self.type == 'image':
  429. Animation.paint(self, screen)
  430. elif self.type == 'text':
  431. font.paint(screen, (self.rect.x, self.rect.y), self.text)
  432. # set trail var
  433. def setTrail(self):
  434. self.isTrail = 1
  435. self.image = assets['smoke']
  436. self.rect.centerx -= 16
  437. self.rect.centery -= 16
  438. # update state
  439. def update(self, ticks):
  440. global particles
  441. # remove explosion on timeout
  442. if ticks - self.startTime > self.lifeTime:
  443. particles.remove(self)
  444. if self.isTrail:
  445. return
  446. if self.type == 'image' and self.image == assets['explosion']:
  447. # spawn trail sprite
  448. if ticks - self.trailSpawnTime > 200 :
  449. e = Particle('image', assets['explosion'], self.fx, self.fy, 0, 0)
  450. e.setTrail()
  451. particles.append(e)
  452. self.trailSpawnTime = ticks
  453. self.trailLength += 1
  454. # movement
  455. self.fx += self.dx
  456. self.fy += self.dy
  457. self.rect.centerx = self.fx
  458. self.rect.centery = self.fy
  459. pass
  460. pass
  461. # main game class (cgam)
  462. class Game:
  463. points = 0
  464. level = config['startLevel']
  465. numSatellites = 0
  466. numDebris = 0
  467. time = config['startTime']
  468. warnStartTime = 0
  469. # timer ticks
  470. prevTicks = pygame.time.get_ticks()
  471. ticks = prevTicks + 1
  472. #isPaused = False
  473. isFinished = False
  474. def __init__(self):
  475. global objects
  476. # init cursor
  477. cursor.setPressed(0)
  478. self.numDebris = self.level
  479. self.numSatellites = 2 + self.level / 2
  480. objects = list()
  481. # spawn objects
  482. for i in xrange(self.numSatellites):
  483. o = WorldObject('satellite')
  484. for o2 in objects:
  485. if o.rect.colliderect(o2.rect):
  486. o = WorldObject('satellite')
  487. objects.append(o)
  488. pass
  489. # spawn debris
  490. for i in xrange(self.numDebris):
  491. o = WorldObject('debris')
  492. for o2 in objects:
  493. if o.rect.colliderect(o2.rect):
  494. o = WorldObject('debris')
  495. objects.append(o)
  496. pass
  497. # for i in xrange(1, 10):
  498. # print i, 850.0 * float(2 + 0.5 * i) / (float(i))
  499. # print 'd', i, 500.0 * float(1 + 1.0) / (float(i))
  500. pass
  501. # add points, raise level if needed
  502. def addPoints(self, points):
  503. time = config['levelTime'][self.level]
  504. if points == 1 and self.level > 1:
  505. time /= 4.0
  506. self.points += points
  507. self.time += time
  508. # print 'PTS', points, 'T+', time
  509. # check for new level
  510. newLevel = 0
  511. for l in config['levelPoints']:
  512. if self.points >= l:
  513. newLevel += 1
  514. pass
  515. # level not raised
  516. if self.level >= newLevel:
  517. return
  518. # raise level and difficulty
  519. self.level = newLevel
  520. self.numDebris = self.level
  521. self.numSatellites = 2 + self.level / 2
  522. # play sound
  523. if config['playSound']:
  524. assets['sndLevel'].play()
  525. # print 'l:', self.level, 'sats:', self.numSatellites, 'debris:',\
  526. # self.numDebris
  527. pass
  528. # check for game finish
  529. def checkFinish(self):
  530. # player still has time
  531. if self.time > 0:
  532. return
  533. self.isFinished = True
  534. pass
  535. # update game state (cgamup)
  536. def update(self):
  537. # count number of ticks passed
  538. self.ticks = pygame.time.get_ticks()
  539. # time passed
  540. self.time -= (self.ticks - self.prevTicks)
  541. if self.ticks - self.prevTicks == 0:
  542. return
  543. # warning sound when time is low
  544. if self.time <= 5000 and self.ticks - self.warnStartTime > 500:
  545. self.warnStartTime = self.ticks
  546. if config['playSound']:
  547. assets['sndTime'].play()
  548. # check for finish
  549. self.checkFinish()
  550. # update cursor
  551. cursor.update(self.ticks)
  552. # update particles
  553. for p in particles:
  554. p.update(self.ticks)
  555. # update objects
  556. for o in objects:
  557. o.update(self.prevTicks, self.ticks)
  558. # check objects for collisions
  559. for o in objects:
  560. for o2 in objects:
  561. o.checkCollision(o2)
  562. # spawn more satellites if needed
  563. cnt = countObjects('satellite')
  564. if cnt < self.numSatellites:
  565. o = WorldObject('satellite', 1)
  566. objects.append(o)
  567. # spawn more debris if needed
  568. cnt = countObjects('debris')
  569. if cnt < self.numDebris:
  570. o = WorldObject('debris', 1)
  571. objects.append(o)
  572. self.prevTicks = self.ticks
  573. pass
  574. pass
  575. # load all assets
  576. def loadAssets():
  577. global assets
  578. # images
  579. assets['bg'] = pygame.image.load("assets/bg.png").convert()
  580. assets['cursorNormal'] = pygame.image.load("assets/cursor.png").convert()
  581. assets['cursorPressed'] = pygame.image.load("assets/cursor_pressed.png").convert()
  582. assets['dir'] = pygame.image.load("assets/dir.png").convert()
  583. assets['satellite'] = pygame.image.load("assets/sat1.png").convert()
  584. assets['satelliteDamaged1'] = pygame.image.load("assets/sat1_dmg1.png").convert()
  585. assets['satelliteDamaged2'] = pygame.image.load("assets/sat1_dmg2.png").convert()
  586. assets['satSelected'] = pygame.image.load("assets/sat_sel.png").convert()
  587. assets['explosion'] = pygame.image.load("assets/explosion.png").convert()
  588. assets['explosionTrail'] = pygame.image.load("assets/explosion_trail.png").convert()
  589. assets['smoke'] = pygame.image.load("assets/smoke.png").convert()
  590. assets['rock'] = pygame.image.load("assets/rock.png").convert()
  591. assets['rockExplosion'] = pygame.image.load("assets/rock_explosion.png").convert()
  592. # sounds
  593. if config['playSound']:
  594. assets['sndExplosion'] = pygame.mixer.Sound("assets/snd_explosion.ogg")
  595. assets['sndGrab'] = pygame.mixer.Sound("assets/snd_grab.ogg")
  596. assets['sndHit'] = pygame.mixer.Sound("assets/snd_hit.ogg")
  597. assets['sndLevel'] = pygame.mixer.Sound("assets/snd_level.ogg")
  598. assets['sndTime'] = pygame.mixer.Sound("assets/snd_time.ogg")
  599. pass
  600. # event handling
  601. def handleEvents():
  602. for e in pygame.event.get():
  603. if e.type == pygame.QUIT:
  604. pygame.quit()
  605. sys.exit()
  606. elif e.type == pygame.KEYDOWN:
  607. # esc exits game
  608. if e.key == K_ESCAPE:
  609. pygame.quit()
  610. sys.exit()
  611. if e.key == K_SPACE:
  612. #game.isPaused = True
  613. introText(("Game is paused.",
  614. "Press any key to continue"))
  615. # clean ticks because of pause
  616. game.prevTicks = pygame.time.get_ticks()
  617. # game.isPaused = False
  618. # F12 - toggle fullscreen
  619. # elif e.key == K_F12:
  620. # print 'ok'
  621. # pygame.display.toggle_fullscreen()
  622. # mouse pressed
  623. elif e.type == pygame.MOUSEBUTTONDOWN and e.button == 1:
  624. cursor.setPressed(1)
  625. # mouse released
  626. elif e.type == pygame.MOUSEBUTTONUP and e.button == 1:
  627. cursor.setPressed(0)
  628. pass
  629. # count number of objects of this type
  630. def countObjects(type):
  631. cnt = 0
  632. for o in objects:
  633. if o.type == type:
  634. cnt += 1
  635. return cnt
  636. pass
  637. # paint status panel
  638. def paintStatus():
  639. text = 'Level: ' + str(game.level) + \
  640. ' Points: ' + str(int(game.points)) + \
  641. ' Time left: '
  642. if game.time >= 10000:
  643. text += str(int(game.time / 1000))
  644. else:
  645. text += '%.1f' % float(game.time / 1000.0)
  646. font.paint(screen, (10, config['screenHeight'] - 13), text.upper())
  647. pass
  648. # paint screen
  649. def paintScreen():
  650. # paint trail
  651. if cursor.grabbed != None:
  652. cursor.paintTrail(screen)
  653. # paint objects
  654. for o in objects:
  655. o.paint(screen)
  656. # paint grabbed satellite
  657. if cursor.grabbed != None:
  658. cursor.grabbed.paint(screen)
  659. # paint particles
  660. for e in reversed(particles):
  661. e.paint(screen)
  662. # paint mouse cursor
  663. cursor.paint(screen)
  664. # paint status panel
  665. paintStatus()
  666. pass
  667. # waits for event
  668. def waitForEvent():
  669. while 1:
  670. for e in pygame.event.get():
  671. if e.type == pygame.QUIT:
  672. pygame.quit()
  673. sys.exit()
  674. elif e.type == pygame.KEYDOWN:
  675. return
  676. pass
  677. pass
  678. pass
  679. # draw centered intro text
  680. def introText(textList):
  681. global font
  682. # clear screen
  683. screen.fill(black)
  684. height = font.charHeight + 3
  685. totalHeight = height * len(textList)
  686. cnt = 0
  687. y = (config['screenHeight'] - totalHeight + height * cnt) / 2
  688. for text in textList:
  689. w = font.charWidth * len(text)
  690. font.paint(screen, ((config['screenWidth'] - w) / 2, y), text.upper())
  691. cnt += 1
  692. y += height
  693. pass
  694. # update screen
  695. pygame.display.flip()
  696. waitForEvent()
  697. pass
  698. # intro
  699. def playIntro():
  700. # intro music
  701. if config['playMusic']:
  702. pygame.mixer.music.load("assets/mus_intro.ogg")
  703. pygame.mixer.music.play(-1)
  704. introText(("Satellite Dash v0.1",
  705. "",
  706. "Bump satellites into each other",
  707. "to gain points and time",
  708. "",
  709. "Press and hold LMB to grab satellites",
  710. "Press SPACE to pause game"
  711. "",
  712. "Have fun!"))
  713. # ingame music
  714. if config['playMusic']:
  715. pygame.mixer.music.load("assets/mus_ingame.ogg")
  716. pygame.mixer.music.play(-1)
  717. pass
  718. # outro
  719. def playOutro():
  720. # outro music
  721. if config['playMusic']:
  722. pygame.mixer.music.load("assets/mus_intro.ogg")
  723. pygame.mixer.music.play(-1)
  724. introText(("GAME OVER",
  725. "Score: " + str(game.points)))
  726. pygame.quit()
  727. sys.exit()
  728. pass
  729. # main function
  730. pygame.mixer.pre_init(44100, 16, 2, 2048)
  731. pygame.init()
  732. pygame.mouse.set_visible(False)
  733. size = (config['screenWidth'], config['screenHeight'])
  734. black = (0, 0, 0)
  735. if config['fullScreen']:
  736. screen = pygame.display.set_mode(size, FULLSCREEN)
  737. else:
  738. screen = pygame.display.set_mode(size)
  739. font = BitmapFont("assets/geebeeyay-8x8.png", 8, 8, \
  740. " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ")
  741. # load all needed assets
  742. loadAssets()
  743. # mouse cursor
  744. cursor = Cursor(assets['cursorNormal'], assets['cursorPressed'])
  745. # intro stuff
  746. playIntro()
  747. # start new game
  748. game = Game()
  749. clock = pygame.time.Clock()
  750. while 1:
  751. clock.tick(config['fpsLimit'])
  752. if config['debugFrameTime']:
  753. ticksDebug = pygame.time.get_ticks()
  754. # handle user input
  755. handleEvents()
  756. # clear screen
  757. screen.fill(black)
  758. # draw background
  759. screen.blit(assets['bg'], (0, 0))
  760. # update game state
  761. game.update()
  762. # game could finish in update()
  763. if game.isFinished:
  764. break
  765. # paint everything
  766. paintScreen()
  767. # update screen
  768. pygame.display.flip()
  769. if config['debugFrameTime']:
  770. print (pygame.time.get_ticks() - ticksDebug)
  771. # outro stuff - display scores etc
  772. playOutro()
  773. pass