Advertisement
TwiNNeR

worm

Dec 23rd, 2018
337
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 12.54 KB | None | 0 0
  1. # Wormy (a Nibbles clone)
  2. # By Al Sweigart al@inventwithpython.com
  3. # http://inventwithpython.com/pygame
  4. # Released under a "Simplified BSD" license
  5.  
  6. import random
  7. import pygame
  8. import sys
  9. import time
  10. from pygame.locals import *
  11.  
  12. FPS = 15
  13. WINDOWWIDTH = 640
  14. WINDOWHEIGHT = 480
  15. CELLSIZE = 20
  16. assert WINDOWWIDTH % CELLSIZE == 0, "Window width must be a multiple of cell size."
  17. assert WINDOWHEIGHT % CELLSIZE == 0, "Window height must be a multiple of cell size."
  18. CELLWIDTH = int(WINDOWWIDTH / CELLSIZE)
  19. CELLHEIGHT = int(WINDOWHEIGHT / CELLSIZE)
  20. TIMEOUT = 5
  21. SECOND_WORM_TIMEOUT = 5  # should be 45
  22.  
  23. #             R    G    B
  24. WHITE = (255, 255, 255)
  25. BLACK = (0, 0, 0)
  26. RED = (255, 0, 0)
  27. GREEN = (0, 255, 0)
  28. DARKGREEN = (0, 155, 0)
  29. DARKGRAY = (40, 40, 40)
  30. BLUE = (0, 0, 255)
  31. DARKBLUE = (0, 0, 155)
  32. BGCOLOR = BLACK
  33.  
  34. RED_DARK = (196, 0, 0)
  35. RED_FLASH = (255, 75, 75)
  36.  
  37. UP = 'up'
  38. DOWN = 'down'
  39. LEFT = 'left'
  40. RIGHT = 'right'
  41.  
  42. HEAD = 0  # syntactic sugar: index of the worm's head
  43.  
  44.  
  45. def main():
  46.     global FPSCLOCK, DISPLAYSURF, BASICFONT, TIMEOUT
  47.  
  48.     pygame.init()
  49.     FPSCLOCK = pygame.time.Clock()
  50.     DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
  51.     BASICFONT = pygame.font.Font('freesansbold.ttf', 18)
  52.     pygame.display.set_caption('Wormy')
  53.  
  54.     showStartScreen()
  55.     while True:
  56.         runGame()
  57.         showGameOverScreen()
  58.  
  59.  
  60. def runGame():
  61.     # Set a random start point.
  62.     startx = random.randint(5, CELLWIDTH - 6)
  63.     starty = random.randint(5, CELLHEIGHT - 6)
  64.     wormCoords = [{'x': startx, 'y': starty},
  65.                   {'x': startx - 1, 'y': starty},
  66.                   {'x': startx - 2, 'y': starty}]
  67.     direction = RIGHT
  68.  
  69.     # Start the apple in a random place.
  70.     apple = getRandomLocation()
  71.  
  72.     score = 0
  73.  
  74.     timeFrame = time.time()
  75.     secondWormTimeFrom = time.time()
  76.     secondWormInitialised = False
  77.     wormCoordsSecond = []
  78.     secondWormTimeout = 1
  79.     flashyApples = []
  80.  
  81.     while True:  # main game loop
  82.         for event in pygame.event.get():  # event handling loop
  83.             if event.type == QUIT:
  84.                 terminate()
  85.             elif event.type == KEYDOWN:
  86.                 if (event.key == K_LEFT or event.key == K_a) and direction != RIGHT:
  87.                     direction = LEFT
  88.                 elif (event.key == K_RIGHT or event.key == K_d) and direction != LEFT:
  89.                     direction = RIGHT
  90.                 elif (event.key == K_UP or event.key == K_w) and direction != DOWN:
  91.                     direction = UP
  92.                 elif (event.key == K_DOWN or event.key == K_s) and direction != UP:
  93.                     direction = DOWN
  94.                 elif event.key == K_ESCAPE:
  95.                     terminate()
  96.                 if secondWormInitialised:
  97.                     directionSecond = getDirectionSecondWorm(oldDirection=directionSecond)
  98.  
  99.         if not secondWormInitialised and secondWormTimeFrom + SECOND_WORM_TIMEOUT <= time.time():
  100.             # set random start point for the second worm
  101.             startxSecond = random.randint(5, CELLWIDTH - 6)
  102.             startySecond = random.randint(5, CELLHEIGHT - 6)
  103.             wormCoordsSecond = [{'x': startxSecond, 'y': startySecond},
  104.                                 {'x': startxSecond - 1, 'y': startySecond},
  105.                                 {'x': startxSecond - 2, 'y': startySecond}]
  106.  
  107.             directionSecond = getDirectionSecondWorm()
  108.             secondWormInitialised = True
  109.  
  110.         # check if the worm has hit itself or the edge
  111.         if wormCoords[HEAD]['x'] == -1 or wormCoords[HEAD]['x'] == CELLWIDTH or wormCoords[HEAD]['y'] == -1 or \
  112.                 wormCoords[HEAD]['y'] == CELLHEIGHT:
  113.             return  # game over
  114.         for wormBody in wormCoords[1:]:
  115.             if wormBody['x'] == wormCoords[HEAD]['x'] and wormBody['y'] == wormCoords[HEAD]['y']:
  116.                 return  # game over
  117.  
  118.         # check if worm has eaten an apply
  119.         if wormCoords[HEAD]['x'] == apple['x'] and wormCoords[HEAD]['y'] == apple['y']:
  120.             score += 1
  121.             # don't remove worm's tail segment
  122.             apple = getRandomLocation()  # set a new apple somewhere
  123.         else:
  124.             del wormCoords[-1]  # remove worm's tail segment
  125.  
  126.         if checkFlashyApple(wormCoords, flashyApples):
  127.             score += 2
  128.  
  129.         # move the worm by adding a segment in the direction it is moving
  130.         newHead = {}
  131.         if direction == UP:
  132.             newHead = {'x': wormCoords[HEAD]['x'], 'y': wormCoords[HEAD]['y'] - 1}
  133.         elif direction == DOWN:
  134.             newHead = {'x': wormCoords[HEAD]['x'], 'y': wormCoords[HEAD]['y'] + 1}
  135.         elif direction == LEFT:
  136.             newHead = {'x': wormCoords[HEAD]['x'] - 1, 'y': wormCoords[HEAD]['y']}
  137.         elif direction == RIGHT:
  138.             newHead = {'x': wormCoords[HEAD]['x'] + 1, 'y': wormCoords[HEAD]['y']}
  139.         wormCoords.insert(0, newHead)
  140.  
  141.         if timeFrame + TIMEOUT <= time.time():
  142.             flashyApples = getFlashyApples()
  143.             timeFrame = time.time()
  144.  
  145.         if secondWormInitialised:
  146.             availableDirections = [LEFT, RIGHT, UP, DOWN]
  147.             changeDirection = False
  148.             if wormCoordsSecond[HEAD]['x'] <= 0:
  149.                 availableDirections.pop(availableDirections.index(LEFT))
  150.                 changeDirection = True
  151.             if wormCoordsSecond[HEAD]['x'] >= CELLWIDTH - 1:
  152.                 availableDirections.pop(availableDirections.index(RIGHT))
  153.                 changeDirection = True
  154.             if wormCoordsSecond[HEAD]['y'] <= 0:
  155.                 availableDirections.pop(availableDirections.index(UP))
  156.                 changeDirection = True
  157.             if wormCoordsSecond[HEAD]['y'] >= CELLHEIGHT - 1:
  158.                 availableDirections.pop(availableDirections.index(DOWN))
  159.                 changeDirection = True
  160.             if changeDirection:
  161.                 directionSecond = getDirectionSecondWorm(availableDirections)
  162.             runSecondWorm(wormCoordsSecond, directionSecond)
  163.  
  164.         drawGame(wormCoords, apple, flashyApples, score, wormCoordsSecond)
  165.  
  166.         FPSCLOCK.tick(FPS)
  167.  
  168.  
  169. def getDirectionSecondWorm(possibleDirections=[UP, RIGHT, DOWN, LEFT], oldDirection=''):
  170.     # if oldDirection == UP and DOWN in possibleDirections:
  171.     #     possibleDirections.pop(possibleDirections.index(DOWN))
  172.     #
  173.     # if oldDirection == DOWN and UP in possibleDirections:
  174.     #     possibleDirections.pop(possibleDirections.index(UP))
  175.     #
  176.     # if oldDirection == LEFT and RIGHT in possibleDirections:
  177.     #     possibleDirections.pop(possibleDirections.index(RIGHT))
  178.     #
  179.     # if oldDirection == RIGHT and LEFT in possibleDirections:
  180.     #     possibleDirections.pop(possibleDirections.index(LEFT))
  181.  
  182.     return possibleDirections[random.randrange(len(possibleDirections))]
  183.  
  184.  
  185. def runSecondWorm(wormCoords=[], direction=''):
  186.     newHead = {}
  187.     if direction == UP:
  188.         newHead = {'x': wormCoords[HEAD]['x'], 'y': wormCoords[HEAD]['y'] - 1}
  189.     elif direction == DOWN:
  190.         newHead = {'x': wormCoords[HEAD]['x'], 'y': wormCoords[HEAD]['y'] + 1}
  191.     elif direction == LEFT:
  192.         newHead = {'x': wormCoords[HEAD]['x'] - 1, 'y': wormCoords[HEAD]['y']}
  193.     elif direction == RIGHT:
  194.         newHead = {'x': wormCoords[HEAD]['x'] + 1, 'y': wormCoords[HEAD]['y']}
  195.     wormCoords.insert(0, newHead)
  196.     del wormCoords[-1]
  197.  
  198.  
  199. def drawGame(wormCoords, apple, flashyApples=[], score=0, wormCoordsSecond=[]):
  200.     DISPLAYSURF.fill(BGCOLOR)
  201.     drawGrid()
  202.     drawWorm(wormCoords)
  203.     drawSecondWorm(wormCoordsSecond)
  204.     drawApple(apple)
  205.     drawScore(score)
  206.     drawFlashyApples(flashyApples)
  207.     pygame.display.update()
  208.  
  209.  
  210. def drawPressKeyMsg():
  211.     pressKeySurf = BASICFONT.render('Press a key to play.', True, DARKGRAY)
  212.     pressKeyRect = pressKeySurf.get_rect()
  213.     pressKeyRect.topleft = (WINDOWWIDTH - 200, WINDOWHEIGHT - 30)
  214.     DISPLAYSURF.blit(pressKeySurf, pressKeyRect)
  215.  
  216.  
  217. def checkForKeyPress():
  218.     if len(pygame.event.get(QUIT)) > 0:
  219.         terminate()
  220.  
  221.     keyUpEvents = pygame.event.get(KEYUP)
  222.     if len(keyUpEvents) == 0:
  223.         return None
  224.     if keyUpEvents[0].key == K_ESCAPE:
  225.         terminate()
  226.     return keyUpEvents[0].key
  227.  
  228.  
  229. def showStartScreen():
  230.     titleFont = pygame.font.Font('freesansbold.ttf', 100)
  231.     titleSurf1 = titleFont.render('Wormy!', True, WHITE, DARKGREEN)
  232.     titleSurf2 = titleFont.render('Wormy!', True, GREEN)
  233.  
  234.     degrees1 = 0
  235.     degrees2 = 0
  236.     while True:
  237.         DISPLAYSURF.fill(BGCOLOR)
  238.         rotatedSurf1 = pygame.transform.rotate(titleSurf1, degrees1)
  239.         rotatedRect1 = rotatedSurf1.get_rect()
  240.         rotatedRect1.center = (WINDOWWIDTH / 2, WINDOWHEIGHT / 2)
  241.         DISPLAYSURF.blit(rotatedSurf1, rotatedRect1)
  242.  
  243.         rotatedSurf2 = pygame.transform.rotate(titleSurf2, degrees2)
  244.         rotatedRect2 = rotatedSurf2.get_rect()
  245.         rotatedRect2.center = (WINDOWWIDTH / 2, WINDOWHEIGHT / 2)
  246.         DISPLAYSURF.blit(rotatedSurf2, rotatedRect2)
  247.  
  248.         drawPressKeyMsg()
  249.  
  250.         if checkForKeyPress():
  251.             pygame.event.get()  # clear event queue
  252.             return
  253.         pygame.display.update()
  254.         FPSCLOCK.tick(FPS)
  255.         degrees1 += 3  # rotate by 3 degrees each frame
  256.         degrees2 += 7  # rotate by 7 degrees each frame
  257.  
  258.  
  259. def terminate():
  260.     pygame.quit()
  261.     sys.exit()
  262.  
  263.  
  264. def getRandomLocation():
  265.     return {'x': random.randint(0, CELLWIDTH - 1), 'y': random.randint(0, CELLHEIGHT - 1)}
  266.  
  267.  
  268. def getFlashyApples():
  269.     flashyApples = []
  270.     for i in range(3):
  271.         flashyApples.append({
  272.             'x': random.randint(0, CELLWIDTH - 1),
  273.             'y': random.randint(0, CELLHEIGHT - 1)
  274.         })
  275.     return flashyApples
  276.  
  277.  
  278. def checkFlashyApple(snake=[], apples=[]):
  279.     for apple in apples:
  280.         if snake[HEAD]['x'] == apple['x'] and snake[HEAD]['y'] == apple['y']:
  281.             apples.pop(apples.index(apple))
  282.             return True
  283.  
  284.  
  285. def showGameOverScreen():
  286.     gameOverFont = pygame.font.Font('freesansbold.ttf', 150)
  287.     gameSurf = gameOverFont.render('Game', True, WHITE)
  288.     overSurf = gameOverFont.render('Over', True, WHITE)
  289.     gameRect = gameSurf.get_rect()
  290.     overRect = overSurf.get_rect()
  291.     gameRect.midtop = (WINDOWWIDTH / 2, 10)
  292.     overRect.midtop = (WINDOWWIDTH / 2, gameRect.height + 10 + 25)
  293.  
  294.     DISPLAYSURF.blit(gameSurf, gameRect)
  295.     DISPLAYSURF.blit(overSurf, overRect)
  296.     drawPressKeyMsg()
  297.     pygame.display.update()
  298.     pygame.time.wait(500)
  299.     checkForKeyPress()  # clear out any key presses in the event queue
  300.  
  301.     while True:
  302.         if checkForKeyPress():
  303.             pygame.event.get()  # clear event queue
  304.             return
  305.  
  306.  
  307. def drawScore(score):
  308.     scoreSurf = BASICFONT.render('Score: %s' % (score), True, WHITE)
  309.     scoreRect = scoreSurf.get_rect()
  310.     scoreRect.topleft = (WINDOWWIDTH - 120, 10)
  311.     DISPLAYSURF.blit(scoreSurf, scoreRect)
  312.  
  313.  
  314. def drawWorm(wormCoords):
  315.     for coord in wormCoords:
  316.         x = coord['x'] * CELLSIZE
  317.         y = coord['y'] * CELLSIZE
  318.         wormSegmentRect = pygame.Rect(x, y, CELLSIZE, CELLSIZE)
  319.         pygame.draw.rect(DISPLAYSURF, DARKGREEN, wormSegmentRect)
  320.         wormInnerSegmentRect = pygame.Rect(x + 4, y + 4, CELLSIZE - 8, CELLSIZE - 8)
  321.         pygame.draw.rect(DISPLAYSURF, GREEN, wormInnerSegmentRect)
  322.  
  323.  
  324. def drawSecondWorm(wormCoords):
  325.     for coord in wormCoords:
  326.         x = coord['x'] * CELLSIZE
  327.         y = coord['y'] * CELLSIZE
  328.         wormSegmentRect = pygame.Rect(x, y, CELLSIZE, CELLSIZE)
  329.         pygame.draw.rect(DISPLAYSURF, DARKBLUE, wormSegmentRect)
  330.         wormInnerSegmentRect = pygame.Rect(x + 4, y + 4, CELLSIZE - 8, CELLSIZE - 8)
  331.         pygame.draw.rect(DISPLAYSURF, BLUE, wormInnerSegmentRect)
  332.  
  333.  
  334. def drawApple(coord):
  335.     x = coord['x'] * CELLSIZE
  336.     y = coord['y'] * CELLSIZE
  337.     appleRect = pygame.Rect(x, y, CELLSIZE, CELLSIZE)
  338.     pygame.draw.rect(DISPLAYSURF, RED, appleRect)
  339.  
  340.  
  341. def drawFlashyApples(coords):
  342.     for coord in coords:
  343.         x = coord['x'] * CELLSIZE
  344.         y = coord['y'] * CELLSIZE
  345.         flashyAppleRect = pygame.Rect(x, y, CELLSIZE, CELLSIZE)
  346.  
  347.         if int(time.time() * 10 % 10) % 2 == 0:
  348.             color = RED_DARK
  349.         else:
  350.             color = RED_FLASH
  351.  
  352.         pygame.draw.rect(DISPLAYSURF, color, flashyAppleRect)
  353.  
  354.  
  355. def drawGrid():
  356.     for x in range(0, WINDOWWIDTH, CELLSIZE):  # draw vertical lines
  357.         pygame.draw.line(DISPLAYSURF, DARKGRAY, (x, 0), (x, WINDOWHEIGHT))
  358.     for y in range(0, WINDOWHEIGHT, CELLSIZE):  # draw horizontal lines
  359.         pygame.draw.line(DISPLAYSURF, DARKGRAY, (0, y), (WINDOWWIDTH, y))
  360.  
  361.  
  362. if __name__ == '__main__':
  363.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement