Advertisement
Guest User

Untitled

a guest
Jan 18th, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 14.63 KB | None | 0 0
  1. import pygame
  2. import random
  3.  
  4. from pygame.locals import *
  5.  
  6. ### Initialize constants
  7.  
  8. WIDTH = 1000
  9. HEIGHT = 800
  10. BOOST_BAR_WIDTH = 150
  11. BOOST_BAR_HEIGHT = 20
  12. BOOST_BAR_COLOR = (0, 255, 0)
  13. BOOST_BAR_COLOR_DEPLETED = (200, 0, 0)
  14. BOOST_BAR_LINE_COLOR = (50, 50, 50)
  15. BACKGROUND_COLOR = (180, 200, 240)
  16. PAUSE_BACKGROUND_COLOR = (255, 255, 255)
  17. FRAMERATE = 60
  18. DEVILSPEED = 1.2
  19. MAX_POINTS = 10
  20. MAX_SPEED = 10
  21. BOOST_SPEED = 20
  22. MIN_BOOST = 20
  23. MAX_BOOST = 50
  24. BOMB_BLAST_RADIUS = 200
  25. BOMB_EXPLOSION_COLOR_1 = (255, 255, 255)
  26. BOMB_EXPLOSION_COLOR_2 = (200, 200, 200)
  27. MAIN_COLOR = (255, 0, 0)
  28. STAR_COLOR = (255, 255, 255)
  29.  
  30. pygame.init()
  31. pygame.mixer.init()
  32.  
  33. mainfont = pygame.font.SysFont('Helvetica', 25)
  34.  
  35. mainsurf = pygame.display.set_mode((WIDTH, HEIGHT))
  36.  
  37. rocketspeed = 1
  38.  
  39. boostmode = False
  40. boostleft = MAX_BOOST
  41.  
  42. devils = []
  43. bombs = []
  44.  
  45. score = 0
  46.  
  47. paused = False
  48. gamewon = False
  49. gamelost = False
  50.  
  51. devilgroup = pygame.sprite.Group()
  52.  
  53. winsound = pygame.mixer.Sound("sounds/winscreen.wav")
  54. losesound = pygame.mixer.Sound("sounds/sadtrombone.wav")
  55. levelupsound = pygame.mixer.Sound("sounds/omnomnom.ogg")
  56.  
  57.  
  58. class Rocket(pygame.sprite.Sprite):
  59.     def __init__(self):
  60.         super().__init__()
  61.  
  62.         self.image = pygame.image.load("images/rocket.png")
  63.         self.rect = pygame.rect.Rect((WIDTH / 2, HEIGHT / 2), self.image.get_size())
  64.  
  65.     def draw(self):
  66.         mainsurf.blit(self.image, self.rect)
  67.  
  68. class Devil(pygame.sprite.Sprite):
  69.     def __init__(self):
  70.         super().__init__()
  71.  
  72.         self.image = pygame.image.load("images/devil.png")
  73.  
  74.         side = random.randint(0, 3)
  75.         if side == 0:  # Top
  76.             x = random.randint(0, WIDTH)
  77.             y = 0
  78.         elif side == 1:  # Right
  79.             x = WIDTH
  80.             y = random.randint(0, HEIGHT)
  81.         elif side == 2:  # Bottom
  82.             x = random.randint(0, WIDTH)
  83.             y = HEIGHT
  84.         elif side == 3:  # Left
  85.             x = 0
  86.             y = random.randint(0, HEIGHT)
  87.  
  88.         self.rect = pygame.rect.Rect((x, y), self.image.get_size())
  89.  
  90.         devilgroup.add(self)
  91.  
  92.     def draw(self):
  93.         mainsurf.blit(self.image, self.rect)
  94.  
  95. class BossDevil(Devil):
  96.     def __init__(self):
  97.         super().__init__()
  98.  
  99.         self._normalimage = pygame.image.load("images/boss.png")
  100.         self._invertedimage = pygame.image.load("images/boss2.png")
  101.  
  102.         self._framecounter = 0
  103.         self._inverted = False
  104.  
  105.         self.image = pygame.image.load('images/boss.png')
  106.         self.rect = pygame.rect.Rect((WIDTH / 2, HEIGHT / 2), self.image.get_size())
  107.  
  108.         devilgroup.add(self)
  109.  
  110.     def draw(self):
  111.         self._framecounter += 1
  112.  
  113.         if self._framecounter == 5:
  114.             self._framecounter = 0
  115.             self._inverted = not self._inverted
  116.             if self._inverted:
  117.                 self.image = self._invertedimage
  118.             else:
  119.                 self.image = self._normalimage
  120.  
  121.         mainsurf.blit(self.image, self.rect)
  122.  
  123. class Cookie(pygame.sprite.Sprite):
  124.     def __init__(self):
  125.         super().__init__()
  126.  
  127.         self.image = pygame.image.load("images/cookie.png")
  128.         self.rect = pygame.rect.Rect((random.randint(15, WIDTH - 15), random.randint(15, HEIGHT - 15)), self.image.get_size())
  129.  
  130.     def draw(self):
  131.         mainsurf.blit(self.image, self.rect)
  132.  
  133. class Bomb(pygame.sprite.Sprite):
  134.     _frames = None
  135.     _blinker = None
  136.     _frames_since_detonated = None
  137.     radius = None
  138.     exploding = None
  139.     done = None
  140.  
  141.     def __init__(self, x, y):
  142.         super().__init__()
  143.  
  144.         self._frames = 0
  145.         self._blinker = False
  146.         self.radius = 0
  147.         self.exploding = False
  148.         self.done = False
  149.  
  150.         self.image = pygame.image.load("images/bomb.png")
  151.         self.rect = pygame.rect.Rect((x, y), self.image.get_size())
  152.  
  153.     def detonate(self):
  154.         self.exploding = True
  155.         self._frames_since_detonated = 0
  156.  
  157.     def draw(self):
  158.         self._frames += 1
  159.         if self.exploding:
  160.             self._frames_since_detonated += 1
  161.  
  162.         if self._frames == 100 and not self.exploding:  # At the 100 frame mark, we detonate
  163.             self.detonate()
  164.  
  165.         if not self.exploding:
  166.             # We haven't exploded yet, so draw the normal bomb
  167.             mainsurf.blit(self.image, self.rect)
  168.         elif self.radius <= BOMB_BLAST_RADIUS:  # Exploding
  169.             self._frames_since_detonated += 1
  170.             if self._frames_since_detonated % 3 == 0:  # Every third frame...
  171.                 self._blinker = not self._blinker
  172.  
  173.             self.radius = self._frames_since_detonated * 20
  174.  
  175.             color = BOMB_EXPLOSION_COLOR_1 if self._blinker else BOMB_EXPLOSION_COLOR_2
  176.  
  177.             # Set the radius based on the number of frames since 100 (so it grows every frame)
  178.             pygame.draw.circle(mainsurf, color, (self.rect.centerx, self.rect.centery), self.radius)
  179.         else:
  180.             # We are past the radius, so we do not draw, and we set this.done to True
  181.             # so the main game loop knows it can remove this from the list of bombs.
  182.             self.done = True
  183.  
  184.  
  185. class StarField(pygame.sprite.Sprite):
  186.     def __init__(self):
  187.         super().__init__()
  188.  
  189.         self.image = pygame.Surface((WIDTH, HEIGHT))
  190.         self.rect = pygame.rect.Rect((0, 0), self.image.get_size())
  191.  
  192.         y = 0
  193.         while y < HEIGHT:
  194.             x = 0
  195.             while x < WIDTH:
  196.                 if random.randint(0, 100) == 0:
  197.                     startype = random.choice(['white', 'red', 'blue'])
  198.                     if startype == 'white':
  199.                         color = (255, 255, 255)
  200.                     elif startype == 'red':
  201.                         color = (random.randint(150, 255), 50, 50)
  202.                     elif startype == 'blue':
  203.                         color = (50, 50, random.randint(150, 255))
  204.  
  205.                     self.image.set_at((x, y), color)
  206.                 x += 1
  207.             y += 1
  208.  
  209.     def draw(self):
  210.         mainsurf.blit(self.image, self.rect)
  211.  
  212. def winscreen():
  213.     mainsurf.fill(BACKGROUND_COLOR)
  214.  
  215.     textsurf = mainfont.render('YOU WON', True, MAIN_COLOR)
  216.  
  217.     mainsurf.blit(textsurf, (WIDTH / 2, HEIGHT / 2))
  218.  
  219. def losescreen():
  220.     mainsurf.fill(BACKGROUND_COLOR)
  221.  
  222.     textsurf = mainfont.render('YOU LOST', True, MAIN_COLOR)
  223.  
  224.     mainsurf.blit(textsurf, (WIDTH / 2, HEIGHT / 2))
  225.  
  226. def pausescreen():
  227.     mainsurf.fill(PAUSE_BACKGROUND_COLOR)
  228.  
  229.     textsurf = mainfont.render("PAUSED", True, MAIN_COLOR)
  230.  
  231.     mainsurf.blit(textsurf, (WIDTH / 2, HEIGHT / 2))
  232.  
  233. def showscore(score):
  234.     textsurf = mainfont.render(str(score), True, MAIN_COLOR)
  235.     mainsurf.blit(textsurf, (WIDTH - 50, 50))
  236.  
  237. def showboostbar(boostleft):
  238.     width = (boostleft / MAX_BOOST) * BOOST_BAR_WIDTH
  239.  
  240.     if boostleft < MIN_BOOST:
  241.         color = BOOST_BAR_COLOR_DEPLETED
  242.     else:
  243.         color = BOOST_BAR_COLOR
  244.  
  245.     # The x position of the bar is the width of the screen, minus the width of the bar
  246.     # (so it doesn't go off the screen), minus another 30px so it's not right up
  247.     # against the edge of the screen.
  248.     barx = WIDTH - BOOST_BAR_WIDTH - 30
  249.  
  250.     # y position is 20px (just a little bit of padding so it's not right at the top)
  251.     bary = 20
  252.  
  253.     # The width of the bar is the percentage of boost that we have left, times the width
  254.     # of the full bar. So if we're at 50% boost and the full bar is 150 pixels, then
  255.     # we display a bar 75 pixels wide.
  256.     barwidth = (boostleft / MAX_BOOST) * BOOST_BAR_WIDTH
  257.  
  258.     # The height is just a constant
  259.     barheight = BOOST_BAR_HEIGHT
  260.  
  261.     # Time to draw the bar!
  262.     pygame.draw.rect(mainsurf, color, (barx, bary, barwidth, barheight))
  263.  
  264.     # Now, let's make the line that marks the minimum boost level
  265.  
  266.     # To compute the x position for the minimum boost line, we take 3 steps:
  267.     #   - First, we divide the minimum boost over the maximum boost, to find out
  268.     #     how far along the bar we should draw the line (as a ratio). For example,
  269.     #     if MIN_BOOST is 20 and MAX_BOOST is 100, then the ratio would be 0.2.
  270.     #   - Next, we multiply this ratio by the width of the bar to get the actual
  271.     #     number of pixels.
  272.     #   - Finally, we add the x position of the bar to push the whole thing to the
  273.     #     right so it lines up with the bar.
  274.     linex = ((MIN_BOOST / MAX_BOOST) * BOOST_BAR_WIDTH) + barx
  275.  
  276.     # Line y position is the same as bar
  277.     liney = bary
  278.  
  279.     # Line is 2 pixels wide
  280.     linewidth = 2
  281.  
  282.     # Line is same height as bar
  283.     lineheight = barheight
  284.  
  285.     pygame.draw.rect(mainsurf, BOOST_BAR_LINE_COLOR, (linex, liney, linewidth, lineheight))
  286.  
  287. starfield = StarField()
  288.  
  289. rocket = Rocket()
  290. cookie = Cookie()
  291.  
  292. # Create first devil
  293. devils.append(Devil())
  294. while True:
  295.     event = pygame.event.poll()    
  296.  
  297.     if event.type == QUIT:
  298.         exit()
  299.  
  300.     if gamewon:
  301.         winscreen()
  302.         pygame.display.update()
  303.         continue
  304.  
  305.     if gamelost:
  306.         losescreen()
  307.         pygame.display.update()
  308.         continue
  309.  
  310.     if event.type == KEYUP and event.key == K_ESCAPE:  # If the player just pressed escape...
  311.         paused = not paused  # Flip paused state
  312.  
  313.     # If the game is paused, display the pause screen and skip everything else
  314.     if paused:
  315.         pausescreen()
  316.         pygame.display.update()
  317.         continue
  318.  
  319.     keyspressed = pygame.key.get_pressed()
  320.  
  321.     ### Update rocket speed
  322.  
  323.     # If the player pressed "b" and we have enough boost to start, then go into boost mode
  324.     if event.type == KEYDOWN and event.key == K_b and boostleft > MIN_BOOST:
  325.         boostmode = True
  326.         rocketspeed = 20
  327.  
  328.     if event.type == KEYUP and event.key == K_b:  # Boost mode over
  329.         boostmode = False
  330.         rocketspeed = 1
  331.  
  332.     if boostmode:
  333.         # We're in boost mode
  334.  
  335.         boostleft -= 1  # Deplete the boost counter
  336.         if boostleft <= 0:
  337.             boostmode = False
  338.             rocketspeed = 1
  339.     else:
  340.         # We're not in boost mode
  341.  
  342.         # Replenish boost counter
  343.         if boostleft <= MAX_BOOST:
  344.             boostleft += 0.25
  345.  
  346.         # If space is held down, increase rocket speed (but don't let the speed go over the max)
  347.         if keyspressed[K_SPACE]:
  348.             rocketspeed += .25
  349.             if rocketspeed > MAX_SPEED:
  350.                 rocketspeed = MAX_SPEED
  351.  
  352.         # If shift is held down, decrease rocket speed (but don't let the speed go under 0)
  353.         if keyspressed[K_LSHIFT] or keyspressed[K_RSHIFT]:
  354.             rocketspeed -= 1
  355.             if rocketspeed < 0:
  356.                 rocketspeed = .1
  357.  
  358.     ### Update rocket position using the speed we just calculated
  359.  
  360.     if keyspressed[K_UP]:
  361.         rocket.rect.y -= rocketspeed
  362.  
  363.     if keyspressed[K_DOWN]:
  364.         rocket.rect.y += rocketspeed
  365.  
  366.     if keyspressed[K_LEFT]:
  367.         rocket.rect.x -= rocketspeed
  368.  
  369.     if keyspressed[K_RIGHT]:
  370.         rocket.rect.x += rocketspeed
  371.  
  372.     # If the rocket is now past the edge in any direction, move it back to the edge.
  373.     if rocket.rect.x < 0:
  374.         rocket.rect.x = 0
  375.  
  376.     if rocket.rect.x > WIDTH - rocket.rect.width:
  377.         rocket.rect.x = WIDTH - rocket.rect.width
  378.  
  379.     if rocket.rect.y < 0:
  380.         rocket.rect.y = 0
  381.  
  382.     if rocket.rect.y > HEIGHT - rocket.rect.height:
  383.         rocket.rect.y = HEIGHT - rocket.rect.height
  384.  
  385.     ### Update devil position
  386.  
  387.     i = 0
  388.     while i < len(devils): # For each devil...
  389.         # Get the current x and y position for this devil
  390.         devil = devils[i]
  391.  
  392.         oldx = devil.rect.x
  393.         oldy = devil.rect.y
  394.  
  395.         # Calculate the *new* x and y position for this devil
  396.         if devil.rect.x > rocket.rect.x:
  397.             devil.rect.x -= DEVILSPEED
  398.    
  399.         if devil.rect.x < rocket.rect.x:
  400.             devil.rect.x += DEVILSPEED
  401.      
  402.         if devil.rect.y > rocket.rect.y:
  403.             devil.rect.y -= DEVILSPEED
  404.      
  405.         if devil.rect.y < rocket.rect.y:
  406.             devil.rect.y += DEVILSPEED
  407.  
  408.         devilgroup.remove(devil)
  409.         collidingdevil = pygame.sprite.spritecollideany(devil, devilgroup)
  410.         devilgroup.add(devil)
  411.  
  412.  
  413.         if collidingdevil is not None:
  414.             devil.rect.x = oldx
  415.             devil.rect.y = oldy
  416.  
  417.         i += 1
  418.  
  419.     if event.type == KEYDOWN and event.key == K_d:
  420.         for bomb in bombs:
  421.             bomb.detonate()
  422.  
  423.     ### We have the new positions for everything. Now, check for collisions and update the game in response
  424.  
  425.     # Check if the rocket is colliding with any of the devils. If so, we lost
  426.     i = 0
  427.     while i < len(devils):
  428.         devil = devils[i]
  429.  
  430.         if rocket.rect.colliderect(devil.rect):
  431.             gamelost = True
  432.             break
  433.         i += 1
  434.  
  435.     if gamelost:
  436.         losesound.play()
  437.         continue
  438.  
  439.     # Check for collisions with bombs.
  440.     for bomb in bombs:
  441.         if bomb.exploding and pygame.sprite.collide_circle(bomb, rocket):
  442.             # If the rocket is colliding with an exploding bomb, we lose
  443.             gamelost = True
  444.             continue
  445.  
  446.         for devil in list(devils):
  447.             # If a devil is colliding with an exploding bomb, it goes bye-bye
  448.             if bomb.exploding and pygame.sprite.collide_circle(bomb, devil):
  449.                 devils.remove(devil)
  450.                 devilgroup.remove(devil)
  451.  
  452.     if event.type == KEYDOWN and event.key == K_d:
  453.         for bomb in bombs:
  454.             bomb.detonate()
  455.  
  456.  
  457.     if gamelost:
  458.         losesound.play()
  459.         continue
  460.  
  461.     # Check if the rocket is colliding with the cookie
  462.     if rocket.rect.colliderect(cookie.rect):
  463.         score += 1
  464.  
  465.         if score > MAX_POINTS:  # We won
  466.             gamewon = True
  467.             winsound.play()
  468.             continue
  469.         else:
  470.             cookie = Cookie()
  471.             if score == MAX_POINTS:  # Final level
  472.                 devilgroup.empty()
  473.                 devils = [BossDevil()]
  474.             else:
  475.                 for i in range(score):
  476.                     devils.append(Devil())
  477.             levelupsound.play()
  478.  
  479.     if event.type == KEYUP and event.key == K_RETURN:  # Drop a bomb
  480.         bombs.append(Bomb(rocket.rect.x, rocket.rect.y))
  481.  
  482.     # Clear out bombs that have finished detonating
  483.     for bomb in list(bombs):
  484.         if bomb.done:
  485.             bombs.remove(bomb)
  486.  
  487.  
  488.     ### The game state has been updated. Time to render!
  489.  
  490.     starfield.draw()
  491.  
  492.     showscore(score)
  493.     showboostbar(boostleft)
  494.  
  495.     # Render rocket and cookie
  496.     rocket.draw()
  497.     cookie.draw()
  498.  
  499.     for bomb in bombs:
  500.         bomb.draw()
  501.  
  502.     # Render devils
  503.     i = 0
  504.     while i < len(devils):
  505.         devil = devils[i]
  506.         devil.draw()
  507.         i += 1
  508.  
  509.     pygame.display.update()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement