Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

Help for Points, High Score List & Game Restart needed for 'Snake' game

Posted on 2005-04-12
3
Medium Priority
?
512 Views
Last Modified: 2008-02-01
I'm trying to make the old 'Nibbles'/'Snake' game on the python IDLE programme and pygame. I've managed to make the snake move using the direction keys and also added the items the snake eats (rats) and made the snake crash when it hits walls and the sides of the screen. There is also the option to restart a game or exit when a crash happens and also to exit whilst in normal play with the esc key.

What I need to do is to add in some sectors which I'm having a lot of bother with trying to work out.

- Firstly I need to make a points system that will appear at the top of the screen and increase each time the snake eats a 'rat'.

- I then need a highscore list that can be maintained on the computer as a txt file stating name and score and the users name needs to be asked before play commences. I would like it to also state the level reached by the user.

- I need to add levels to the game and at each level I need to increase the speed of the snake and also make it so that the snake is longer. I have a base of the levels and the snake size increase at each level but cannot sort it out properly. If this could be made so that the snake increases in size with each point gained this would be even more helpful but size increase with levels would be sufficient.

- Next i need to be able to choose after a crash and the score being entered into the list whether to restart at the level where the user crashed or back at the original level. I have attempted at this in a different file but without having the levels implemented to start with I cannot make it work properly.

- Trying to implement rats which are worth more points which randomly spawn and only appear for a certain length of time before they disappear would also be a good addition but not really needed fully for the game.


I have included my last working code below and any help would be greatly appreciated.

--------------------------------------------------------------------------------------------------------------


import pygame
import random
WIDTH = 640
HEIGHT = 480
SIZE = (WIDTH, HEIGHT)
WHITE = 255, 255, 255  #RGB value for white
RED = 255, 0, 0
GREEN = 0,255,0
BLUE = 0,0, 255
DELAY = 1
STEP = 10
MAX_WAIT = 2000
count = 0 # NAUGHTY GLOBAL VARIABLE; USED TO GENERATE THE RANDOM TURNS OF THE SNAKE

#CRASH IMAGE
BANG = pygame.image.load("bang.gif")
#RAT CONSTANTS
RAT = pygame.image.load("rat.gif")
RAT_WIDTH = RAT.get_width()
RAT_HEIGHT = RAT.get_height()
#SNAKE CONSTANTS
LINE = 10
LEVEL = [5, 20, 30, 40, 50, 60, 70, 80, 90, 100]  # length of snake at different levels
SPEED = 50

#WALL CONSTANTS
THICKNESS = 10
WALL_1 = pygame.Rect(120,95, 400, 10)
WALL_2 = pygame.Rect(120, 395, 400, 10)
WALLS = [WALL_1, WALL_2]

direction = "r" # initial direction of movement

def generateRatPos():
    # this is basically the same code as that used to generate the starting position
    # for the snake
    # it is slightly more sophisticated so that we don't draw the rat inside the walls
    # or too close to screen borders    
    ratX = random.randint(5, WIDTH - RAT_WIDTH)
    ratY = random.randint(5 , HEIGHT - RAT_HEIGHT)    
    while ratInWalls([ratX, ratY]):
        ratX = random.randint(5, WIDTH - RAT_WIDTH)
        ratY = random.randint(5, HEIGHT - RAT_HEIGHT)
    return [ratX, ratY]

# both ratHit( ) and ratInWalls( ) use the same technique as that used to
# check when the snake hits the walls or screen border
def ratInWalls(coords):
    hit = False
    for wall in WALLS:
        if wall.colliderect([coords, [RAT_WIDTH, RAT_HEIGHT]]):
            hit = True
    return hit

def ratHit(coords, ratRects):
    hit = False
    for box in ratRects:
        if box.collidepoint(coords):
            hit = True
    return hit


def checkMove(coords,move):
    global direction, WIDTH, HEIGHT
    move = "go"
    f7 = False
    theEvent = pygame.event.poll()
    eventType = theEvent.type
    if eventType == pygame.QUIT :
        move = "q"
    elif eventType == pygame.KEYDOWN:
        if theEvent.key == pygame.K_DOWN:
            direction = "d"
        elif theEvent.key == pygame.K_UP:
            direction = "u"
        elif theEvent.key == pygame.K_LEFT:
            direction = "l"
        elif theEvent.key == pygame.K_RIGHT:
            direction = "r"
        elif theEvent.key == pygame.K_ESCAPE:
            move = "q"
        elif theEvent.key == pygame.K_F7:
            f7 = True
            move = "go"
    if move != "q" and not f7:
        move = moveTo(direction, coords)        
   
    return move


# == end checkMove( ) =====

def crashed(x, y, direction):
    # SYNTAX: Rect.collidepoint(x, y) -> bool;
    # collidepoint(x, y) returns True if x, y is inside the rectangle specified by Rect.
    crash = False
    if direction == "l":
        x = x - STEP
        if x < LINE/2:
            crash = True
    if direction == "r":
        x = x + STEP
        if x > SIZE[0] - LINE/2:
            crash = True
    if direction == "u":
        y = y - STEP
        if y < LINE/2:
            crash = True
    if direction == "d":
        y = y + STEP
        if y > SIZE[1] - LINE/2:
            crash = True
    for wall in WALLS:      # could use the same technique to detect if the snake crosses itself.
        if wall.collidepoint(x, y):
            crash = True
    return crash

def moveTo(direction, coords):
    crash = "ok"
    if crashed(coords[0], coords[1], direction):
        crash = "boom"
    elif direction =="d":
        coords[1] += STEP
    elif direction == "u":
        coords[1] -= STEP
    elif direction == "l":
        coords[0] -= STEP
    elif direction == "r":
        coords[0] += STEP
    return crash

def drawLine(screen, background, snake, oldX, oldY, usedRect):
    level = len(snake)
    # clear the end of the snake...
    rect = pygame.draw.line(screen, screen.get_at([oldX, oldY]),[oldX, oldY], snake[level -1], LINE)
    # rect represents the rectangle which was the last position of the snake's tail
    screen.blit(background, rect ,rect) # the covers up the tail with the corresponding rectangle from the background.
    for area in usedRect:
        screen.blit(BANG,area) # redraw the explosion in case the snake has crossed it.
    if level > 1:
        screen.fill(BLUE, pygame.draw.line(screen, BLUE, snake[0], snake[1], LINE)) # snake's head
    for i in range(1,level -1):
        screen.fill(GREEN, pygame.draw.line(screen, GREEN, snake[i], snake[i+1], LINE))
    pygame.display.flip()
     
   
def displayImage(screen, back, centre, usedRect, img):
    for rect in usedRect:
        screen.blit(back, rect, rect) # cover up the rect from the corresponding bit of the background
        usedRect.remove(rect)
    x = centre[0]
    y = centre[1]
    if x >= WIDTH - (2*STEP):
        x -= 20
    if y >= HEIGHT - (2*STEP):
        y -= 20        
    rect = screen.blit(img, [x,y]) # draw the IMAGE

    usedRect.append(rect)          # remember where the IMAGE WAS DRAWN.
    pygame.display.flip()
# == end displayImage( ) ====

def displayScore(screen, back, centre, score)


def update(list, newElement, limit):
    list.insert(0,newElement)
    if len(list) > limit:
        list.pop(limit)
       
def init(screen):
    screen.fill(WHITE)
    for wall in WALLS:
        screen.fill(RED, wall)

def main( ):
    global WIDTH, HEIGHT,SPEED,img, direction
# create background ==============
# background represents the background image for the game. The snake is drawn on top of this background.


                 
    pygame.init()
    screen = pygame.display.set_mode( SIZE)
    background = pygame.Surface(screen.get_size())
    init(background)
    background = background.convert()
    move = "go"
    while move != "q":
        if move == "go":
            screen.blit(background, (0,0))
            pygame.display.update()
           
        # start the game ==================  
           
            snake = []
            usedRect = [] # used to store the position of the last crash.
            x = random.randint(0, WIDTH)
            y = random.randint(0, HEIGHT)
            centre = [x,y]
            level = LEVEL[1]  # change speed and length of snake for harder levels
            update(snake, [x,y], level)
            move = checkMove(centre, move)
            # sneaky line; some understanding required.
            update(snake, [centre[0], centre[1]], 0)

            screen.blit(background, (0,0))
            pygame.display.update()

            ratCentre = generateRatPos()                                # this line
            usedRat = []                                                # this line
            displayImage(screen, background, ratCentre, usedRat, RAT)   #this line

            snake = []
            usedRect = [] # used to store the position of the last crash.            
            level = LEVEL[1]  # change speed and length of snake for harder levels

            # == start the game ===
            update(snake, [x,y], level)
            move = checkMove(centre, move)
            update(snake, [centre[0], centre[1]], 0) # sneaky line; some understanding required.

            while move != "boom" and move != "q":
                drawLine(screen, background, snake, x,y, usedRect)
                pygame.time.delay(SPEED) # wait a bit to slow the snake down
                pygame.event.pump() # sychronise the event queue
                length = len(snake)
                x = snake[length-1][0] # current position of the tail of the snake
                y = snake[length-1][1]
                move = checkMove(centre, move)
                update(snake, [centre[0], centre[1]], level)
                if ratHit(centre, usedRat):                                     # this line
                    ratCentre = generateRatPos( )                               # this line
                    displayImage(screen, background, ratCentre, usedRat, RAT)   # this line
                   

            while move != "q" and move!="boom":
                update(snake, [centre[0], centre[1]], 0) # <--- this was in the wrong place
                drawLine(screen, background, snake, x,y, usedRect)
                pygame.time.delay(SPEED) # wait a bit to slow the snake down
                pygame.event.pump() # sychronise the event queue
                length = len(snake)
                x = snake[length-1][0] # current position of the tail of the snake
                y = snake[length-1][1]
                move = checkMove(centre,move)
                update(snake, [centre[0], centre[1]], level)

            displayImage(screen, background, centre, usedRect, BANG)
            # vvv this should be in a function called gameOver or something with the parameter 'screen'
            font = pygame.font.Font(None, 28)
            text = font.render("Game Over - F7 to restart / Esc to quit.", 1, (255,0,0))
            textpos = text.get_rect()
            screen.blit(text, textpos)
            pygame.display.flip()
            # ^^^ this should be in a function called gameOver or something with the parameter 'screen'

        move = checkMove(centre,move)
    #endwhile
    pygame.display.quit()
   
#end main( )

# ======= call main( ) to start program ==========

main( )


0
Comment
Question by:seremaz
1 Comment
 
LVL 2

Accepted Solution

by:
Dariuzk earned 1000 total points
ID: 13771181
Hi seremaz,

this is function for dispalaying points on screen

def displayPoints(screen, points):
    #erase old points from screen
    font = pygame.font.Font(None, 28)
    text = font.render("Points: %s" % (points,), 1, (255,255,255))
    screen.fill((255,255,255), text.get_rect())

    newPoints = points + 1
   
    #display new points
    text = font.render("Points: %s" % (points,), 1, (255,0,0))
    textpos = text.get_rect()
    screen.blit(text, textpos)
    pygame.display.update(text.get_rect())
   
    return newPoints

I changet main() a bit:

----------------------------------------------
1.)
    while move != "q":
        if move == "go":
            screen.blit(background, (0,0))
            pygame.display.update()
           
        # start the game ==================  
           
            points = 0 <- insert this
----------------------------------------------
2.)
            while move != "boom" and move != "q":
                #display points
                displayPoints(screen, points) <- insert this
----------------------------------------------
3.)
                if ratHit(centre, usedRat):                                     # this line
                    ratCentre = generateRatPos( )                               # this line
                    displayImage(screen, background, ratCentre, usedRat, RAT)   # this line

                    points = displayPoints(screen, points) <- insert this
                   
               

0

Featured Post

[Webinar] Database Backup and Recovery

Does your company store data on premises, off site, in the cloud, or a combination of these? If you answered “yes”, you need a data backup recovery plan that fits each and every platform. Watch now as as Percona teaches us how to build agile data backup recovery plan.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

"The time has come," the Walrus said, "To talk of many things: Of sets--and lists--and dictionaries-- Of variable kinks-- And why you see it changing not-- And why so strange are strings." This part describes how variables and references (see …
When we want to run, execute or repeat a statement multiple times, a loop is necessary. This article covers the two types of loops in Python: the while loop and the for loop.
Learn the basics of if, else, and elif statements in Python 2.7. Use "if" statements to test a specified condition.: The structure of an if statement is as follows: (CODE) Use "else" statements to allow the execution of an alternative, if the …
Learn the basics of while and for loops in Python.  while loops are used for testing while, or until, a condition is met: The structure of a while loop is as follows:     while <condition>:         do something         repeate: The break statement m…
Suggested Courses
Course of the Month10 days, 5 hours left to enroll

569 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question