Wednesday, August 1, 2012

python: snake game

Here is my second try to write a simple game in python using pygame. I'm not posting here the whole source code since I don't want the post to be too long. The complete source code can be downloaded from this link.

First lets take a look at the game...

Snake Game Screen Cast:


 

Snake Class: 

Besides pygame, im using three self made classes on the game:
  • snake.py
  • food.py 
  • colors.py
The source code has plenty of comments which should make it quite easy to understand what is going on.
snake.py
  1 #==============================================================================================#
  2 # Name        : snake.py                                                                       #
  3 # Description : The snake class definition for the snake game.                                 #
  4 # Author      : Adrian Antonana                                                                #
  5 # Date        : 29.07.2012                                                                     #
  6 #==============================================================================================#
  7 
  8 # imports
  9 import pygame as pg
 10 from colors import *
 11 
 12 # motion direction constants
 13 UP    = 0
 14 DOWN  = 1
 15 LEFT  = 2
 16 RIGHT = 3
 17 
 18 # block sizes
 19 BLOCK_SIZE       = 30
 20 BLOCK_SIZE_INNER = 20
 21 
 22 # snake class definition
 23 class snake:
 24 
 25   # constructor
 26   def __init__(self,surface,headposx=10,headposy=10):
 27     self.surface = surface
 28     self.length  = 10
 29     self.poslist = [(headposx,y) for y in reversed(range(headposy-self.length+1,headposy+1))]
 30     self.motdir  = RIGHT
 31     self.crashed = False
 32 
 33     # for drawing the snake
 34     self.snakeblock = pg.Surface((BLOCK_SIZE,BLOCK_SIZE))
 35     self.snakeblock.set_alpha(255)
 36     self.snakeblock.fill(GREEN)
 37     self.snakeblockdark = pg.Surface((BLOCK_SIZE_INNER,BLOCK_SIZE_INNER))
 38     self.snakeblockdark.set_alpha(255)
 39     self.snakeblockdark.fill(GREEN_DARK)
 40 
 41     # for removing the snake
 42     self.backblock = pg.Surface((BLOCK_SIZE,BLOCK_SIZE))
 43     self.backblock.set_alpha(255)
 44     self.backblock.fill(BLACK)
 45 
 46   # get snake's head position
 47   def getHeadPos(self):
 48     return (self.poslist[0])
 49 
 50   # get the motion direction
 51   def getMotionDir(self):
 52     return self.motdir
 53 
 54   # get the snake positions list
 55   def getPosList(self):
 56     return self.poslist
 57 
 58   # set the motion direction
 59   def setMotionDir(self,motdir):
 60     self.motdir = motdir
 61 
 62   # increase the snake length by one
 63   def incLength(self):
 64     self.length += 1
 65 
 66   # move the snake updates the positions list and checks if the snake has crashed
 67   def move(self):
 68     motdir = self.getMotionDir()
 69     headpos = self.getHeadPos()
 70 
 71     # update positions
 72     if motdir == UP:
 73       poslist = [(headpos[0]-1,headpos[1])]
 74     elif motdir == DOWN:
 75       poslist = [(headpos[0]+1,headpos[1])]
 76     elif motdir == LEFT:
 77       poslist = [(headpos[0],headpos[1]-1)]
 78     elif motdir == RIGHT:
 79       poslist = [(headpos[0],headpos[1]+1)]
 80 
 81     poslist.extend(self.poslist[:-1])
 82     self.poslist = poslist
 83 
 84     # check if crashed
 85     if self.getHeadPos() in self.getPosList()[1:]:
 86       self.crashed = True
 87 
 88   # check if the snake has crashed
 89   def chrashed(self):
 90     return self.crashed
 91 
 92   # grow the snake. add a new position at the end
 93   def grow(self):
 94     lastpos = self.getPosList()[-1]
 95     self.length += 1
 96     self.poslist.append((lastpos[0]-1,lastpos[1]))
 97 
 98   # draw the snake
 99   def draw(self):
100     skb = self.snakeblock
101     skbd = self.snakeblockdark
102     sf = self.surface
103 
104     for blockpos in self.getPosList():
105       sf.blit(skb,(blockpos[1]*BLOCK_SIZE,blockpos[0]*BLOCK_SIZE))
106       sf.blit(skbd,(blockpos[1]*BLOCK_SIZE+5,blockpos[0]*BLOCK_SIZE+5))
107 
108   # delete the snake
109   def remove(self):
110     bkb = self.backblock
111     sf = self.surface
112 
113     # draw block for every snake position
114     for blockpos in self.getPosList():
115       sf.blit(bkb,(blockpos[1]*BLOCK_SIZE,blockpos[0]*BLOCK_SIZE))

17 comments:

  1. Im getting into python, this is nice work <3

    ReplyDelete
    Replies
    1. When I run it, it not work. Could you help me ?

      Delete
    2. You have to delete the numbers in the commands, i meant the line number.

      Delete
  2. It's not work!!! Could you send me a new code and video tutorial for me?

    Thanks!

    ReplyDelete
    Replies
    1. Just delete the numbers of the lines, in front of the commands.

      Delete
  3. Btw, eik nachuj. :) Best Regards, Britain.

    ReplyDelete
  4. thank you so much for this good informations !

    ดูหนังออนไลน์

    ReplyDelete
  5. IS NOT WORK
    # imports
    import pygame as pg
    from colors import *

    # motion direction constants
    UP = 0
    DOWN = 1
    LEFT = 2
    RIGHT = 3

    # block sizes
    BLOCK_SIZE = 30
    BLOCK_SIZE_INNER = 20

    # snake class definition
    class snake:

    # constructor
    def __init__(self,surface,headposx=10,headposy=10):
    self.surface = surface
    self.length = 10
    self.poslist = [(headposx,y) for y in reversed(range(headposy-self.length+1,headposy+1))]
    self.motdir = RIGHT
    self.crashed = False

    # for drawing the snake
    self.snakeblock = pg.Surface((BLOCK_SIZE,BLOCK_SIZE))
    self.snakeblock.set_alpha(255)
    self.snakeblock.fill(GREEN)
    self.snakeblockdark = pg.Surface((BLOCK_SIZE_INNER,BLOCK_SIZE_INNER))
    self.snakeblockdark.set_alpha(255)
    self.snakeblockdark.fill(GREEN_DARK)

    # for removing the snake
    self.backblock = pg.Surface((BLOCK_SIZE,BLOCK_SIZE))
    self.backblock.set_alpha(255)
    self.backblock.fill(BLACK)

    # get snake's head position
    def getHeadPos(self):
    return (self.poslist[0])

    # get the motion direction
    def getMotionDir(self):
    return self.motdir

    # get the snake positions list
    def getPosList(self):
    return self.poslist

    # set the motion direction
    def setMotionDir(self,motdir):
    self.motdir = motdir

    # increase the snake length by one
    def incLength(self):
    self.length += 1

    # move the snake updates the positions list and checks if the snake has crashed
    def move(self):
    motdir = self.getMotionDir()
    headpos = self.getHeadPos()

    # update positions
    if motdir == UP:
    poslist = [(headpos[0]-1,headpos[1])]
    elif motdir == DOWN:
    poslist = [(headpos[0]+1,headpos[1])]
    elif motdir == LEFT:
    poslist = [(headpos[0],headpos[1]-1)]
    elif motdir == RIGHT:
    poslist = [(headpos[0],headpos[1]+1)]

    poslist.extend(self.poslist[:-1])
    self.poslist = poslist

    # check if crashed
    if self.getHeadPos() in self.getPosList()[1:]:
    self.crashed = True

    # check if the snake has crashed
    def chrashed(self):
    return self.crashed

    # grow the snake. add a new position at the end
    def grow(self):
    lastpos = self.getPosList()[-1]
    self.length += 1
    self.poslist.append((lastpos[0]-1,lastpos[1]))

    # draw the snake
    def draw(self):
    skb = self.snakeblock
    skbd = self.snakeblockdark
    sf = self.surface

    for blockpos in self.getPosList():
    sf.blit(skb,(blockpos[1]*BLOCK_SIZE,blockpos[0]*BLOCK_SIZE))
    sf.blit(skbd,(blockpos[1]*BLOCK_SIZE+5,blockpos[0]*BLOCK_SIZE+5))

    # delete the snake
    def remove(self):
    bkb = self.backblock
    sf = self.surface

    # draw block for every snake position
    for blockpos in self.getPosList():
    sf.blit(bkb,(blockpos[1]*BLOCK_SIZE,blockpos[0]*BLOCK_SIZE))

    ReplyDelete
  6. My too Dear Some Help Please

    ReplyDelete
  7. output is not coming

    ReplyDelete
  8. how to get surface module please give the answer

    ReplyDelete
    Replies
    1. if you use pycharm go to file > default settings > project interpreter , chose your project interpreter and then you will see The plus sign have green color on left here you can install any module.

      Delete
  9. มาเด้ เป็นยังไง? เป็นส่วนประกอบของสารสกัดธรรมชาติมีอีกทั้งวิตามินรวม ธาตุ เอนเหล้าองุ่นและก็เชลล์บำบัดรักษา
    มีทั้งยังพลาสเซนต้าและก็คอลลาเจนโดนสารทั้งหมดจำเป็นที่จะต้องผ่านขั้นตอนตระเตรียมสูตรยาแบบ(Homeopathy)
    เป็นศาสตร์การบำบัดที่มีต้นกำเนิดมาจาก ประเทศเยอรมนี โดยกานศึกษาและทำการค้นพบของหมอ ซามุเอลฮาเนมัน แก่มากยิ่งกว่า 200
    ปีโดยมีวิธีการบำบัดรักษาว่า (ใช้สิ่งที่คล้ายคลึงกันมารักษาสิ่งที่คล้ายคลึงกัน) หรือการนำเอาสารที่เป็นต้นเหตุของอาการนั้นๆ


    มาเด้
    มาเด้ หน้าใส
    ฉีดมาเด้ ที่ไหนดี

    ReplyDelete