Pastebin launched a little side project called VERYVIRAL.com, check it out ;-) Want more features on Pastebin? Sign Up, it's FREE!
Guest

Pygame

By: a guest on May 5th, 2012  |  syntax: Python  |  size: 10.32 KB  |  views: 62  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. """ turretFire.py
  2.    Use vector projection
  3.    to add a shell to the turret"""
  4.    
  5. import pygame, math
  6. from Tkinter import *
  7. pygame.init()
  8. pygame.mixer.init()
  9.  
  10. screen = pygame.display.set_mode((800,480))
  11. pygame.display.set_caption ("Orbit Rider")
  12. background = pygame.Surface(screen.get_size())
  13.  
  14.    
  15. class Label(pygame.sprite.Sprite):
  16.     """ Label Class (simplest version)
  17.        Properties:
  18.            font: any pygame font object
  19.            text: text to display
  20.            center: desired position of label center (x, y)
  21.    """
  22.     def __init__(self):
  23.         pygame.sprite.Sprite.__init__(self)
  24.         self.font = pygame.font.SysFont("None", 30)
  25.         self.text = ""
  26.         self.center = (320, 240)
  27.                
  28.     def update(self):
  29.         self.image = self.font.render(self.text, 1, (255, 255, 0))
  30.         self.rect = self.image.get_rect()
  31.         self.rect.center = self.center
  32.  
  33. class Turret(pygame.sprite.Sprite):
  34.     def __init__(self, shell):
  35.         self.shell = shell
  36.         pygame.sprite.Sprite.__init__(self)
  37.         self.image = pygame.image.load("turret.gif")
  38.         self.image = self.image.convert()
  39.         self.rect = self.image.get_rect()
  40.         self.rect.center = (10, 480)
  41.         self.TURNRATE = 10
  42.         self.dir = 45
  43.         self.charge = 5
  44.        
  45.     def update(self):
  46.         self.checkKeys()
  47.         self.rotate()
  48.    
  49.     def checkKeys(self):
  50.         keys = pygame.key.get_pressed()
  51.         if keys[pygame.K_LEFT]:
  52.             self.dir += self.TURNRATE
  53.             if self.dir > 360:
  54.                 self.dir = self.TURNRATE
  55.         if keys[pygame.K_RIGHT]:
  56.             self.dir -= self.TURNRATE
  57.             if self.dir < 0:
  58.                 self.dir = 360 - self.TURNRATE
  59.         if keys[pygame.K_UP]:
  60.             self.charge += 1
  61.             if self.charge > 20:
  62.                 self.charge = 20
  63.         if keys[pygame.K_DOWN]:
  64.             self.charge -= 1
  65.             if self.charge < 0:
  66.                 self.charge = 0
  67.            
  68.         if keys[pygame.K_SPACE]:
  69.             self.shell.x = self.rect.centerx
  70.             self.shell.y = self.rect.centery
  71.             self.shell.speed = self.charge
  72.             self.shell.dir = self.dir
  73.             self.shell.calcVector()
  74.    
  75.     def rotate(self):
  76.         oldCenter = self.rect.center
  77.         self.image = pygame.transform.rotate(self.image, self.dir)
  78.         self.rect = self.image.get_rect()
  79.         self.rect.center = oldCenter
  80.  
  81. class Shell(pygame.sprite.Sprite):
  82.     def __init__(self, screen, background):
  83.         pygame.sprite.Sprite.__init__(self)
  84.         self.screen = screen
  85.         self.background = background
  86.         self.boom = pygame.mixer.Sound("thunder.ogg")
  87.         self.image = pygame.Surface((10, 10))
  88.         self.image.fill((255, 255, 255))
  89.         self.image.set_colorkey((255, 255, 255))
  90.         pygame.draw.circle(self.image, (255, 255, 255), (5, 5), 5)
  91.         self.image = pygame.transform.scale(self.image, (5, 5))
  92.         self.rect = self.image.get_rect()
  93.         self.rect.center = (-100, -100)
  94.        
  95.         self.x = -100
  96.         self.y = -100
  97.         self.dx = 0
  98.         self.dy = 0
  99.         self.speed = 0
  100.         self.dir = 0
  101.         self.gravity = 0
  102.         self.mass = 1
  103.  
  104.        
  105.  
  106.  
  107.    
  108.     def update(self):
  109.         self.calcPos()
  110.         self.checkBounds()
  111.         self.rect.center = (self.x, self.y)
  112.    
  113.     def calcVector(self):
  114.         radians = self.dir * math.pi / 180
  115.        
  116.         self.dx = self.speed * math.cos(radians)
  117.         self.dy = self.speed * math.sin(radians)
  118.         self.dy *= -1
  119.        
  120.         #clear the background
  121.         self.background.fill((0,0,0))
  122.    
  123.     def calcPos(self):
  124.         #compensate for gravity
  125.         self.dy += self.gravity
  126.        
  127.         #get old position for drawing
  128.         oldx = self.x
  129.         oldy = self.y
  130.        
  131.         self.x += self.dx
  132.         self.y += self.dy
  133.    
  134.         pygame.draw.line(self.background, (255,255,255), (oldx, oldy), (self.x, self.y))
  135.    
  136.     def checkBounds(self):
  137.         screen = self.screen
  138.         if self.x > screen.get_width():
  139.             self.reset()
  140.         if self.x < 0:
  141.             self.reset()
  142.         if self.y > screen.get_height():
  143.             self.reset()
  144.         if self.y < 0:
  145.             self.reset()
  146.    
  147.     def reset(self):
  148.         """ move off stage and stop"""
  149.         self.x = -100
  150.         self.y = -100
  151.         self.speed = 0
  152.        
  153. class Planet(pygame.sprite.Sprite):
  154.     def __init__(self):
  155.         pygame.sprite.Sprite.__init__(self)
  156.         self.image = pygame.image.load("pluto.gif")
  157.         self.image = self.image.convert()
  158.         self.image = pygame.transform.scale(self.image, (30, 30))
  159.         self.rect = self.image.get_rect()
  160.         self.mass = 500
  161.         self.x = 320
  162.         self.y = 240
  163.         self.rect.center = (self.x, self.y)
  164.  
  165.     def gravitate(self, body):
  166.         """ calculates gravitational pull on
  167.            object """
  168.         (self.x, self.y) = self.rect.center
  169.        
  170.         #get dx, dy, distance
  171.         dx = self.x - body.x
  172.         dy = self.y - body.y
  173.        
  174.         distance = math.sqrt((dx * dx) + (dy * dy))
  175.         #normalize dx and dy
  176.         dx /= distance
  177.         dy /= distance
  178.        
  179.         force = (body.mass * self.mass)/(math.pow(distance, 2))
  180.        
  181.         dx *= force
  182.         dy *= force
  183.        
  184.         body.dx += dx
  185.         body.dy += dy
  186.     def reset(self):
  187.         """ move off stage and stop"""
  188.         self.x = -100
  189.         self.y = -100
  190.         self.speed = 0
  191.  
  192. class Asteroid(pygame.sprite.Sprite):
  193.     def __init__(self):
  194.         pygame.sprite.Sprite.__init__(self)
  195.         self.image = pygame.image.load("asteroid01.png")
  196.         self.image = self.image.convert()
  197.         self.image = pygame.transform.scale(self.image, (30, 30))
  198.         self.rect = self.image.get_rect()
  199.         self.mass = 500
  200.         self.x = 320
  201.         self.y = 240
  202.        
  203.         self.rect.center = (self.x, self.y)
  204.  
  205.     def reset(self):
  206.         """ move off stage and stop"""
  207.         self.x = -100
  208.         self.y = -100
  209.         self.speed = 0
  210.  
  211. class Statboard(pygame.sprite.Sprite):
  212.     def __init__(self):
  213.         pygame.sprite.Sprite.__init__(self)
  214.         self.lives = 4
  215.         self.score = 0
  216.         self.font = pygame.font.SysFont("None", 50)
  217.        
  218.     def update(self):
  219.         self.text = "Shells: %d, score: %d" % (self.lives, self.score)
  220.         self.image = self.font.render(self.text, 1, (255, 255, 0))
  221.         self.rect = self.image.get_rect()
  222.        
  223. def showInstructions(score):
  224.    
  225.     shell = Shell(screen, background)
  226.     turret = Turret(shell)
  227.    
  228.     allSprites = pygame.sprite.Group(shell,turret)
  229.    
  230.     insFont = pygame.font.SysFont(None, 50)
  231.     insLabels = []
  232.     instructions = (
  233.     "Orbit Rider.",
  234.     "Instructions:  You are a foreman for a ",
  235.     "space age demolition crew called Orbit Riders.",
  236.     "",
  237.     "shoot a shell with space bar at an asteroid ",
  238.     "in the orbit of planets.",
  239.     "but be careful not to miss,",
  240.     " we have limited ammo!",
  241.     "Control the turret with the left and right ",
  242.     " arrow keys and adjust speed with the",
  243.     " and adjust speed with the up and down arrow keys",
  244.     "Use the gravity of the planets to",
  245.     " bend the trajectory of the shell ",
  246.     "into the asteroids!",
  247.     "good luck!",
  248.     "click to start, escape to quit..."
  249.     )
  250.    
  251.     for line in instructions:
  252.         tempLabel = insFont.render(line, 1, (255, 255, 0))
  253.         insLabels.append(tempLabel)
  254.  
  255.     keepGoing = True
  256.     clock = pygame.time.Clock()
  257.     pygame.mouse.set_visible(False)
  258.     while keepGoing:
  259.         clock.tick(30)
  260.         for event in pygame.event.get():
  261.             if event.type == pygame.QUIT:
  262.                 keepGoing = False
  263.                 donePlaying = True
  264.             if event.type == pygame.MOUSEBUTTONDOWN:
  265.                 keepGoing = False
  266.                 donePlaying = False
  267.             elif event.type == pygame.KEYDOWN:
  268.                 if event.key == pygame.K_ESCAPE:
  269.                     keepGoing = False
  270.                     donePlaying = True
  271.        
  272.         allSprites.update()
  273.         allSprites.draw(screen)
  274.  
  275.         for i in range(len(insLabels)):
  276.             screen.blit(insLabels[i], (50, 30*i))
  277.  
  278.         pygame.display.flip()
  279.         pygame.mouse.set_visible(True)
  280.        
  281.     return donePlaying
  282.  
  283. def game():
  284.     background.fill((0,0,0))
  285.     screen.blit(background, (0, 0))
  286.  
  287.     shell = Shell(screen, background)
  288.     turret = Turret(shell)
  289.    
  290.    
  291.     planet = Planet()
  292.     planet.rect.center = (450,200)
  293.    
  294.    
  295.     asteroid = Asteroid()
  296.     asteroid.rect.center = (300,100)
  297.    
  298.  
  299.     statboard = Statboard()
  300.  
  301.  
  302.     friendSprites = pygame.sprite.Group(turret,shell)
  303.     targetSprites = pygame.sprite.Group(asteroid)
  304.    
  305.     allySprites = pygame.sprite.Group(planet)
  306.  
  307.     statSprites = pygame.sprite.Group(statboard)
  308.  
  309.     clock = pygame.time.Clock()
  310.     keepGoing = True
  311.     while keepGoing:
  312.         clock.tick(30)
  313.         pygame.mouse.set_visible(True)
  314.         for event in pygame.event.get():
  315.             if event.type == pygame.QUIT:
  316.                 keepGoing = False
  317.  
  318.         #check collisions
  319.         Goodcollision = pygame.sprite.spritecollide(shell, targetSprites,False)
  320.         Badcollision = pygame.sprite.spritecollide(shell, allySprites,False)
  321.         planet.gravitate(shell)
  322.        
  323.         if Goodcollision:
  324.             shell.boom.play()
  325.             shell.reset()
  326.             statboard.score += 1
  327.            
  328.         elif Badcollision:
  329.             shell.reset()
  330.             statboard.lives -=1
  331.            
  332.         if statboard.lives <= 0:
  333.             keepGoing = False
  334.         for theAsteroid in Goodcollision:
  335.             theAsteroid.reset()
  336.  
  337.         statSprites.update()
  338.         friendSprites.update()
  339.        
  340.         friendSprites.draw(screen)
  341.         targetSprites.draw(screen)
  342.         allySprites.draw(screen)
  343.         statSprites.draw(screen)
  344.        
  345.         pygame.display.flip()
  346.  
  347.     pygame.mouse.set_visible(True)
  348.     return statboard.score
  349.  
  350.  
  351. def main():
  352.     donePlaying = False
  353.     score = 0
  354.     while not donePlaying:
  355.         donePlaying = showInstructions(score)
  356.         if not donePlaying:
  357.             score = game()
  358.  
  359. if __name__ == "__main__":
  360.     main()