Chapter ? - Square Dodge

SquareDodge.py
  1. import pygame, time, random, sys
  2. from pygame.locals import *
  3. windowWidth = 600
  4. windowHeight = 600
  5. topScore = 0
  6. displayWindow = None
  7. mainSurface = None
  8. font = None
  9. def init():
  10.     global mainSurface, displayWindow, font
  11.     
  12.     displayWindow = pygame.display.set_mode((windowWidth, windowHeight))
  13.     
  14.     mainSurface = pygame.Surface(displayWindow.get_size())
  15.     pygame.display.set_caption('Square Dodge')
  16.     
  17.     pygame.font.init()
  18.     font = pygame.font.SysFont(None, 48)
  19. def showStartScreen():
  20.     global mainSurface, displayWindow, font
  21.     
  22.     mainSurface.fill((0,0,0))
  23.     text = font.render("Square Dodge", 1, (255,255,255) )
  24.     textpos = text.get_rect()
  25.     textpos.centerx = mainSurface.get_rect().centerx
  26.     mainSurface.blit(text, textpos)
  27.     
  28.     displayWindow.blit(mainSurface, (0, 0))
  29.     pygame.display.flip()
  30.     
  31.     while True:
  32.         for event in pygame.event.get():
  33.             if event.type == QUIT:
  34.                 sys.exit()
  35.             if event.type == KEYDOWN:
  36.                 return
  37.     
  38.     
  39. def showGameOverScreen():
  40.     global mainSurface, displayWindow, font
  41.     
  42.     #mainSurface.fill((0,0,0))
  43.     text = font.render("GAME OVER", 1, (255,255,255) )
  44.     textpos = text.get_rect()
  45.     textpos.centerx = mainSurface.get_rect().centerx
  46.     textpos.centery = mainSurface.get_rect().centery
  47.     mainSurface.blit(text, textpos)
  48.     
  49.     text = font.render("(Press a key to play again.)", 1, (255,255,255) )
  50.     textpos = text.get_rect()
  51.     textpos.centerx = mainSurface.get_rect().centerx
  52.     textpos.centery = mainSurface.get_rect().centery + 50
  53.     mainSurface.blit(text, textpos)
  54.     
  55.     displayWindow.blit(mainSurface, (0, 0))
  56.     pygame.display.flip()
  57.     
  58.     while True:
  59.         for event in pygame.event.get():
  60.             if event.type == QUIT:
  61.                 sys.exit()
  62.             if event.type == KEYDOWN:
  63.                 mainSurface.fill((0,0,0))
  64.                 displayWindow.blit(mainSurface, (0, 0))
  65.                 pygame.display.flip()
  66.                 return
  67. def enterGameLoop():
  68.     global windowWidth, windowHeight, topScore
  69.     
  70.     blocks = []
  71.     
  72.     gameSpeed = 0.001
  73.     addNewBlockRate = 4
  74.     playerMoveRate = 8
  75.     
  76.     minBlockSpeed = 1
  77.     maxBlockSpeed = 8
  78.     
  79.     score = 0
  80.     
  81.     playerRect = pygame.Rect(windowWidth / 2, windowHeight - 30, 20, 20)
  82.     moveLeft = False
  83.     moveRight = False
  84.     moveUp = False
  85.     moveDown = False
  86.     shiftDown = False
  87.     
  88.     lastWorldUpdate = time.time()
  89.     blockAddCounter = 0
  90.     lastScoreAdd = time.time()
  91.     
  92.     while True:
  93.         # Update the score
  94.         if time.time() > lastScoreAdd + 0.1:
  95.             lastScoreAdd = time.time()
  96.             score += 1
  97.             
  98.         # Update the blocks and the user's position.
  99.         for event in pygame.event.get():
  100.             if event.type == QUIT:
  101.                 sys.exit()
  102.             if event.type == KEYDOWN:
  103.                 if event.key == 276: # 276 is the left key
  104.                     moveRight = False
  105.                     moveLeft = True
  106.                 if event.key == 275: # 275 is the right key
  107.                     moveLeft = False
  108.                     moveRight = True
  109.                 if event.key == 273: # 273 is the up key
  110.                     moveDown = False
  111.                     moveUp = True
  112.                 if event.key == 274: # 274 is the down key
  113.                     moveUp = False
  114.                     moveDown = True
  115.                 if event.key in [303,304]:
  116.                     shiftDown = True
  117.             if event.type == KEYUP:
  118.                 if event.key == 276: # 276 is the left key
  119.                     moveLeft = False
  120.                 if event.key == 275: # 275 is the right key
  121.                     moveRight = False
  122.                 if event.key == 273: # 273 is the up key
  123.                     moveUp = False
  124.                 if event.key == 274: # 274 is the down key
  125.                     moveDown = False
  126.                 if event.key == 27: # 27 is the Escape key
  127.                     sys.exit()
  128.                 if event.key in [303,304]:
  129.                     shiftDown = False
  130.             
  131.         # Update the game world, if needed.
  132.         if time.time() > lastWorldUpdate + gameSpeed:
  133.             lastWorldUpdate = time.time()
  134.             
  135.             # Add new blocks at the top of the screen, if needed.
  136.             blockAddCounter += 1
  137.             if blockAddCounter > addNewBlockRate:
  138.                 blockAddCounter = 0
  139.                 blockSize = random.randint(10, 30)
  140.                 newBlock = {'rect': pygame.Rect(random.randint(0, windowWidth-blockSize), -1 * blockSize, blockSize, blockSize),
  141.                             'speed': random.randint(minBlockSpeed, maxBlockSpeed),
  142.                             'size': blockSize,
  143.                             'color': (random.randint(100,255),0,0),
  144.                             }
  145.                 blocks.append(newBlock)
  146.             
  147.             # Move the player around.
  148.             if moveLeft and playerRect.left > 0:
  149.                 playerRect.move_ip(-playerMoveRate, 0)
  150.             if moveRight and playerRect.right < windowWidth:
  151.                 playerRect.move_ip(playerMoveRate, 0)
  152.             if moveUp and playerRect.top > 0:
  153.                 playerRect.move_ip(0, -playerMoveRate)
  154.             if moveDown and playerRect.bottom < windowHeight:
  155.                 playerRect.move_ip(0, playerMoveRate)
  156.             
  157.             # Move the blocks down.
  158.             for b in blocks:
  159.                 b['rect'].move_ip(0, b['speed'])
  160.             
  161.              # Delete blocks that have fallen past the bottom.
  162.             delBlocks = []
  163.             for i in range(len(blocks)):
  164.                 if blocks[i]['rect'].top > windowHeight:
  165.                     delBlocks.append(i)
  166.             delBlocks.reverse()
  167.             for i in delBlocks:
  168.                 del blocks[i]
  169.             
  170.             # Draw the game world on the window.
  171.             mainSurface.fill((0,0,0)) # black out everything
  172.             
  173.             # Draw the score.
  174.             text = font.render('Score: %s' % (score), 1, (255,255,255) )
  175.             textpos = text.get_rect()
  176.             textpos.left = mainSurface.get_rect().left
  177.             textpos.top = mainSurface.get_rect().top
  178.             mainSurface.blit(text, textpos)
  179.             
  180.             text = font.render('Top Score: %s' % (topScore), 1, (255,255,255) )
  181.             textpos = text.get_rect()
  182.             textpos.left = mainSurface.get_rect().left
  183.             textpos.top = mainSurface.get_rect().top + 50
  184.             mainSurface.blit(text, textpos)
  185.             
  186.             # Draw the player's rectangle    
  187.             mainSurface.fill((255,255,255), playerRect)
  188.             
  189.             # Draw each block
  190.             for b in blocks:
  191.                 mainSurface.fill(b['color'], b['rect'])
  192.                         
  193.             # Draw the surface to the window
  194.             displayWindow.blit(mainSurface, (0, 0))
  195.             pygame.display.flip()
  196.             
  197.             # Check if any of the blocks have hit the player.
  198.             for b in blocks:
  199.                 if doRectsOverlap(playerRect, b['rect']):
  200.                     if score > topScore:
  201.                         topScore = score
  202.                     score = 0
  203.                     
  204.                     blocks = [] # delete all the blocks
  205.                     
  206.                     # reset the player's location
  207.                     playerRect = pygame.Rect(windowWidth / 2, windowHeight - 30, 20, 20)
  208.                     moveLeft = False
  209.                     moveRight = False
  210.                     moveUp = False
  211.                     moveDown = False
  212.                     return
  213.                     
  214. def doRectsOverlap(rect1, rect2):
  215.     # Check if rect1's corners are inside rect
  216.     if ((isPointInsideRect(rect1.left, rect1.top, rect2)) or
  217.         (isPointInsideRect(rect1.left, rect1.bottom, rect2)) or
  218.         (isPointInsideRect(rect1.right, rect1.top, rect2)) or
  219.         (isPointInsideRect(rect1.right, rect1.bottom, rect2))):
  220.         return True
  221.     
  222.     # Check if rect2's corners are inside rect1
  223.     if ((isPointInsideRect(rect2.left, rect2.top, rect1)) or
  224.         (isPointInsideRect(rect2.left, rect2.bottom, rect1)) or
  225.         (isPointInsideRect(rect2.right, rect2.top, rect1)) or
  226.         (isPointInsideRect(rect2.right, rect2.bottom, rect1))):
  227.         return True
  228.     
  229.     return False
  230. def isPointInsideRect(x, y, rect):
  231.     if (x > rect.left) and (x < rect.right) and (y > rect.top) and (y < rect.bottom):
  232.         return True
  233.     else:
  234.         return False
  235.         
  236. def main():
  237.     global mainSurface, displayWindow, font
  238.     
  239.     init()
  240.     showStartScreen()
  241.     
  242.     while True:
  243.         enterGameLoop()
  244.         showGameOverScreen()
  245. if __name__ == '__main__': main()

Things Covered In This Chapter: