AstroPi – Projecto CEF 2

 

A equipa CEF2 já submeteu o seu projecto à organização. O projecto consiste no conhecido jogo da cobra adaptado ao astroPi. O projecto inicial previa vários jogos mas apenas um foi totalmente concluído. Outros jogos foram desenvolvidos ( jogo da memória e jogo do galo) mas não estão totalmente operacionais.

 

O código do projecto submetido :

(os comentários estão em inglês por imposição da organização)

#!/usr/bin/python

## Snake
##
## This game is played with 2 buttons: LEFT and RIGHT
## 
## The goal is lead the snake to eat the green points. When a green poin is eated, the snake grows 
## game is over when the head of the snake touch is own body
##
## the results are saved in a file
## button a exits the game


from sense_hat import SenseHat
import os, time, random, pygame, sys
from pygame.locals import *

pygame.init()
pygame.display.set_mode((640, 480))

sense = SenseHat()
sense.clear()  # Blank the LED matrix
sense.set_rotation(270)  # Flight orientation

# 0, 0 = Top left
# 7, 7 = Bottom right

BLACK= [0, 0, 0]
WHITE= [255, 255, 255]
RED=   [255,0,0]
GREEN= [0,255,0]
BLUE=  [0,0,255]

UP    =  [0,-1]
DOWN  =  [0,1]
LEFT  =  [-1,0]
RIGHT =  [1,0]

running = True
score=0
speed=0.9
grow= False

# Calculate new coordenates of the snake
def calculateNewPosition(offset):
    global player
    global grow

    x=player[0][0]+offset[0]
    y=player[0][1]+offset[1]

    if x==8:        
        x=0
    elif x==-1:
        x=7
    elif y==8:
        y=0
    elif y==-1:
        y=7
    player.insert(0,[x,y])
    if grow==False:         
        player.pop()                    # Remove snake tail
    else:
        grow=False

# Show player and target on led Array
def showObjects():
    global astroPi
    global player
    global target
    sense.clear()
    for p in player:
        sense.set_pixel(p[0], p[1], WHITE)
    sense.set_pixel(target[0], target[1], GREEN)
    
        
# Manage button events
def handle_event(event, colour):
    global player
    global currentDirection

    if event.key == pygame.K_l:        # left button pressed
        if currentDirection==LEFT:
           currentDirection=DOWN
        elif currentDirection==RIGHT:
           currentDirection=UP
        elif currentDirection==UP:
           currentDirection=LEFT
        else:
           currentDirection=RIGHT
        showObjects()
    elif event.key == pygame.K_r:   # right button pressed
        if currentDirection==LEFT:
           currentDirection=UP
        elif currentDirection==RIGHT:
           currentDirection=DOWN
        elif currentDirection==UP:
           currentDirection=RIGHT
        else:
           currentDirection=LEFT
     elif event.key == K_a:
         sense.show_message("goodbye")
         if score>highScore:
             highScore= score
             fHigh=open(fileName,'w')
             fHigh.write(str(highScore))
             fHigh.close()
             sense.show_message("NEW HIGHSCORE",text_colour=BLUE)            
             sys.exit()
        showObjects()
       
# play game
player=[[4,4]]
target=[random.randint(0,7),random.randint(0,7)]
currentDirection= random.choice([UP,DOWN,LEFT,RIGHT])
highScore=0


fileName="snake_high.txt"
# read previous highscore if exists
exists=os.path.isfile(fileName)
if exists:
    with open(fileName,newline='') as fHigh:
        highScore =int(fHigh.read())
        fHigh.close()
else:
    fHigh=open(fileName,'w')
    fHigh.write('0')
    fHigh.close()

fscores= open("snake_scores.txt",'a')
while running:
    for event in pygame.event.get():
        if event.type == KEYDOWN:
            handle_event(event, WHITE)           
    calculateNewPosition(currentDirection)
    if player[0][0]==target[0] and player[0][1]==target[1]:      # If player eat target
        score += 1
        speed = 0.9*speed    
        target=[random.randint(0,7),random.randint(0,7)]
        while target in player:
            target=[random.randint(0,7),random.randint(0,7)]
        grow=True;   
        sense.clear()
    elif player[0] in player[1:]:           # If snake head touch body
        sense.show_message("game over", text_colour=RED)
        sense.show_message("score:"+str(score),text_colour=GREEN)
        fscores.write(str(score)+"\n")
        if score>highScore:
            highScore= score
            fHigh=open(fileName,'w')
            fHigh.write(str(highScore))
            fHigh.close()
            sense.show_message("NEW HIGHSCORE",text_colour=BLUE, scroll_speed=0.06)
        # restart game    
        time.sleep(1)
        sense.clear()
        player=[[4,4]]
        target=[random.randint(0,7),random.randint(0,7)]
        currentDirection= random.choice([UP,DOWN,LEFT,RIGHT])
        score=0
    showObjects()
    time.sleep(speed)    
sense.clear()
fscores.close()
       

March 3, 2017

Tags: ,

Leave a Reply

Your email address will not be published. Required fields are marked *