Chapter ? - Square Dodge
- import pygame, time, random, sys
- from pygame.locals import *
- windowWidth = 600
- windowHeight = 600
- topScore = 0
- displayWindow = None
- mainSurface = None
- font = None
- def init():
- global mainSurface, displayWindow, font
-
- displayWindow = pygame.display.set_mode((windowWidth, windowHeight))
-
- mainSurface = pygame.Surface(displayWindow.get_size())
- pygame.display.set_caption('Square Dodge')
-
- pygame.font.init()
- font = pygame.font.SysFont(None, 48)
- def showStartScreen():
- global mainSurface, displayWindow, font
-
- mainSurface.fill((0,0,0))
- text = font.render("Square Dodge", 1, (255,255,255) )
- textpos = text.get_rect()
- textpos.centerx = mainSurface.get_rect().centerx
- mainSurface.blit(text, textpos)
-
- displayWindow.blit(mainSurface, (0, 0))
- pygame.display.flip()
-
- while True:
- for event in pygame.event.get():
- if event.type == QUIT:
- sys.exit()
- if event.type == KEYDOWN:
- return
-
-
- def showGameOverScreen():
- global mainSurface, displayWindow, font
-
- #mainSurface.fill((0,0,0))
- text = font.render("GAME OVER", 1, (255,255,255) )
- textpos = text.get_rect()
- textpos.centerx = mainSurface.get_rect().centerx
- textpos.centery = mainSurface.get_rect().centery
- mainSurface.blit(text, textpos)
-
- text = font.render("(Press a key to play again.)", 1, (255,255,255) )
- textpos = text.get_rect()
- textpos.centerx = mainSurface.get_rect().centerx
- textpos.centery = mainSurface.get_rect().centery + 50
- mainSurface.blit(text, textpos)
-
- displayWindow.blit(mainSurface, (0, 0))
- pygame.display.flip()
-
- while True:
- for event in pygame.event.get():
- if event.type == QUIT:
- sys.exit()
- if event.type == KEYDOWN:
- mainSurface.fill((0,0,0))
- displayWindow.blit(mainSurface, (0, 0))
- pygame.display.flip()
- return
- def enterGameLoop():
- global windowWidth, windowHeight, topScore
-
- blocks = []
-
- gameSpeed = 0.001
- addNewBlockRate = 4
- playerMoveRate = 8
-
- minBlockSpeed = 1
- maxBlockSpeed = 8
-
- score = 0
-
- playerRect = pygame.Rect(windowWidth / 2, windowHeight - 30, 20, 20)
- moveLeft = False
- moveRight = False
- moveUp = False
- moveDown = False
- shiftDown = False
-
- lastWorldUpdate = time.time()
- blockAddCounter = 0
- lastScoreAdd = time.time()
-
- while True:
- # Update the score
- if time.time() > lastScoreAdd + 0.1:
- lastScoreAdd = time.time()
- score += 1
-
- # Update the blocks and the user's position.
- for event in pygame.event.get():
- if event.type == QUIT:
- sys.exit()
- if event.type == KEYDOWN:
- if event.key == 276: # 276 is the left key
- moveRight = False
- moveLeft = True
- if event.key == 275: # 275 is the right key
- moveLeft = False
- moveRight = True
- if event.key == 273: # 273 is the up key
- moveDown = False
- moveUp = True
- if event.key == 274: # 274 is the down key
- moveUp = False
- moveDown = True
- if event.key in [303,304]:
- shiftDown = True
- if event.type == KEYUP:
- if event.key == 276: # 276 is the left key
- moveLeft = False
- if event.key == 275: # 275 is the right key
- moveRight = False
- if event.key == 273: # 273 is the up key
- moveUp = False
- if event.key == 274: # 274 is the down key
- moveDown = False
- if event.key == 27: # 27 is the Escape key
- sys.exit()
- if event.key in [303,304]:
- shiftDown = False
-
- # Update the game world, if needed.
- if time.time() > lastWorldUpdate + gameSpeed:
- lastWorldUpdate = time.time()
-
- # Add new blocks at the top of the screen, if needed.
- blockAddCounter += 1
- if blockAddCounter > addNewBlockRate:
- blockAddCounter = 0
- blockSize = random.randint(10, 30)
- newBlock = {'rect': pygame.Rect(random.randint(0, windowWidth-blockSize), -1 * blockSize, blockSize, blockSize),
- 'speed': random.randint(minBlockSpeed, maxBlockSpeed),
- 'size': blockSize,
- 'color': (random.randint(100,255),0,0),
- }
- blocks.append(newBlock)
-
- # Move the player around.
- if moveLeft and playerRect.left > 0:
- playerRect.move_ip(-playerMoveRate, 0)
- if moveRight and playerRect.right < windowWidth:
- playerRect.move_ip(playerMoveRate, 0)
- if moveUp and playerRect.top > 0:
- playerRect.move_ip(0, -playerMoveRate)
- if moveDown and playerRect.bottom < windowHeight:
- playerRect.move_ip(0, playerMoveRate)
-
- # Move the blocks down.
- for b in blocks:
- b['rect'].move_ip(0, b['speed'])
-
- # Delete blocks that have fallen past the bottom.
- delBlocks = []
- for i in range(len(blocks)):
- if blocks[i]['rect'].top > windowHeight:
- delBlocks.append(i)
- delBlocks.reverse()
- for i in delBlocks:
- del blocks[i]
-
- # Draw the game world on the window.
- mainSurface.fill((0,0,0)) # black out everything
-
- # Draw the score.
- text = font.render('Score: %s' % (score), 1, (255,255,255) )
- textpos = text.get_rect()
- textpos.left = mainSurface.get_rect().left
- textpos.top = mainSurface.get_rect().top
- mainSurface.blit(text, textpos)
-
- text = font.render('Top Score: %s' % (topScore), 1, (255,255,255) )
- textpos = text.get_rect()
- textpos.left = mainSurface.get_rect().left
- textpos.top = mainSurface.get_rect().top + 50
- mainSurface.blit(text, textpos)
-
- # Draw the player's rectangle
- mainSurface.fill((255,255,255), playerRect)
-
- # Draw each block
- for b in blocks:
- mainSurface.fill(b['color'], b['rect'])
-
- # Draw the surface to the window
- displayWindow.blit(mainSurface, (0, 0))
- pygame.display.flip()
-
- # Check if any of the blocks have hit the player.
- for b in blocks:
- if doRectsOverlap(playerRect, b['rect']):
- if score > topScore:
- topScore = score
- score = 0
-
- blocks = [] # delete all the blocks
-
- # reset the player's location
- playerRect = pygame.Rect(windowWidth / 2, windowHeight - 30, 20, 20)
- moveLeft = False
- moveRight = False
- moveUp = False
- moveDown = False
- return
-
- def doRectsOverlap(rect1, rect2):
- # Check if rect1's corners are inside rect
- if ((isPointInsideRect(rect1.left, rect1.top, rect2)) or
- (isPointInsideRect(rect1.left, rect1.bottom, rect2)) or
- (isPointInsideRect(rect1.right, rect1.top, rect2)) or
- (isPointInsideRect(rect1.right, rect1.bottom, rect2))):
- return True
-
- # Check if rect2's corners are inside rect1
- if ((isPointInsideRect(rect2.left, rect2.top, rect1)) or
- (isPointInsideRect(rect2.left, rect2.bottom, rect1)) or
- (isPointInsideRect(rect2.right, rect2.top, rect1)) or
- (isPointInsideRect(rect2.right, rect2.bottom, rect1))):
- return True
-
- return False
- def isPointInsideRect(x, y, rect):
- if (x > rect.left) and (x < rect.right) and (y > rect.top) and (y < rect.bottom):
- return True
- else:
- return False
-
- def main():
- global mainSurface, displayWindow, font
-
- init()
- showStartScreen()
-
- while True:
- enterGameLoop()
- showGameOverScreen()
- if __name__ == '__main__': main()
Things Covered In This Chapter: