Python

Python Scripting for Snake

 

Click Here for more python coding examples

Below are some of the .py scripts that I used to create the Snake Game

***Scrolling
#The x and y boundaries are represented by empty objects.
#The x and y values of these xyz tuples are used to bind the snake

from bge import logic
from mathutils import Vector
cont = logic.getCurrentController()
own = cont.owner
scene = logic.getCurrentScene()
head = scene.objects[“head”]
yMarker = scene.objects[“yMarker”]
xMarker = scene.objects[“xMarker”]

yLimit = yMarker.worldPosition[1]
xLimit = xMarker.worldPosition[0]
position = head.worldPosition

if position[0] > xLimit:
position[0] = -xLimit
if position[0] < -xLimit:
position[0] = xLimit

if position[1] > yLimit:
position[1] = -yLimit
if position[1] < -yLimit:
position[1] = yLimit

#Saving/Loading
#Create a file or read from a file that contains information
#About the number of sections the snake has and its xy position

from bge import logic
import pickle

def save(own):

cont = logic.getCurrentController()
own = cont.owner
scene = logic.getCurrentScene()
scoreObj = scene.objects[“score”]
addSection = cont.actuators[“addSection”]

file = open(“snakeData.txt”,’wb’)
list =[own.worldPosition.x,own.worldPosition.y,own[“direction”],addSection.time,scoreObj[“Text”]]
pickle.dump(list,file)
file.close()

def load(own):

cont = logic.getCurrentController()
own = cont.owner
scene = logic.getCurrentScene()
scoreObj = scene.objects[“score”]
addSection = cont.actuators[“addSection”]

file = open(“snakeData.txt”,’rb’)
listed = pickle.load(file)
file.close()

own.worldPosition.x = listed[0]
own.worldPosition.y = listed[1]
own[“direction”] = listed[2]
addSection.time = listed[3]
scoreObj[“Text”] = listed[4]

def saveLoad():
cont = logic.getCurrentController()
own = cont.owner
scene = logic.getCurrentScene()
scoreObj = scene.objects[“score”]
addSection = cont.actuators[“addSection”]

k = cont.sensors[“k”]
l = cont.sensors[“l”]

if k.positive:
print(“saved”)
save(own)
if l.positive:
print(“loaded”)
load(own)

*** Add Section

#Add a new section to the body of the snake

from bge import logic
from mathutils import Vector
cont = logic.getCurrentController()
own = cont.owner
scene = logic.getCurrentScene()
head = scene.objects[“head”]
addSection = cont.actuators[“addSection”]
addSection.time += 3

css.php