Programmazione

Il gioco della vita in Python

Se volete giocare con Python e il gioco della vita, questo è il codice che serve (è per Python3)

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

#Number of frames per second
FPS = 10

###Sets size of grid
WINDOWWIDTH = 640
WINDOWHEIGHT = 480
CELLSIZE = 10

#Check to see if the width and height are multiples of the cell size.
assert WINDOWWIDTH % CELLSIZE == 0, "Window width must be a multiple of cell size"
assert WINDOWHEIGHT % CELLSIZE == 0, "Window height must be a multiple of cell size"

#Determine number of cells in horizonatl and vertical plane
CELLWIDTH = WINDOWWIDTH // CELLSIZE # number of cells wide
CELLHEIGHT = WINDOWHEIGHT // CELLSIZE # Number of cells high

# set up the colours
BLACK =    (0,  0,  0)
WHITE =    (255,255,255)
DARKGRAY = (40, 40, 40)
GREEN =    (0,255,0)

#Draws the grid lines
def drawGrid():
    for x in range(0, WINDOWWIDTH, CELLSIZE): # draw vertical lines
        pygame.draw.line(DISPLAYSURF, DARKGRAY, (x,0),(x,WINDOWHEIGHT))
    for y in range (0, WINDOWHEIGHT, CELLSIZE): # draw horizontal lines
        pygame.draw.line(DISPLAYSURF, DARKGRAY, (0,y), (WINDOWWIDTH, y))

#Colours the cells green for life and white for no life
def colourGrid(item, lifeDict):
    x = item[0]
    y = item[1]
    y = y * CELLSIZE # translates array into grid size
    x = x * CELLSIZE # translates array into grid size
    if lifeDict[item] == 0:
        pygame.draw.rect(DISPLAYSURF, WHITE, (x, y, CELLSIZE, CELLSIZE))
    if lifeDict[item] == 1:
        pygame.draw.rect(DISPLAYSURF, GREEN, (x, y, CELLSIZE, CELLSIZE))
    return None

#Creates an dictionary of all the cells
#Sets all cells as dead (0)
def blankGrid():
    gridDict = {}
    #creates dictionary for all cells
    for y in range (CELLHEIGHT):
        for x in range (CELLWIDTH):
            gridDict[x,y] = 0 #Sets cells as dead
    return gridDict

#Assigns a 0 or a 1 to all cells
def startingGridRandom(lifeDict):
    for item in lifeDict:
        lifeDict[item] = random.randint(0,1)
    return lifeDict


#Determines how many alive neighbours there are around each cell
def getNeighbours(item,lifeDict):
    neighbours = 0
    for x in range (-1,2):
        for y in range (-1,2):
            checkCell = (item[0]+x,item[1]+y)
            if checkCell[0] < CELLWIDTH and checkCell[0] >=0:
                if checkCell [1] < CELLHEIGHT and checkCell[1]>= 0:
                    if lifeDict[checkCell] == 1:
                        if x == 0 and y == 0: # negate the central cell
                            neighbours += 0
                        else:
                            neighbours += 1
    return neighbours

#determines the next generation by running a 'tick'
def tick(lifeDict):
    newTick = {}
    for item in lifeDict:
        #get number of neighbours for that item
        numberNeighbours = getNeighbours(item, lifeDict)
        if lifeDict[item] == 1: # For those cells already alive
            if numberNeighbours < 2: # kill under-population newTick[item] = 0 elif numberNeighbours > 3: #kill over-population
                newTick[item] = 0
            else:
                newTick[item] = 1 # keep status quo (life)
        elif lifeDict[item] == 0:
            if numberNeighbours == 3: # cell reproduces
                newTick[item] = 1
            else:
                newTick[item] = 0 # keep status quo (death)
    return newTick

#main function
def main():
    pygame.init()
    global DISPLAYSURF
    FPSCLOCK = pygame.time.Clock()
    DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH,WINDOWHEIGHT))
    pygame.display.set_caption('Game of Life')

    DISPLAYSURF.fill(WHITE)

    lifeDict = blankGrid() # creates library and Populates to match blank grid
    lifeDict = startingGridRandom(lifeDict) # Assign random life
    
    #Colours the live cells, blanks the dead
    for item in lifeDict:
        colourGrid(item, lifeDict)

    drawGrid()
    pygame.display.update()
    
    while True: #main game loop
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()

        #runs a tick
        lifeDict = tick(lifeDict)

        #Colours the live cells, blanks the dead
        for item in lifeDict:
            colourGrid(item, lifeDict)

        drawGrid()
        pygame.display.update()    
        FPSCLOCK.tick(FPS)
        
if __name__=='__main__':
    main()

Installare Idle in Fedora

Idle è un ambiente visuale che permette di modificare, eseguire, e fare il debug di programmi Python da un’unica interfaccia: IDLE (Integrated Development and Learning Environment).

 Avviando IDLE, apparirà una finestra con l’ormai noto prompt dei comandi Python (>>>), e le voci di menu che si è abituati a vedere in altre applicazioni simili.

IDLE non è installato di default in Fedora…

Per installarlo bisogna seguire  questi passi

Per Python2 :

  1. per Python2 dnf -y install python-tools
  2. per avviare IDLE digitare idle&
  3. per aggiungere IDLE al menù Applicazioni seguire i seguenti passi
    1. scaricare l’immagine per l’Icona di IDLE con il seguente comando
      wget -O /usr/share/icons/idle.png https://s3-us-west-2.amazonaws.com/wsldpshare/images/idle.png
    2. creare con il vostro editor preferito il file
      /usr/share/applications/idle2.desktop con il seguente contenuto

      [Desktop Entry]
      Version=1.0
      Type=Application
      Name=IDLE 2
      GenericName=Text Editor
      Comment=Interactive Editor for Python Programming
      Exec=idle
      Terminal=false
      MimeType=text/plain;
      Icon=/usr/share/icons/idle.png
      Categories=TextEditor;Development;
      StartupNotify=true
      Actions=Window;Document;

Per Python3 :

  1. per Python3  dnf -y install python3-tools
  2. per avviare IDLE digitare idle3&
  3. per aggiungere IDLE al menù Applicazioni seguire i seguenti passi
    1. scaricare l’immagine per l’Icona di IDLE con il seguente comando
      wget -O /usr/share/icons/idle.png https://s3-us-west-2.amazonaws.com/wsldpshare/images/idle.png
    2. creare con il vostro editor preferito il file
      /usr/share/applications/idle3.desktop con il seguente contenuto

      [Desktop Entry]
      Version=1.0
      Type=Application
      Name=IDLE 3
      GenericName=Text Editor
      Comment=Interactive Editor for Python Programming
      Exec=idle3
      Terminal=false
      MimeType=text/plain;
      Icon=/usr/share/icons/idle.png
      Categories=TextEditor;Development;
      StartupNotify=true
      Actions=Window;Document;

Python

per sapere che versione di Python è installata sul vostro sistema:
ls /usr/bin/python*
questo è l’output:

/usr/bin/python /usr/bin/python3.5m
/usr/bin/python2 /usr/bin/python3-chardetect
/usr/bin/python2.7 /usr/bin/python3-coverage
/usr/bin/python2.7-config /usr/bin/python3-mako-render
/usr/bin/python2-config /usr/bin/python3-pyinotify
/usr/bin/python2-coverage /usr/bin/python-config
/usr/bin/python3 /usr/bin/python-coverage
/usr/bin/python3.5

In questo esempio è presente sia Python 2.7 che Python 3.5

Invece per sapere quale è la versione di default del vostro sistema digitate:

python -V
e in output in questo caso si ha
Python 2.7.12