I made a snake

Started by
2 comments, last by Nuorah 10 years, 9 months ago

Hello!

I had a (very) little experience of programming with python from my classes and i decided to start making game. I did a crappy attempt at pong that i will post later because it has a lot of problem, and then i did this very simplistic snake, which i ask you to criticize without mercy.

I went through the tutorial "Invent Your Own Computer Games With Python" and stop just before the part where he explains how to implement sound an images. I felt that i could already do many games and gain some experience with what i read.

I plan to add a menu and the possiblility to start again a game after losing, also a victory message (when you have filled the entire screen) and a score. Also the possibility to chose the difficulty.

I plan to first finish my pong and then work into adding theses into the snake.

If you could point how i could improve my code it would be great. I especially think i could have used more function and i ant to know you opinion about what could be functionized.

Thanks!


import pygame, sys, time, random
from pygame.locals import *

pygame.init()
mainClock = pygame.time.Clock()

WINDOWWIDTH = 480
WINDOWHEIGHT = 480
SPEED = 5

windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT), 0, 32)

pygame.display.set_caption('Running_window')

basicFont = pygame.font.SysFont(None, 48)
headPosition = [240 , 240]
foodPos = [20 + random.randint(0, 19)*22, 20 + random.randint(0, 19)*22]
head = pygame.Rect(headPosition[0] ,headPosition[1] ,20 ,20)
tail = [pygame.Rect(headPosition[0] ,headPosition[1] ,10 ,10)]
tailPosition = [240, 240]
food = pygame.Rect(foodPos[0] + 5, foodPos[1] + 5, 10, 10)
square = [pygame.Rect(16, 16, 444, 2), pygame.Rect(16, 16, 2, 444), pygame.Rect(460, 16, 2, 444),  pygame.Rect(16, 460, 446, 2)]

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
position2 = []

updates = 0
seconds = 0
foodEaten = 0

moveUp = False
moveDown = False
moveLeft = False
moveRight = False
foodIsHere = False

lose = False



while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
        if event.type == KEYDOWN:
            # events for changing the direction of the snake
            if moveRight: 
                if event.key == K_UP:
                    moveDown = False
                    moveUp = True
                    moveLeft = False
                    moveRight = False
                if event.key == K_DOWN:
                    moveUp = False
                    moveDown = True
                    moveLeft = False
                    moveRight = False
                if event.key == K_RIGHT:
                    moveUp = False
                    moveDown = False
                    moveLeft = False
                    moveRight = True
                if event.key == K_LEFT:
                    pygame.quit()
                    sys.exit()
            if moveLeft:
                if event.key == K_UP:
                    moveDown = False
                    moveUp = True
                    moveLeft = False
                    moveRight = False
                if event.key == K_DOWN:
                    moveUp = False
                    moveDown = True
                    moveLeft = False
                    moveRight = False
                if event.key == K_LEFT:
                    moveDown = False
                    moveUp = False
                    moveLeft = True
                    moveRight = False
                if event.key == K_RIGHT:
                    pygame.quit()
                    sys.exit()
            if moveDown:
                if event.key == K_DOWN:
                    moveUp = False
                    moveDown = True
                    moveLeft = False
                    moveRight = False
                if event.key == K_LEFT:
                    moveDown = False
                    moveUp = False
                    moveLeft = True
                    moveRight = False
                if event.key == K_RIGHT:
                    moveUp = False
                    moveDown = False
                    moveLeft = False
                    moveRight = True
                if event.key == K_UP:
                    pygame.quit()
                    sys.exit()
            if moveUp:
                if event.key == K_UP:
                    moveDown = False
                    moveUp = True
                    moveLeft = False
                    moveRight = False
                if event.key == K_LEFT:
                    moveDown = False
                    moveUp = False
                    moveLeft = True
                    moveRight = False
                if event.key == K_RIGHT:
                    moveUp = False
                    moveDown = False
                    moveLeft = False
                    moveRight = True
                if event.key == K_DOWN:
                    pygame.quit()
                    sys.quit()
            else:
                if event.key == K_UP:
                    moveDown = False
                    moveUp = True
                    moveLeft = False
                    moveRight = False
                if event.key == K_LEFT:
                    moveDown = False
                    moveUp = False
                    moveLeft = True
                    moveRight = False
                if event.key == K_RIGHT:
                    moveUp = False
                    moveDown = False
                    moveLeft = False
                    moveRight = True
                if event.key == K_DOWN:
                    moveUp = False
                    moveDown = True
                    moveLeft = False
                    moveRight = False
                
        if event.type == KEYUP:
            if event.key == K_ESCAPE:
                pygame.quit()
                sys.exit()

    #eating of food

    if head.colliderect(food):
        foodEaten += 1
        foodIsHere = False
        while foodPos in tailPosition:
            foodPos = [20 + random.randint(0, 19)*22, 20 + random.randint(0, 19)*22]
        tail.append(head)
        tailPosition.append(headPosition)

    #apparitions of food
    if foodIsHere == False:
        food = pygame.Rect(foodPos[0] + 5, foodPos[1] + 5, 10, 10)
        foodIsHere = True

    #movement of the tail of the snake

    if tail != []:
        tail.reverse()
        tailPosition.reverse()
        tail.pop(0)
        tailPosition.pop(0)
        tail.append(pygame.Rect(headPosition[0] + 5,headPosition[1] + 5 ,10 ,10))
        tailPosition.append(headPosition)
        tail.reverse()
        tailPosition.reverse()     
                
    # movements of the head of the snake

    if moveRight and (not moveLeft):
        headPosition[0] += 22
        head = pygame.Rect(headPosition[0] ,headPosition[1] ,20 ,20)
    elif moveLeft and (not moveRight):
        headPosition[0] -= 22
        head = pygame.Rect(headPosition[0] ,headPosition[1] ,20 ,20)
    elif moveUp and (not moveDown):
        headPosition[1] -= 22
        head = pygame.Rect(headPosition[0] ,headPosition[1] ,20 ,20)
    elif moveDown and (not moveUp):
        headPosition[1] += 22
        head = pygame.Rect(headPosition[0] ,headPosition[1] ,20 ,20)

    #collision ith the tail

    for piece in tail[1:]:
        if head.colliderect(piece):
            lose = True

    # collision with the border of the screen
    for bord in square :
        if head.colliderect(bord):
            lose = True

    if lose == True:
        while lose:
            windowSurface.fill(BLACK)
            lost1 = basicFont.render('You lose.', True, WHITE, None)
            textRectLost1 = lost1.get_rect()
            textRectLost1.centerx = 240
            textRectLost1.centery = 180
            lost2 = basicFont.render('Press q to quit.', True, WHITE, None)
            textRectLost2 = lost2.get_rect()
            textRectLost2.centerx = 240
            textRectLost2.centery = 250
            windowSurface.blit(lost2, textRectLost2)
            windowSurface.blit(lost1, textRectLost1)
            pygame.display.update()
            for event in pygame.event.get():
                if event.type == KEYUP:
                    if event.key == ord('q'):
                        pygame.quit()
                        sys.exit()

    windowSurface.fill(BLACK)

    pygame.draw.rect(windowSurface, RED, food)
    pygame.draw.rect(windowSurface, BLUE, head)
    for piece in tail:
        pygame.draw.rect(windowSurface, GREEN, piece)
        
    pygame.draw.rect(windowSurface, WHITE, square[0])
    pygame.draw.rect(windowSurface, WHITE, square[1])
    pygame.draw.rect(windowSurface, WHITE, square[2])
    pygame.draw.rect(windowSurface, WHITE, square[3])    
    
    


    updates += 1
    pygame.display.update()
    mainClock.tick(SPEED)
                

Advertisement

Maybe refactor it up a bit, with functions and objects.

1. You may want to consider changing the flags moveUp, moveDown etc, to either a vector for the direction (e.g. (1,0), as a tuple) or a number or something indicating the direction. Having four flags is redundant when the snake can only move one direction at once.

2. You could consider reducing the number of "lose" paths to just 1 - for example, remove the instances of sys.exit(), and just do that in your shutdown function.

3. Of course putting things into functions sounds like a good idea too.

4. The code for calculcating the tail positions, seems strange. I don't think you need to call reverse(). You should be able to do it using array slicing or other things. You could consider tailPosition = headPosition + tailPosition[:-1] (if this is the right way around... I can't easily see from your code "which way" your tailPosition array is supposed to be)

Thanks for the answers, I just finished working on my pong so i'm going to take a look again at the snake now.

This topic is closed to new replies.

Advertisement