Advertisement
Guest User

Untitled

a guest
Jun 24th, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 9.31 KB | None | 0 0
  1. import pygame, sys, random, time
  2. from pygame.locals import *
  3.  
  4. pygame.init()
  5.  
  6. snakeSize = 30 #determines the size of snake squares
  7. displayWidth = 500  #determines width of window in pixels
  8. displayHeight = 500 #determines height of window in pixels
  9. topPadding = snakeSize * 2 #how much space to leave at top for info, default 2*snakeSize
  10.  
  11. #set up window
  12. DISPLAYSURF = pygame.display.set_mode((displayWidth,displayHeight),0,32)
  13. pygame.display.set_caption('Snake by Isabella')
  14.  
  15. #set up colours to be used later
  16. black = (0,0,0)
  17. white = (230,230,230)
  18. red = (150,0,0)
  19. green = (0,100,0)
  20.  
  21. #set up fonts to be used later
  22. bigFont = pygame.font.Font('freesansbold.ttf', round(snakeSize))
  23. smallFont = pygame.font.Font('freesansbold.ttf', round(snakeSize/2))
  24.  
  25. class menuButton:
  26.     registry = []
  27.     def __init__(self,text,pos,size):
  28.         self.registry.append(self)
  29.         self.buttonText = smallFont.render(text, True, white)
  30.         self.buttonTextRect = self.buttonText.get_rect()
  31.         self.buttonTextRect.center = (pos)
  32.         DISPLAYSURF.blit(self.buttonText,self.buttonTextRect)
  33.         self.buttonRect = Rect(0,0,snakeSize*3,snakeSize)
  34.         self.buttonRect.center = pos
  35.         pygame.draw.rect(DISPLAYSURF,white,self.buttonRect, 2)
  36.         self.size = size
  37.  
  38. def startMenu():
  39.     #function to display screen that greets player at start of game
  40.     #buttons determine size of playing field
  41.     mouseClicked = False
  42.     mouseX = 0
  43.     mouseY = 0
  44.     size = 0
  45.    
  46.     #define buttons
  47.     tenByten = menuButton('10 x 10',(displayWidth/2,displayHeight/2),(10,10)) #(text,position, size of playing field)
  48.     fifteenByFifteen = menuButton('15 x 15',(displayWidth/2,displayHeight/(5/3)),(15,15))
  49.     twentyByTwenty = menuButton('20 x 20',(displayWidth/2,displayHeight/(10/7)),(20,20))
  50.     thirtyByThirty = menuButton('30 x 30',(displayWidth/2,displayHeight/(5/4)),(30,30))
  51.    
  52.     #show text
  53.     welcomeText = bigFont.render('WELCOME', True, green) #choose text and colour
  54.     welcomeRect = welcomeText.get_rect() #get Rect object containing text
  55.     welcomeRect.center = (displayWidth/2, displayHeight/3) #center rect on given coord
  56.     DISPLAYSURF.blit(welcomeText, welcomeRect) #blit to screen
  57.    
  58.     pleaseText = smallFont.render('Please pick the size of the playing field', True, white)
  59.     pleaseRect = pleaseText.get_rect()
  60.     pleaseRect.center = (displayWidth/2, displayHeight/2.5)
  61.     DISPLAYSURF.blit(pleaseText, pleaseRect)
  62.     #update screen
  63.     pygame.display.update()
  64.     while size == 0: #loop to check for user input, exits as soon as a size if found
  65.         for event in pygame.event.get(): #get events
  66.             if event.type == QUIT: #checks if a quit action has been undertaken
  67.                 pygame.quit() #quits pygame
  68.                 sys.exit() #quits the python program
  69.             elif event.type == MOUSEBUTTONUP: #check if mouse has been clicked
  70.                 mouseX, mouseY == event.pos #get coordinates of mouseclick
  71.                 for i in menuButton.registry: #loop through buttons
  72.                     if i.buttonRect.collidepoint(mouseX,mouseY): #if mourse coord contained in button
  73.                         size = i.size
  74.                         gameLoop(highScore,size)    #start main game loop
  75.  
  76.  
  77.  
  78. def thankYou():
  79.     #function to display thank you screen at end of play, disabled by default
  80.     DISPLAYSURF.fill(black)
  81.     thankYouText = bigFont.render('THANK YOU FOR PLAYING!', True, white)
  82.     thankYouRect = thankYouText.get_rect()
  83.     thankYouRect.center = (displayWidth/2, displayHeight/3)
  84.     DISPLAYSURF.blit(thankYouText, thankYouRect)
  85.     pygame.display.update()
  86.     time.sleep(5) #sleep for x seconds
  87.        
  88. def fruitPicker():
  89.         #function to find location of next fruit by picking random numbers in range width and height in boxes
  90.         widthInBoxes = displayWidth/snakeSize
  91.         heightInBoxes = (displayHeight-topPadding)/snakeSize #determines width and height in boxes for easy calculation
  92.         fruit = [0,0]
  93.         fruit[0]=random.randrange(0,widthInBoxes,1)*snakeSize+1 #picks random number and range and finds the coordinate of the corrosponding box
  94.         fruit[1]=random.randrange(2,heightInBoxes,1)*snakeSize+1
  95.         return fruit
  96.  
  97. def drawScreen(score,size):
  98.     global displayWidth, displayHeight #global because fuck you that's why
  99.     displayWidth = snakeSize*size[0]  #determines width of window in pixels
  100.     displayHeight = snakeSize*size[1]
  101.     DISPLAYSURF = pygame.display.set_mode((displayWidth,displayHeight),0,32)
  102.  
  103.     #function to draw the background the game takes place on
  104.     DISPLAYSURF.fill(black)
  105.     #draw horizontal lines
  106.     lineX = 0
  107.     while lineX < displayWidth:
  108.         lineX += snakeSize
  109.         pygame.draw.line(DISPLAYSURF, white, (lineX,topPadding),(lineX,displayHeight),1) #draw at x value lineX from top to bottom
  110.     #draw vertical lines
  111.     lineY = topPadding
  112.     while lineY < displayHeight:
  113.         pygame.draw.line(DISPLAYSURF, white, (0,lineY),(displayWidth,lineY),1) #draw at y value lineY from left edge to right edge
  114.         lineY += snakeSize
  115.     #The name of the game displayed in top
  116.     byline = smallFont.render('Snake by Isabella', True, green)
  117.     bylineRect = byline.get_rect()
  118.     bylineRect.topleft = (20,snakeSize/2)
  119.     DISPLAYSURF.blit(byline, bylineRect)
  120.    
  121.     #the current score displayed in top
  122.     scoreText = smallFont.render('Score: ' + str(score), True, white)
  123.     scoreRect = scoreText.get_rect()
  124.     scoreRect.topright = (displayWidth - 20, snakeSize/2)
  125.     DISPLAYSURF.blit(scoreText, scoreRect)
  126.    
  127. def gameOver(highScore,size):
  128.     #a function to handle the game over scenario
  129.     #starts by drawing the game over screen
  130.     pygame.draw.rect(DISPLAYSURF,black,(0,topPadding,displayWidth,displayHeight))
  131.     gameOverText = bigFont.render('GAME OVER!', True, green)
  132.     tryAgainText = smallFont.render('Try Again? y/n', True, white)
  133.     highScoreText = smallFont.render('High score: '+  str(highScore), True, white)
  134.    
  135.     gameOverRect = gameOverText.get_rect()
  136.     gameOverRect.center = (round(displayWidth/2), round(displayHeight/4))
  137.    
  138.     tryAgainRect = tryAgainText.get_rect()
  139.     tryAgainRect.center = (round(displayWidth/2), round(displayHeight/3))
  140.    
  141.     highScoreRect = highScoreText.get_rect()
  142.     highScoreRect.center = (round(displayWidth/2),round(displayHeight/2))
  143.    
  144.    
  145.     DISPLAYSURF.blit(gameOverText, gameOverRect)
  146.     DISPLAYSURF.blit(tryAgainText, tryAgainRect)
  147.     DISPLAYSURF.blit(highScoreText, highScoreRect)
  148.     pygame.display.update()
  149.     while True: #loop to check for user input
  150.         for event in pygame.event.get(): #get events
  151.             if event.type == QUIT or event.type == KEYUP and event.key == K_n: #checks if n key or a quit action has been undertaken
  152.                 pygame.quit() #quits pygame
  153.                 sys.exit() #quits the python program
  154.             elif event.type ==  KEYDOWN and event.key == K_y: # checks if y has been pressed    
  155.                 gameLoop(highScore,size) #start game over
  156.  
  157. def gameLoop(highScore,size):
  158.     #main game loop
  159.     snakeList = [] #list of coordinates for the snake segments
  160.     score = 0 #the current score
  161.     fps = 10 #framerate of game, increase to increase difficulty and smoothness.
  162.     fpsClock = pygame.time.Clock()
  163.     snakePosx = snakeSize + 1 #x-coordinate of the snake head
  164.     snakePosy = snakeSize*2 + 1 #y-coordinate of the snake head
  165.     snakeList = [(snakePosx,snakePosy)] #add starting position to segment list
  166.     direction = '' #keeps track of the direction of the snake head
  167.     fruit = (snakeSize*5+1,snakeSize*5+1) #stores position of fruit
  168.     fruitCheck = False #did the snake eat a fruit last loop?
  169.     pygame.draw.rect(DISPLAYSURF, green, (snakePosx,snakePosy, snakeSize-1, snakeSize-1))#draw starting position
  170.     while True:
  171.         #get events
  172.         for event in pygame.event.get():
  173.             if event.type == QUIT:
  174.                 #thankYou() #never enable this, I hate it.
  175.                 pygame.quit()
  176.                 sys.exit()
  177.             #check if user pressed an arrow key
  178.             elif event.type == KEYDOWN:
  179.                 previousDirection = direction #store direction
  180.                 if event.key == K_RIGHT:
  181.                     if len(snakeList) == 1 or previousDirection is not 'left': #check if direction is applicable
  182.                         direction = 'right' #match direction to arrow key
  183.                 elif event.key == K_LEFT:
  184.                     if len(snakeList) == 1 or previousDirection is not 'right':
  185.                         direction = 'left'
  186.                 elif event.key == K_DOWN:
  187.                     if len(snakeList) == 1 or previousDirection  is not 'up':
  188.                         direction = 'down'
  189.                 elif event.key == K_UP:
  190.                     if len(snakeList) == 1 or previousDirection is not 'down':
  191.                         direction = 'up'
  192.         #move snake in accordance with current direction
  193.         if direction == 'right':
  194.             snakePosx += snakeSize
  195.         elif direction == 'left':
  196.             snakePosx -= snakeSize
  197.         elif direction == 'down':
  198.             snakePosy += snakeSize
  199.         elif direction == 'up':
  200.             snakePosy -= snakeSize
  201.         snakeList.append((snakePosx,snakePosy))
  202.         if fruitCheck == False:
  203.             snakeList.pop(0)
  204.         else:
  205.             fruitCheck = False
  206.         #check oob or collision
  207.         if snakePosx < 0 or snakePosx > displayWidth or snakePosy < topPadding or snakePosy > displayHeight \
  208.         or (snakePosx,snakePosy) in snakeList[0:len(snakeList)-2]:
  209.             if score > highScore: #checks if the highscore has been beaten and corrects
  210.                 highScore = score
  211.             gameOver(highScore,size)
  212.         elif snakePosx == fruit[0] and snakePosy == fruit[1]:
  213.             fruitCheck = True
  214.             score += 1
  215.         #draw the background
  216.         drawScreen(score,size)
  217.         #check if we need to find new location for fruit and draw fruit
  218.         if fruitCheck == True:
  219.             fruit = fruitPicker()
  220.         pygame.draw.rect(DISPLAYSURF, red, (fruit[0],fruit[1], snakeSize-1, snakeSize-1))
  221.         #draw new snake
  222.         for snakePiece in snakeList:
  223.             pygame.draw.rect(DISPLAYSURF, green, (snakePiece[0],snakePiece[1], snakeSize-1, snakeSize-1))
  224.         pygame.display.update()
  225.         fpsClock.tick(fps)
  226. highScore = 0 #keeps track of the highscore
  227. startMenu()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement