##################################################
#
# (C) Copyright 2010 Manuel Soukup, London
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##################################################

import pyglet, pygame
from pyglet.gl import *
from pyglet import window
from pyglet import font
from pyglet import clock
from pyglet.window import key
import sys, os, shutil
from pygame.locals import *
import datetime
import threading
import base64,  random
import pyKsoko_stones

class TextureEnableGroup(pyglet.graphics.Group):
	"""
	Handels the OpenGL state for Textures in 2D
	If used with TextureBindGroup it will set the correct state to add a Texture into a Batch obj

	"""
	def set_state(self):
		"""
		Enables OpenGL GL_TEXTURE_2D
		"""
		glEnable(GL_TEXTURE_2D)

	def unset_state(self):
		"""
		Disables OpenGL GL_TEXTURE_2D
		"""
		glDisable(GL_TEXTURE_2D)

class TextureBindGroup(pyglet.graphics.Group):
	"""
	This class is used to bind a texture element onto vertices and into an Batch obj
	Argument: texture obj.

	Example of useage:

	main_batch.add(4, GL_QUADS,TextureBindGroup(texture) , ('v2f', (100+x, 100, 200+x, 100, 200+x, 200, 100+x, 200)),
			('t2f', (0, 0, 1, 0, 1, 1, 0, 1)))

	"""
	def __init__(self, texture):
		"""
		Generates a TextureEnableGroup obj, loads the texture, sets the texture state to a 2D in OpenGL

		Use of class: TextureEnableGroup()
		"""
		texture_enable_group = TextureEnableGroup()
		super(TextureBindGroup, self).__init__(parent=texture_enable_group)
		texture.target = GL_TEXTURE_2D
		self.texture = texture

	def set_state(self):
		"""
		Binds texture from texture.id on OpenGL texture commands who are executed after this

		glBindTexture(GL_TEXTURE_2D, self.texture.id)
		"""
		glBindTexture(GL_TEXTURE_2D, self.texture.id)

	# No unset_state method required.

	def __eq__(self, other):
		"""
		The use of an ``__eq__`` method on the group to allow `Batch` to merge
		the two ``TextureBindGroup`` identical instances.

		"""
		return (self.__class__ is other.__class__ and
			self.texture == other.__class__)




class Target: # class of the balck block
	def __init__(self,pos):  # position of the block and parent
		self.x = 0
		self.x = 0
		self.x = pos[0] # pos is a list so it just gets 2 values
		self.y = pos[1] #
		self.sizeX=jumpSize
		self.sizeY=jumpSize
		self.stonevar=0
		self.collision = False
	def getCenterPointX(self):
		self.retX= self.x+(self.sizeX/2.0)
		return self.retX
	def getCenterPointY(self):
		self.retY= self.y+(self.sizeY/2.0)
		return self.retY
	def setPos(self,xnew,ynew):
		self.x = xnew # define new xy cords
		self.y = ynew
	def getPosX(self):
		return self.x
	def getPosY(self):
		return self.y
	def getPosXLeft(self):
		return self.x+jumpSize
	def getPosYDown(self):
		return self.y+jumpSize
	def getType(self):
		return 6
	def isLocked(self):
		return self.collision
	def setLock(self):
		self.collision = True
	def unsetLock(self):
		self.collision = False
	def setStone(self,stone2):
		self.stonevar=stone2
	def getStone(self):
		return self.stonevar

class Stone: # class of the balck block
	def __init__(self,pos, on,  alt):  # position of the block and parent
		self.x = pos[0] # pos is a list so it just gets 2 values
		self.y = pos[1] #
		self.sizeX=jumpSize
		self.sizeY=jumpSize
		self.onTarget =on
		self.altPic=alt
	def move(self,x,y):
			self.x += x # define new xy cords
			self.y += y
	def setPos(self,xnew,ynew):
		self.x = xnew # define new xy cords
		self.y = ynew
	def getCenterPointX(self):
		self.retX= self.x+(self.sizeX/2.0)
		return self.retX
	def getCenterPointY(self):
		self.retY= self.y+(self.sizeY/2.0)
		return self.retY
	def getPosX(self):
		return self.x
	def getPosY(self):
		return self.y
	def getPosXLeft(self):
		return self.x+jumpSize
	def getPosYDown(self):
		return self.y+jumpSize
	def getType(self):
		return 3
	def isTarget(self):
		#print "ask target"
		return self.onTarget
	def setTarget(self,coll):
		#print "set target",
		self.onTarget = coll
		print coll
	def isColliding(self):
		self.collision
		return self.collision
	def setColliding(self,coll):
		self.collision = coll
	def setPic(self, picc):
		self.altPic=picc
	def getPic(self):
		return self.altPic

class Wall: # class of the balck block
	def __init__(self,pos):  # position of the block and parent
		self.x = pos[0] # pos is a list so it just gets 2 values
		self.y = pos[1] #
		self.sizeX=jumpSize
		self.sizeY=jumpSize
	def getCenterPointX(self):
		self.retX= self.x+(self.sizeX/2.0)
		return self.retX
	def getCenterPointY(self):
		self.retY= self.y+(self.sizeY/2.0)
		return self.retY
	def getPosX(self):
		return self.x
	def setPos(self,xnew,ynew):
		self.x = xnew # define new xy cords
		self.y = ynew
	def getPosY(self):
		return self.y
	def getPosXLeft(self):
		return self.x+jumpSize
	def getPosYDown(self):
		return self.y+jumpSize
	def getType(self):
		return 8


class Player: # class of the balck block
	def __init__(self,pos):  # position of the block and parent
		self.x = pos[0] # pos is a list so it just gets 2 values
		self.y = pos[1] #
		self.sizeX=jumpSize
		self.sizeY=jumpSize
		self.direction='none'
		self.collision=0
	def move(self,x,y,d):
		if d ==1: # 1 left
			self.direction='R'
		if d ==2: # rigth
			self.direction='L'
		if d ==3: # down
			self.direction='D'
		if d ==4: # up
			self.direction='U'

		self.x += x # define new xy cords
		self.y += y
	def setPos(self,xnew,ynew):
		self.x = xnew # define new xy cords
		self.y = ynew
	def getCenterPointX(self):
		self.retX= self.x+(self.sizeX/2.0)
		return self.retX
	def getCenterPointY(self):
		self.retY= self.y+(self.sizeY/2.0)
		return self.retY
	def getPosX(self):
		return self.x
	def getPosY(self):
		return self.y
	def getPosXLeft(self):
		return self.x+jumpSize
	def getPosYDown(self):
		return self.y+jumpSize
	def getType(self):
		return 1
	def getDir(self):
		return self.direction


class Game_Basics(window.Window, threading.Thread):
	"""
	Class for game coding.

	Consits off:
	Timer
	OpenGL Batches
	Input Handling
	"""
	global gameVersion
	#############################  UPDATE !!!!!!!!!!!!
	gameVersion = '0.3.3'
	#############################  UPDATE !!!!!!!!!!!!
	global screenSizeX
	screenSizeX=800
	global screenSizeY
	screenSizeY=600
	global scrollX
	scrollX=0
	global scrollY
	scrollY=0
	global blockDraw
	blockDraw = False
	global jumpSize
	jumpSize = 32
	global stoneCrt
	stoneCrt = 0
	global checkTarget
	checkTarget = 0
	global currentLevelSet
	currentLevelSet = 0
	global currentLevel
	currentLevel = 1
	global loadNxtLev
	loadNxtLev=False
	global scrollCTRX
	scrollCTRX=0
	global scrollCTRY
	scrollCTRY=0
	global levTime
	levTime=0
	global levMoves
	levMoves=0
	global levSetMoves
	levSetMoves=0
	global levPushes
	levPushes=0
	global levSetPushes
	levSetPushes=0
	global displayHelp
	displayHelp=False
	global displayStats
	displayStats=False
	global displayMenu
	displayMenu=True
	global displayLevSet
	displayLevSet=False
	global displayOptions
	displayOptions=False
	global displayLevChoose
	displayLevChoose=False
	global displayAbout
	displayAbout=False
	global displayHelpMain
	displayHelpMain=False
	global playSound
	#playSound=True
	global playMusic
	playMusic=False
	global musicBuffer
	global endOfLevelSets
	endOfLevelSets=False
	global musicNames
	musicNames=[]
	global gameActive
	gameActive=True
	global musicCTR
	musicCTR=0
	global displayMusic
	displayMusic =False
	global music_is_playing
	music_is_playing = False
	global music_loop_it
	music_loop_it=0
	global play_n_track
	play_n_track=True
	global music_Timer
	global stoneList
	stoneList =[]
	global stoneListLevelset
	stoneListLevelset =[]
	global targetList
	targetList =[]
	global updateDone
	updateDone =False
	global drawSaved
	drawSaved=False
	global skinClassic
	#skinClassic=False
	global drawFPS
	drawFPS=False
	global collStone
	global plainBackground
	#plainBackground=False
	global truckColor
	truckColor=1
	collStone=True # important to be true at the beinning so the move batch is fillend
	global timerLevel, timeLevelSet, timerDisturb_start,  time_disturb
	global levScore, levSetScore,  stoneScore,  pushMulFact, drawLevelSavedTime,  levSetReload
	stoneScore= 225
	pushMulFact=10
	levSetScore=0
	levScore=0
	drawLevelSavedTime=1
	levSetReload=0
	global gameQuit
	gameQuit=False

	def __init__(self, *args, **kwargs):
		"""
		init for window , generates graphics batch and texture list
		starts main_loop()
		"""
		threading.Thread.__init__(self)
		win= window.Window.__init__(self, *args, **kwargs)

		self.set_caption("pyKsoko - working is fun!")

		pyglet.options['audio'] = ('alsa','openal',  'silent')

		#self.write_emptyStats()

		self.make_dirs()


		self.main_loop()

	def callback(self, dt):
		"""
		Is callles ever x seconds as stated in the
		clock.schedule_interval(self.callback, 0.1) in the main loop
		prints seconds since last call
		"""
		global updateDone, gameActive, displayStats

		if not displayHelp and not displayOptions and not displayHelpMain and not displayAbout and not displayLevSet and not displayStats and not displayMenu and not displayMusic  and not displayLevChoose:

			gameActive=True
		else:
			gameActive=False

		if not gameQuit:

			self.update_Game()

			self.timer_1_print_stuff(drawLevelSavedTime)
			updateDone=True
		else:
			pyglet.app.exit()
			self.close()

	def get_runningTime(self):
		"""
		prints the running time of the programm
		"""
		global startTime

		finish = datetime.datetime.now()
		print "programm runs since:",  datetime.datetime.now() - startTime


	def timer_1_print_stuff(self, time):
		"""
		Timer method exectues stuff after "time" and resets "startTimer_1"
		after execution

		!!! accuracy depends on callback() time if you put it in there if in main loop depends on CPU frequenzy!!!!

		if callback time > time --> no accuracy
		"""
		global drawSaved
		if not drawSaved:
			return

		if datetime.datetime.now().second - startTimer_1.second > time:
			#startTimer_1=datetime.datetime.now()
			drawSaved=False
			print ">>>>>>now %f seconds are gone"% time

	def main_loop(self):
		"""
		Draws fps and main_batch
		limits fps
		executes:
		clock.schedule_interval(self.callback, 0.1)
		in while ticks the clock
		and listens for events
		"""
		print "main loop"
		global  gameQuit
		#Create a font for our FPS clock
		self.ft = font.load('Arial', 24)
		#The pyglet.font.Text object to display the FPS
		self.fps_text = font.Text(self.ft, y=10)

		self.init_game_obj()

		#print truckColor
		#Schedule the Monster creation
		clock.schedule_interval(self.callback, 0.1)
		clock.set_fps_limit(90)# frequenzy of monitor

		while not self.has_exit and not gameQuit:
			self.dispatch_events()
			dt=clock.tick()
		#print "Execue after while because we have Threading but only inside the loop ;-)"
		print "Quit Game"
		gameQuit=True
		self.close()
		pyglet.app.exit()

	def make_dirs(self):

#		print "hallo"
		print sys.platform
#		#print os.environ['APPDATA']

# windows
		# %AppData%

		print "make dirs"

		global configPath

		global sys_path

		sys_path=sys.argv[0][:-10]

		print sys.argv[0][:-10]

		if sys.platform == "win32":

			f = os.environ['APPDATA']+"/.pyKsoko/"
			f2 = os.environ['APPDATA']+"/.pyKsoko/highscore"
			f3 = os.environ['APPDATA']+"/.pyKsoko/music"

		else: # mac or linux
			#print "dirs linux"
			f = os.environ['HOME']+"/.pyKsoko/"
			f2 = os.environ['HOME']+"/.pyKsoko/highscore"
			f3 = os.environ['HOME']+"/.pyKsoko/music"


		configPath=f
		d = os.path.dirname(f)
		if not os.path.exists(d):
			print "create"
			os.makedirs(d)

		if not os.path.exists(f2):
			os.makedirs(f2)

		if not os.path.exists(f3):
			os.makedirs(f3)

		fd =f+".nocopy.txt"
		if not os.path.exists(fd):
			print sys.argv[0]

			print sys_path

			shutil.copy(sys_path+"conf.dat", f)
			shutil.copy(sys_path+"save.dat", f)
			shutil.copy(sys_path+"stats.dat", f)
			FILE = open(fd,"w")
			#FILE.writelines(namelist)
			FILE.close()



	def init_OpenGL_Vars(self):
		glViewport(0, 0, 800, 600)
		glMatrixMode(GL_PROJECTION)
		glLoadIdentity()
		# deactivate  rendering of the backside of the polygone --> better perf
		glEnable(GL_CULL_FACE);
		glCullFace(GL_BACK);
		glOrtho(0,800,600,0,0,128);
		#glOrtho(0.0, 800, 600, 0.0, 1.0, 10.0) #procedure glOrtho(left, right, bottom, top, znear, zfar : double); #
		# znear =1 and zfar = 10 thi means you have -9 levels to use its minus because it is in front of the camera
		glMatrixMode(GL_MODELVIEW)
		glLoadIdentity()

		glEnable(GL_BLEND)
		#glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
		glEnable(GL_TEXTURE_2D)
		glShadeModel(GL_SMOOTH)
		glClearColor(1.0, 0.0, 0.0, 0.0)
		glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE)
		glEnable(GL_BLEND)
		glClearDepth(1.0)
		glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST)

	def init_game_obj(self):
		"""
		initialize one-time game stuff
		"""
		global gameObjects, currentLevel,  soundPlayer, currentLevelSet, musicBuffer
		onStepOnTarget =False
		gameObjects = [] # emty list of object created in the drawinf fork
		global texList, main_batch, dynamic_batch, background_batch, move_batch, startTime, startTimer_1, music_Timer, time_disturb, timeLevelSet
		#soundPlayer=pyglet.media.ManagedSoundPlayer()

		self.loadConfig()

		self.init_OpenGL_Vars()
		texList =[]
		dynamic_batch = pyglet.graphics.Batch()
		move_batch  = pyglet.graphics.Batch()
		background_batch = pyglet.graphics.Batch()

		timeLevelSet=datetime.timedelta()
		time_disturb=datetime.timedelta()
		startTime=datetime.datetime.now()
		startTimer_1=datetime.datetime.now()
		music_Timer=datetime.datetime.now()

		gameObjects.append(Player((-jumpSize,-jumpSize))) # append the block obj to the list, pos par, parent obj
		self.readLevel()
		pygame.mixer.init() # important for sound
		self.saveSound()
		self.readMusic()
		self.saveImages()
		self.bufferTrack(musicCTR)
		self.loadStonesInSetFromDisk()
		#self.countStonesInSet() # important but very resourceeating use to generate output for stones.,dat file!!!!
		self.init_batches_labels()


	def update_Game(self):
		"""
		Updates game stuff ervery x second
		draws screens and flips it
		"""
		#self.dispatch_events()

		self.clear()
		##########
		# updates here
		##########


		if play_n_track:
			self.play_next_track()

		if displayHelpMain:
			self.draw_help_main()


		if displayAbout:
			self.draw_about()

		if displayOptions:
			self.draw_options()

		if displayMenu:
			self.draw_main()

		if displayLevChoose:
			self.draw_levChoose()

		if displayMusic:
			self.draw_music()

		if displayLevSet:
			if music_is_playing:
				musicBuffer.stop()
			self.draw_levSet()

		if displayStats:
			if music_is_playing:
				musicBuffer.stop()
			self.draw_stats()

		if displayHelp:

			self.draw_help()

		if gameActive:
			self.draw_playfield()

		##########
		# updates stop!!!
		##########

		if drawFPS:
			self.fps_text.text = ("fps: %d") % (clock.get_fps())
			self.fps_text.draw()

		self.flip()


	def write_emptyStats_SaveFile(self):
		"""

		OUTDATED!!!!!!

		"""
		filename = "stats.dat"
		FILE = open(filename,"w")
		namelist = []
		name = "0XXXXX"
		namelist.append((base64.b64encode(name)+"\n"))
		namelist.append((base64.b64encode(name)+"\n"))
		namelist.append((base64.b64encode(name)+"\n"))
		namelist.append((base64.b64encode(name)+"\n"))
		namelist.append((base64.b64encode(name)+"\n"))
		namelist.append((base64.b64encode(name)))
		#namelist.append((base64.b64encode(name)+"\n"))
		FILE.writelines(namelist)
		FILE.close() # this is icing, you can just exit and this will be

		filename = "save.dat"
		FILE = open(filename,"w")
		namelist = []
		name = "0XXXXX"
		namelist.append((base64.b64encode(name)+"\n"))
		namelist.append((base64.b64encode(name)))
		#namelist.append((base64.b64encode(name)+"\n"))
		FILE.writelines(namelist)
		FILE.close() # this is icing, you can just exit and this will be

	def on_key_press(self, symbol, modifiers): ####### big performance problem here!!!!!!!!!!!!!!! also drawing jumps cause of 2. new pos
		"""Simple input handling of the keyboard"""
		global updateDone, collStone

		if not updateDone:
			return

		global levMoves, displayHelp, displayStats, displayLevSet, loadNxtLev, displayMusic, musicCTR, musicBuffer, gameActive, timerDisturb_start, time_disturb, timerLevel
		global drawFPS, skinClassic,  truckColor, plainBackground, background_batch,  displayMusic, displayMenu, displayOptions, levSetReload
		global levSetReload, levSetMoves, levSetPushes, levSetScore, endOfLevelSets

		if displayMenu:
			if endOfLevelSets:
				endOfLevelSets=False

		if displayOptions:
			if symbol == key.P:
				global playSound
				if playSound:

					playSound=False
				else:

					playSound=True
				#self.fillBatch_draw_music()
			elif symbol == key.F:
				#global playMusic
					if drawFPS:
						drawFPS=False
					else:

						drawFPS=True
			elif symbol == key.D:
				#global playMusic
					if drawFPS:
						drawFPS=False
					else:

						drawFPS=True
			elif symbol == key.U:
				#global playMusic
					if plainBackground:
						plainBackground=False
					else:

						plainBackground=True
			elif symbol == key.C:
				#global playMusic
					if skinClassic:
						skinClassic=False
					else:
						plainBackground=False
						skinClassic=True
			elif symbol == key.T:
				truckColor+=1
				if truckColor>4:
					truckColor=1

			elif symbol == key.ESCAPE:
				#self.init_game_obj()

				global texList
				texList=[]
				self.saveImages()
				displayOptions=False
				displayMenu=True
				background_batch=pyglet.graphics.Batch()
				if plainBackground:

					self.fillBatch(background_batch, 20, 0,0)
				else:

					self.fillBatch(background_batch, 0, 0,0)
				self.saveConfig()
			return # important to not ineract with other stuff

		#gameActive=True
		if displayMusic:
			global music_is_playing, playMusic,  music_loop_it, play_n_track, music_Timer, displayLevChoose
			if symbol == key.N:
				musicCTR+=1
				if musicCTR>len(musicNames)-1:
					musicCTR=0
			elif symbol == key.R:
				musicCTR-=1
				if musicCTR<0:
					musicCTR=len(musicNames)-1
			elif symbol == key.P:
				playMusic=True
				if music_is_playing:
					musicBuffer.stop()
					music_is_playing=False
				self.bufferTrack(musicCTR)
				music_is_playing=True
				music_Timer=datetime.datetime.now()
				musicBuffer.play(music_loop_it)
			elif symbol == key.L:
				if music_loop_it==0:
					if music_is_playing:
						musicBuffer.stop()
						music_is_playing=False
					music_loop_it=-1
					play_n_track=False
				else:
					music_loop_it=0
					play_n_track=True
			elif symbol == key.S:
				if music_is_playing:
					musicBuffer.stop()
					music_is_playing=False
			elif symbol == key.ESCAPE:
				time_disturb=time_disturb+((datetime.datetime.now()-timerDisturb_start))
				displayMusic=False

			return # important to not ineract with other stuff

		global displayAbout, displayHelpMain
		if displayAbout:
			if symbol == key.ESCAPE:
				displayAbout=False
				displayMenu=True
			return

		if displayHelpMain:
			if symbol == key.ESCAPE:
				displayHelpMain=False
				displayMenu=True
			return

#		if displayOptions:
#			if symbol == key.ESCAPE:
#				displayOptions=False
#				displayMenu=True
#			return
		global gameQuit
		if displayMenu:
			if symbol == key.C:
				displayLevChoose=True
				self.loadStatsFromDisk()
				displayMenu=False
			if symbol == key.L:
				self.loadStatsFromDisk()
				self.loadLevelFromDisk()
				displayMenu=False
			if symbol == key.A:
				displayAbout=True
				displayMenu=False
			if symbol == key.O:
				displayOptions=True
				displayMenu=False
			if symbol == key.H:
				displayHelpMain=True
				displayMenu=False
			if symbol == key.Q:
				gameQuit=True
			return

		if displayLevChoose:
			global currentLevelSet, currentLevel, levSetScore, timeLevelSet

			if symbol == key.ENTER:
				displayLevChoose=False

				#
				if savedLevSet==currentLevelSet:
					self.loadLevelFromDisk()
				else:
				#	currentLevel=0
				##	self.saveLevelToDisk()
				#	self.loadLevelFromDisk()
				#currentLevelSet-=1
				#currentLevel-=1
					levSetReload=0
					self.loadNextLevelSet(True)

					self.fillBatch_move()
			if symbol == key.ESCAPE:
				displayLevChoose=False
				displayMenu=True
			if symbol == key.N:
				currentLevelSet+=1
				if currentLevelSet>len(levelSetsList)-1:
					currentLevelSet=0
				self.loadStatsFromDisk()
			elif symbol == key.P:
				currentLevelSet-=1
				if currentLevelSet<0:
					currentLevelSet=len(levelSetsList)-1
				self.loadStatsFromDisk()
			if symbol == key.R:
				# empty stats file
				self.write_emptyStats_SaveFile()
				currentLevel=0
				levSetMoves=0
				levSetPushes=0
				timeLevelSet=datetime.timedelta()
				levSetScore=0
			return

		if displayLevSet:
			if symbol == key.SPACE:

				self.saveScreenShot()

				if not endOfLevelSets:
					displayLevSet=False
					displayStats=False
					#global    levSetPushes
					### save here for statsitics
					levSetReload=0
					levSetMoves=0
					levSetPushes=0
					levSetScore=0
					timeLevelSet=datetime.timedelta()
					self.saveStatsToDisk()
					#loadNxtLev=True
					self.loadNextLevel()
					#musicList[musicCTR].play()
				else:
					displayLevSet=False
					displayStats=False
					displayMenu=True
			else:
				return

		if displayStats:
			if symbol == key.SPACE:
				displayStats=False
				self.loadNextLevel()
				if not displayLevSet:
				#	global musicBuffer
					if music_is_playing:
						music_Timer=datetime.datetime.now()
						musicBuffer.play(music_loop_it)
					#musicList[musicCTR].play()
					#pass
			else:
				return

		if displayHelp:
			#gameActive=False
			if symbol == key.ESCAPE:
				#gameActive=True
				#print datetime.datetime.now()-timerDisturb_start
				time_disturb=time_disturb+((datetime.datetime.now()-timerDisturb_start))
				#print time_disturb
				displayHelp=False
			return

		if symbol == key.R:
			#global levSetReload
			timerLevel=datetime.datetime.now()
			self.restartLevel()
			levSetReload+=1
		if symbol == key.H:
			timerDisturb_start=datetime.datetime.now()
			displayHelp=True
			#gameActive=False
		if symbol == key.M:
			if len(musicNames)==0:
				print "NO music found!"
				return

			timerDisturb_start=datetime.datetime.now()
			#self.fillBatch_draw_music()
			displayMusic=True
			#musicBuffer.stop()
		#if symbol == key.S:
		#	self.saveLevelToDisk()
		if symbol == key.L:
			self.loadStatsFromDisk()
			self.loadLevelFromDisk()
		if symbol == key.K:
			self.loadNextLevel()
		if symbol == key.ESCAPE:
		#	global musicBuffer
			displayMenu=True
			if playMusic:
				musicBuffer.stop()
			#print "any key"

		if symbol == key.LEFT: # should work without check target and would gain fps!!!!! scrolling buggy
			self.scrolling('L')
			gameObjects[0].move(-jumpSize,0,2)
			levMoves+=1
			if self.collCheck():
				gameObjects[0].move(jumpSize,0,2)
				#blockDraw=False
				if not collStone:
					levMoves-=1
				#levMoves-=1

		if symbol == key.RIGHT:
			blockDraw=True
			#self.chTarget()
			self.scrolling('R')
			gameObjects[0].move(jumpSize,0,1)
			levMoves+=1
			if self.collCheck():
				gameObjects[0].move(-jumpSize,0,1)
				#blockDraw=False
				if not collStone:
					levMoves-=1
		if symbol == key.DOWN:
			#blockDraw=True
			#self.chTarget()
			self.scrolling('D')
			gameObjects[0].move(0,-jumpSize,3)
			levMoves+=1
			if self.collCheck():
				gameObjects[0].move(0,jumpSize,3)
				#blockDraw=False
				if not collStone:
					levMoves-=1
				#evMoves-=1
		if symbol == key.UP:
			#blockDraw=True
			##self.chTarget()
			self.scrolling('U')
			gameObjects[0].move(0,jumpSize,4)
			levMoves+=1
			if self.collCheck():
				gameObjects[0].move(0,-jumpSize,4)
				#blockDraw=False
				if not collStone:
					levMoves-=1
				#levMoves-=1

		self.fillBatch_dynamic()
		#print "coll stone: ", collStone
		if collStone:
			self.fillBatch_move()
			collStone=False
		updateDone=False

	def saveImages(self):
		#print "sav img"
		global  texList, truckColor

		if skinClassic:

			self.load_Tex(sys_path+"data/img/classic_skin/bg.png")
			self.load_Tex(sys_path+"data/img/classic_skin/wall.png")
			self.load_Tex(sys_path+"data/img/classic_skin/target.png")
			self.load_Tex(sys_path+"data/img/classic_skin/box.png")
			self.load_Tex(sys_path+"data/img/classic_skin/player.png")

			# necesarry otherwise the order of the arry would be crumbeld and crash would happen
			self.load_Tex(sys_path+"data/img/classic_skin/player.png")
			self.load_Tex(sys_path+"data/img/classic_skin/player.png")
			self.load_Tex(sys_path+"data/img/classic_skin/player.png")
			self.load_Tex(sys_path+"data/img/classic_skin/player.png")
			self.load_Tex(sys_path+"data/img/classic_skin/player.png")
			self.load_Tex(sys_path+"data/img/classic_skin/player.png")

		else:
			self.load_Tex(sys_path+"data/img/new_skin/bg.png")
			self.load_Tex(sys_path+"data/img/new_skin/wall.png")
			self.load_Tex(sys_path+"data/img/new_skin/target.png")
			self.load_Tex(sys_path+"data/img/new_skin/box.png")
			self.load_Tex(sys_path+"data/img/new_skin/box_ok.png")
			self.load_Tex(sys_path+"data/img/new_skin/box2.png")#5
			self.load_Tex(sys_path+"data/img/new_skin/box2_ok.png")


			if truckColor==1:
				p="b/"
			elif truckColor==2:
				p="g/"
			elif truckColor==3:
				p="p/"
			else:
				p="y/"

			self.load_Tex(sys_path+"data/img/new_skin/"+p+"truck_l.png")
			self.load_Tex(sys_path+"data/img/new_skin/"+p+"truck_r.png")
			self.load_Tex(sys_path+"data/img/new_skin/"+p+"truck_u.png")
			self.load_Tex(sys_path+"data/img/new_skin/"+p+"truck_d.png")#10

		self.load_Tex(sys_path+"data/img/music.png")
		self.load_Tex(sys_path+"data/img/help.png")
		self.load_Tex(sys_path+"data/img/stats.png")
		self.load_Tex(sys_path+"data/img/newLevSet.png")
		self.load_Tex(sys_path+"data/img/main.png")#15
		self.load_Tex(sys_path+"data/img/chLevSet.png")
		self.load_Tex(sys_path+"data/img/help_main.png")
		self.load_Tex(sys_path+"data/img/about.png")
		self.load_Tex(sys_path+"data/img/options.png")#20
		self.load_Tex(sys_path+"data/img/new_skin/bg2.png")
		#print len(texList)

	def play_next_track(self):
		"""
		Load textures into texture list
		"""
		if len(musicNames)==0:
			return

		global musicBuffer,  musicCTR, music_is_playing, music_Timer
		#print music_Timer.second,"|",  musicBuffer.get_length(),"|",  music_is_playing
		musicBufferDeta=datetime.timedelta(seconds=musicBuffer.get_length())
		#print music_Timer,"|",  music_is_playing, "|", musicBufferDeta
		if datetime.datetime.now() - music_Timer>musicBufferDeta and music_is_playing:
			#lead next song and play it
			#print "play next track"
			musicCTR+=1
			if musicCTR>len(musicNames)-1:
				musicCTR=0
			if music_is_playing:
					musicBuffer.stop()
					music_is_playing=False
			self.bufferTrack(musicCTR)
			music_is_playing=True
			music_Timer=datetime.datetime.now()
			musicBuffer.play(music_loop_it)
			#musicBuffer.play()


	def load_Tex(self, img):
		"""
		Load textures into texture list
		"""
		global texList
		tex =pyglet.image.load(img).texture

		tex.anchor_y = tex.height
		tex.anchor_x = tex.width

		texList.append(tex)

	def loadStonesInSetFromDisk(self):
		global stoneListLevelset

		stoneListLevelset = pyKsoko_stones.getStones()


	def countStonesInSet(self):
		""""
		#######################
		Use this to count the boxes in the level.data file and copy the output into stones.dat
		########################
		"""""
		self.levSet=0
		self.lev=1
		self.ctr=0
		global stoneListLevelset
		#print "count stones"
		#print len(levelSetsList)
		while self.levSet<len(levelSetsList): # levelsets
			#print "inside"# works!!!
			lenOneLev=len(levelSetsList[self.levSet][self.lev]) # important for ctr
			lenLevels=len(levelSetsList[self.levSet])
			stoneListLevelset.append(0)
			#print lenOneLev, lenLevels
			#print levelSetsList[self.levSet][self.lev][self.ctr]
			while self.lev<lenLevels:# 4 levels len levels is 5 , is executed in every level 1 time
				#print "inside 2"
				lenOneLev=len(levelSetsList[self.levSet][self.lev]) # important for ctr
				while self.ctr<lenOneLev: # loops touh the lines in one spe level
					#print "check one line"
					for tile in levelSetsList[self.levSet][self.lev][self.ctr]: #check tiles in line
						#print tile,
						if tile == "*" or tile == "$":
							stoneListLevelset[self.levSet]+=1
					self.ctr+=1
				self.lev+=1
				self.ctr=0
			self.levSet+=1
			self.lev=1
		print "test\n"
		print stoneListLevelset


	def findStones_Targets(self):
		global stoneList, stoneCrt, targetList
		stoneList=[]
		targetList=[]
		for obj in range(len(gameObjects)):
			if gameObjects[obj].getType()==3:
				stoneList.append(obj)
			if gameObjects[obj].getType()==6:
				targetList.append(obj)

		#print stoneList
		stoneCrt=len(stoneList)

	def fillBatch_scrolling(self):
		"""
		Fills main batch with data
		"""
		global  move_batch
		move_batch= pyglet.graphics.Batch()
		batch= move_batch

		global  texList, gameObjects, stoneList

		for obj in stoneList: # could be done with one search at the beginn and copy stone inits into new array
				if gameObjects[obj].isTarget():
					pic=4
				else:
					pic=3
				if skinClassic:
					if gameObjects[obj].isTarget():
						pic =2
					else:
						pic =3

				batch.add(4, GL_QUADS,TextureBindGroup(texList[pic]) , ('v2f', (gameObjects[obj].getPosX(), gameObjects[obj].getPosY(),gameObjects[obj].getPosXLeft() , gameObjects[obj].getPosY(), gameObjects[obj].getPosXLeft(), gameObjects[obj].getPosYDown(),gameObjects[obj].getPosX() ,gameObjects[obj].getPosYDown())),
			('t2f', (0, 0, 1, 0, 1, 1, 0, 1)))


	def fillBatch_move(self):
		"""
		Fills main batch with data
		"""
		global  move_batch
		move_batch= pyglet.graphics.Batch()
		batch= move_batch

		global  texList, gameObjects, stoneList


		for obj in stoneList: #
				if gameObjects[obj].isTarget():
					pic =4
					if gameObjects[obj].getPic():
						pic =6
				else:
					pic =3
					if gameObjects[obj].getPic():
						pic =5

				if skinClassic:
						pic =3

				batch.add(4, GL_QUADS,TextureBindGroup(texList[pic]) , ('v2f', (gameObjects[obj].getPosX(), gameObjects[obj].getPosY(),gameObjects[obj].getPosXLeft() , gameObjects[obj].getPosY(), gameObjects[obj].getPosXLeft(), gameObjects[obj].getPosYDown(),gameObjects[obj].getPosX() ,gameObjects[obj].getPosYDown())),
			('t2f', (0, 0, 1, 0, 1, 1, 0, 1)))

	def fillBatch_dynamic(self):
		"""
		Fills main batch with data
		"""
		global  dynamic_batch
		dynamic_batch= pyglet.graphics.Batch()
		batch= dynamic_batch

		global  texList, gameObjects, stoneList

		#pic = 4
		if gameObjects[0].getDir()=="U":
			pic=9
		elif 	gameObjects[0].getDir()=="D":
			pic=10
		elif 	gameObjects[0].getDir()=="R":
			pic=8
		else:
			pic=7

		if skinClassic:
			pic=4 # player

		batch.add(4, GL_QUADS,TextureBindGroup(texList[pic]) , ('v2f', (gameObjects[0].getPosX(), gameObjects[0].getPosY(),gameObjects[0].getPosXLeft() , gameObjects[0].getPosY(), gameObjects[0].getPosXLeft(), gameObjects[0].getPosYDown(),gameObjects[0].getPosX() ,gameObjects[0].getPosYDown())),
			('t2f', (0, 0, 1, 0, 1, 1, 0, 1)))

	def fillBatch(self,batch, index,  x, y):
		"""
		Fills main batch with data
		"""

		global  texList

		batch.add(4, GL_QUADS,TextureBindGroup(texList[index]) , ('v2f', (x, y, texList[index].width+x, y, texList[index].width+x, texList[index].height+y, x,texList[index].height+y )),
			('t2f', (0, 0, 1, 0, 1, 1, 0, 1)))

	def draw_playfield(self):
		"""
		Draws main bacht and init openGL blending
		"""
		global main_batch,  dynamic_batch, background_batch, move_batch
		#bg_batch.draw()

		background_batch.draw()
		main_batch.draw() # draw batch
		move_batch.draw()
		dynamic_batch.draw()

		if drawSaved:
			saveLabel.draw()

	def init_batches_labels(self):

		global escLabel, saveLabel

		escLabel = pyglet.text.Label('[ESC] to go back', font_name='Times New Roman',font_size=12,bold=True,
			color=(255,255,255, 255), x=680, y=screenSizeY-572,
			anchor_x='left', anchor_y='top')

		saveLabel = pyglet.text.Label("Level saved!\n 'h'for help", font_name='Times New Roman',font_size=25,bold=True,
			color=(0, 0, 0, 255), x=screenSizeX//2+70, y=screenSizeY//2-30,multiline=True, width=300,
			anchor_x='center', anchor_y='bottom')

		################################################################
		###################### ABOUT #####################################
		global aboutMenu_batch, aboutlabel_2

		aboutMenu_batch=pyglet.graphics.Batch()

		self.fillBatch(aboutMenu_batch, 18, 0,0)

		aboutlabel_2 = pyglet.text.Label(
		"Programmer: Manuel Soukup\n\nDesign: Frederic Lespine\nhttp://www.mugadesign.com/\n\nSound: Other sokoban game\nhttp://sourceforge.net/projects/sokoban/\n\nMusic: Dinner for One by Amity in Fame \nhttp://www.amityinfame.com/\n\nTester: Stefan Buss, Manuel Soukup\n\nWindows Build: Volunteer needed!"
		, width=400, multiline=True, font_name='Times New Roman',font_size=14,
			color=(255, 255, 255, 255), x=65 , y=screenSizeY-196,#170
			anchor_x='left', anchor_y='top')

		################################################################
		################################################################
		################################################################
		###################### MAIN MENU ##################################
		global mainMenu_batch, mainlabel_1, mainlabel_2, mainlabel_3, mainlabel_4, mainlabel_5, mainlabel_6, mainlabel_7
		mainlabel_1 = pyglet.text.Label('[C]hoose levelset', font_name='Times New Roman',font_size=30,bold=True,
			color=(255, 255,  255, 255), x=145+97, y=screenSizeY-335+25,
			anchor_x='left', anchor_y='bottom')

		mainlabel_2 = pyglet.text.Label('[L]oad game', font_name='Times New Roman',font_size=30,
			color=(255, 255, 255, 255), x=145+97, y=screenSizeY-380+25,#170
			anchor_x='left', anchor_y='bottom')

		mainlabel_3 = pyglet.text.Label('[O]ptions', font_name='Times New Roman',font_size=30,bold=True,
			color=(255, 255, 255, 255), x=145+97, y=screenSizeY-420+25,
			anchor_x='left', anchor_y='bottom')

		mainlabel_4 = pyglet.text.Label('[H]elp', font_name='Times New Roman',font_size=30,bold=True,
			color=(255, 255, 255, 255),x=145+97, y=screenSizeY-510+25,
			anchor_x='left', anchor_y='bottom')

		mainlabel_5 = pyglet.text.Label('[A]bout', font_name='Times New Roman',font_size=30,
			color=(255, 255, 255, 255),x=145+97, y=screenSizeY-465+25,
			anchor_x='left', anchor_y='bottom')

		mainlabel_6 = pyglet.text.Label('[Q]uit', font_name='Times New Roman',font_size=30,
			color=(255, 255, 255, 255), x=145+97, y=screenSizeY-555+25,
			anchor_x='left', anchor_y='bottom')

		mainlabel_7 = pyglet.text.Label("v. "+gameVersion, font_name='Times New Roman',font_size=15,bold=True,
			color=(0, 0, 0, 70), x=675, y=screenSizeY-530,
			anchor_x='left', anchor_y='bottom')

		mainMenu_batch=pyglet.graphics.Batch()

		self.fillBatch(mainMenu_batch, 15, 0,0)

		################################################################
		################################################################
		################################################################
		###################### HELP MAIN MENU ###############################
		global helpMainMenu_batch, help_mainlab_1, help_maintext1, help_mainlab_2, help_maintext2, help_mainlab_3, help_maintext3
		help_mainlab_1 = pyglet.text.Label('What ...', font_name='Times New Roman',font_size=25,bold=True,
			color=(255,255, 255, 255), x=400, y=screenSizeY-20,
			anchor_x='center', anchor_y='top')

		help_maintext1 = pyglet.text.Label(
		"Sokoban is a classic puzzle,thought and logic game invented in Japan. \nThe original game of Sokoban was written by Hiroyuki Imabayashi.\n\nThe simplicity of the rules, in combination with the many levels ranging from easy to extremely difficult, have made Sokoban become a real classic."
		,width=650, multiline=True, font_name='Times New Roman',font_size=14,bold=True,
			color=(255,255, 255, 255), x=100, y=screenSizeY-60,#170
			anchor_x='left', anchor_y='top')

		help_mainlab_2 = pyglet.text.Label('Why ...', font_name='Times New Roman',font_size=25,bold=True,
			color=(255,255,255, 255), x=400, y=screenSizeY-190,
			anchor_x='center', anchor_y='top')

		help_maintext2 = pyglet.text.Label(
		"pyKsoko is a clone from Sokoban, yes another one. \nIt was intended as a clone of Ksokoban the old Sokoban clone from KDE 3.5.x because  unfortunately Ksokoban is not in KDE 4 anymore.\n\nSo I decided to clone the clone ...."
		,width=600, multiline=True, font_name='Times New Roman',font_size=14,bold=True,
			color=(255, 255, 255, 255), x=100, y=screenSizeY-230,#170\n\n
			anchor_x='left', anchor_y='top')

		help_mainlab_3 = pyglet.text.Label('Rules ...', font_name='Times New Roman',font_size=25,bold=True,
			color=(255,255,255, 255), x=400, y=screenSizeY-355,
			anchor_x='center', anchor_y='top')

		help_maintext3 = pyglet.text.Label(
		"The objective of the Sokoban game is to move the boxes to designated locations by pushing them.\nThe user controls a pusher with a forklift called 'Sokoban' which is said to mean something like 'warehouse keeper' in Japanese.\nThe pusher can move up, down, left and right, but cannot pass through walls or boxes, and can only push one box at a time (never pull).\nA square can only be occupied by either a wall, a box, or the pusher."
		,width=600, multiline=True, font_name='Times New Roman',font_size=14,bold=True,
			color=(255, 255, 255, 255), x=100, y=screenSizeY-395,#170\n\n
			anchor_x='left', anchor_y='top')

		helpMainMenu_batch=pyglet.graphics.Batch()

		self.fillBatch(helpMainMenu_batch, 17, 0,0)

		################################################################
		################################################################
		################################################################
		###################### OPTIONS MENU ################################
		global optionsMenu_batch#, optionslabel_3, optionslabel_4, optionslabel_5, optionslabel_6

		optionsMenu_batch=pyglet.graphics.Batch()

		self.fillBatch(optionsMenu_batch, 19, 0,0)

		################################################################
		################################################################
		################################################################
		###################### CHOOSELEVELSET MENU ##########################
		global levChooseMenu_batch, levChooselabel_4, levChooselabel_5, levChooselabel_6, levChooselabel_17, levChooselabel_8

		levChooseMenu_batch=pyglet.graphics.Batch()

		self.fillBatch(levChooseMenu_batch, 16, 0,0)


		levChooselabel_4 = pyglet.text.Label("[p]rev", font_name='Times New Roman',font_size=15,
			color=(255, 255, 255, 255), x=141, y=screenSizeY-120+12,#170
			anchor_x='left', anchor_y='bottom')

		levChooselabel_5 = pyglet.text.Label("[n]ext", font_name='Times New Roman',font_size=15,
			color=(255, 255, 255, 255), x=299, y=screenSizeY-120+12,#170
			anchor_x='left', anchor_y='bottom')

		levChooselabel_6 = pyglet.text.Label("[Enter] play", font_name='Times New Roman',font_size=15,
			color=(255, 255, 255, 255), x=270, y=screenSizeY-161,#170
			anchor_x='left', anchor_y='bottom')

		levChooselabel_17 = pyglet.text.Label("[r]eset levelset", font_name='Times New Roman',font_size=15,
			color=(255, 255, 255, 255), x=105, y=screenSizeY-161,#170
			anchor_x='left', anchor_y='bottom')

		levChooselabel_8 = pyglet.text.Label("Levelset info", font_name='Times New Roman',font_size=17,bold=True,
			color=(0, 0, 0, 255), x=330, y=screenSizeY-310,#170
			anchor_x='left', anchor_y='bottom')
		################################################################
		################################################################
		################################################################
		###################### HELP MENU ##################################
		global helpMenu_batch, helplabel_2, helplabel_3, helplabel_4, helplabel_5, helplabel_6, helplabel_7

		helplabel_2 = pyglet.text.Label('[m] choose music', font_name='Times New Roman',font_size=20,
			color=(0, 0, 0, 255), x=210+40, y=screenSizeY-195+20,#170
			anchor_x='left', anchor_y='top')

		helplabel_3 = pyglet.text.Label('[k]   = jump level', font_name='Times New Roman',font_size=20,
			color=(0, 0, 0, 255), x=210+40, y=screenSizeY-225+20-10,
			anchor_x='left', anchor_y='top')

		helplabel_4 = pyglet.text.Label('[ESC]   = back to main menu', font_name='Times New Roman',font_size=20,
			color=(0, 0, 0, 255), x=210+40, y=screenSizeY-255+20-16,
			anchor_x='left', anchor_y='top')

		helplabel_5 = pyglet.text.Label('[r]   = restart this level', font_name='Times New Roman',font_size=20,
			color=(0, 0, 0, 255), x=210+40, y=screenSizeY-285-4,
			anchor_x='left', anchor_y='top')

		helplabel_6 = pyglet.text.Label('[h]   = display this', font_name='Times New Roman',font_size=20,
			color=(0, 0, 0, 255), x=210+40, y=screenSizeY-315-12,
			anchor_x='left', anchor_y='top')

		helplabel_7 = pyglet.text.Label('[ARROWS] = move truck', font_name='Times New Roman',font_size=20,
			color=(0, 0, 0, 255), x=210+40, y=screenSizeY-345-20,
			anchor_x='left', anchor_y='top')

		helpMenu_batch=pyglet.graphics.Batch()

		self.fillBatch(helpMenu_batch, 12, 0,0)

		################################################################
		################################################################
		################################################################
		###################### MUSIC MENU #################################
		global musicMenu_batch, musiclabel_4, musiclabel_5, musiclabel_6, musiclabel_9, musiclabel_11

		musiclabel_4 = pyglet.text.Label("p[r]ev", font_name='Times New Roman',font_size=15,
			color=(255, 255, 255, 255), x=15+150+10, y=screenSizeY-250-45-50-40-3,#170
			anchor_x='left', anchor_y='bottom')

		musiclabel_5 = pyglet.text.Label("[n]ext", font_name='Times New Roman',font_size=15,
			color=(255, 255, 255, 255), x=15+150+10, y=screenSizeY-250-45-45-2,#170
			anchor_x='left', anchor_y='bottom')

		musiclabel_6 = pyglet.text.Label("[p]lay", font_name='Times New Roman',font_size=15,
			color=(255, 255, 255, 255), x=15+150+10, y=screenSizeY-220-25-3,#170
			anchor_x='left', anchor_y='bottom')

		musiclabel_9 = pyglet.text.Label("[s]top", font_name='Times New Roman',font_size=15,
			color=(255, 255, 255, 255), x=15+150+10, y=screenSizeY-250-45,#170
			anchor_x='left', anchor_y='bottom')

		musiclabel_11 = pyglet.text.Label("[l]oop", font_name='Times New Roman',font_size=15,
			color=(255, 255, 255, 255), x=335+10, y=screenSizeY-250+3,#170
			anchor_x='left', anchor_y='bottom')

		musicMenu_batch=pyglet.graphics.Batch()

		self.fillBatch(musicMenu_batch, 11, 0,0)
		################################################################
		################################################################
		################################################################
		###################### STATS MENU #################################
		global statsMenu_batch, statslabel_15, statslabel_12, statslabel_13, statslabel_7, statslabel_1, statslabel_2

		statsMenu_batch=pyglet.graphics.Batch()

		self.fillBatch(statsMenu_batch, 13, 0,0)

		statslabel_15 = pyglet.text.Label("Score:", font_name='Times New Roman',font_size=15,
			color=(0,0, 0, 255), x=495-20, y=screenSizeY-442-10,
			anchor_x='left', anchor_y='bottom')

		statslabel_12 = pyglet.text.Label('Press [space] to continue', font_name='Times New Roman',font_size=15,
			color=(255, 255, 255, 255), x=300, y=screenSizeY-596+8,
			anchor_x='left', anchor_y='bottom')

		statslabel_13 = pyglet.text.Label('Score:', font_name='Times New Roman',font_size=15,
			color=(0, 0, 0, 255), x=235-125, y=screenSizeY-225-20,
			anchor_x='left', anchor_y='bottom')

		statslabel_7 = pyglet.text.Label('This Levelsset', font_name='Times New Roman',font_size=17,
			color=(0, 0, 0, 255), x=330, y=screenSizeY-355,
			anchor_x='left', anchor_y='bottom')

		statslabel_1 = pyglet.text.Label('Statistics', font_name='Times New Roman',font_size=17,bold=True,
			color=(0, 0, 0,  255), x=350, y=screenSizeY-150+10,
			anchor_x='left', anchor_y='bottom')

		statslabel_2 = pyglet.text.Label('This level', font_name='Times New Roman',font_size=17,
			color=(0, 0, 0, 255), x=350, y=screenSizeY-195,#170
			anchor_x='left', anchor_y='bottom')

		################################################################
		################################################################
		################################################################
		###################### LEVSET MENU #################################
		global levSetMenu_batch, levSetlabel_5, levSetlabel_6, levSetlabel_7, levSetlabel_12
		levSetlabel_5 = pyglet.text.Label('pyKsoko', font_name='Times New Roman',font_size=17,
				color=(0, 0, 0, 255), x=375, y=screenSizeY-85,bold=True,
				anchor_x='left', anchor_y='bottom')

		levSetlabel_6 = pyglet.text.Label('Certificate that you completed \na levelset in pyKsoko.\n\nCongratulations!', font_name='Times New Roman',font_size=17,
				color=(0, 0, 0, 255), x=280, y=screenSizeY-220,multiline=True, width=500,
				anchor_x='left', anchor_y='bottom')

		levSetlabel_7 = pyglet.text.Label('Levelsset completed:', font_name='Times New Roman',font_size=17,
				color=(0, 0, 0, 255), x=320, y=screenSizeY-260,bold=True,
				anchor_x='left', anchor_y='bottom')

		levSetlabel_12 = pyglet.text.Label('Press [space] to continue', font_name='Times New Roman',font_size=15,
			color=(255, 255, 255, 255), x=380, y=screenSizeY-596,
			anchor_x='left', anchor_y='bottom')

		levSetMenu_batch=pyglet.graphics.Batch()

		self.fillBatch(levSetMenu_batch, 14, 0,0)
		################################################################
		################################################################
	def draw_levSet(self):

		num= "Name: "+ str(levelSetsList[currentLevelSet-1][0])
		label_8 = pyglet.text.Label(num, font_name='Times New Roman',font_size=15,
			color=(0, 0, 0, 255), x=330+20, y=screenSizeY-300+10,
			anchor_x='left', anchor_y='bottom')

		num= "Pushes: "+ str(levSetPushes)
		label_9 = pyglet.text.Label(num, font_name='Times New Roman',font_size=15,
			color=(0, 0, 0, 255), x=330+20, y=screenSizeY-330+10,
			anchor_x='left', anchor_y='bottom')

		num= "Moves: "+ str(levSetMoves)
		label_10 = pyglet.text.Label(num, font_name='Times New Roman',font_size=15,
			color=(0, 0, 0, 255), x=330+20, y=screenSizeY-360+10,
			anchor_x='left', anchor_y='bottom')

		n ="Time: "+str(timeLevelSet)[:-7]
		label_11 = pyglet.text.Label(n, font_name='Times New Roman',font_size=15,
			color=(0, 0, 0, 255), x=330+20, y=screenSizeY-390+10,
			anchor_x='left', anchor_y='bottom')

		n ="Reloaded: "+str(levSetReload)
		label_4 = pyglet.text.Label(n, font_name='Times New Roman',font_size=15,
			color=(0, 0, 0, 255), x=330+20, y=screenSizeY-420+10,
			anchor_x='left', anchor_y='bottom')

		n ="Score: "+str(levSetScore)
		label_3 = pyglet.text.Label(n, font_name='Times New Roman',font_size=15,
			color=(0, 0, 0, 255), x=330+20, y=screenSizeY-450+10,
			anchor_x='left', anchor_y='bottom')

		levSetMenu_batch.draw()
		label_3.draw()
		label_4.draw()
		levSetlabel_5.draw()
		levSetlabel_6.draw()
		levSetlabel_7.draw()
		label_8.draw()
		label_9.draw()
		label_10.draw()
		label_11.draw()
		levSetlabel_12.draw()


	def draw_stats(self):

		num= "Number in Set: "+ str(currentLevel)
		label_3 = pyglet.text.Label(num, font_name='Times New Roman',font_size=15,
			color=(0, 0, 0, 255), x=350, y=screenSizeY-225,
			anchor_x='left', anchor_y='bottom')

		num= "Pushes: "+ str(levPushes)
		label_4 = pyglet.text.Label(num, font_name='Times New Roman',font_size=15,
			color=(0, 0, 0, 255), x=350, y=screenSizeY-255,
			anchor_x='left', anchor_y='bottom')


		num= "Moves: "+ str(levMoves)
		label_5 = pyglet.text.Label(num, font_name='Times New Roman',font_size=15,
			color=(0, 0, 0, 255), x=350, y=screenSizeY-285,
			anchor_x='left', anchor_y='bottom')

		n ="Time: "+str(timerLevel)[2:-7]

		label_6 = pyglet.text.Label(n, font_name='Times New Roman',font_size=15,
			color=(0, 0, 0, 255), x=350, y=screenSizeY-315,
			anchor_x='left', anchor_y='bottom')

		num= "Name: "+ str(levelSetsList[currentLevelSet][0])
		label_8 = pyglet.text.Label(num, font_name='Times New Roman',font_size=15,
			color=(0, 0, 0, 255), x=330, y=screenSizeY-385,
			anchor_x='left', anchor_y='bottom')

		num= "Pushes: "+ str(levSetPushes)
		label_9 = pyglet.text.Label(num, font_name='Times New Roman',font_size=15,
			color=(0, 0, 0, 255), x=330, y=screenSizeY-415,
			anchor_x='left', anchor_y='bottom')

		num= "Moves: "+ str(levSetMoves)
		label_10 = pyglet.text.Label(num, font_name='Times New Roman',font_size=15,
			color=(0, 0, 0, 255), x=330, y=screenSizeY-445,
			anchor_x='left', anchor_y='bottom')

		n ="Time: "+str(timeLevelSet)[:-7]
		label_11 = pyglet.text.Label(n, font_name='Times New Roman',font_size=15,
			color=(0, 0, 0, 255), x=330, y=screenSizeY-475,
			anchor_x='left', anchor_y='bottom')

		n =str(levScore)
		label_14 = pyglet.text.Label(n, font_name='Times New Roman',font_size=15,bold=True,
			color=(255, 255, 255, 255), x=235-125, y=screenSizeY-245-20,
			anchor_x='left', anchor_y='bottom')


		n = str(levSetScore)
		label_16 = pyglet.text.Label(n, font_name='Times New Roman',font_size=15,bold=True,
			color=(0, 0, 0, 255), x=495-20, y=screenSizeY-462-10,
			anchor_x='left', anchor_y='bottom')

		statsMenu_batch.draw()
		statslabel_1.draw()
		statslabel_2.draw()
		label_3.draw()
		label_4.draw()
		label_5.draw()
		label_6.draw()
		statslabel_7.draw()
		label_8.draw()
		label_9.draw()
		label_10.draw()
		label_11.draw()
		statslabel_12.draw()
		statslabel_13.draw()
		label_14.draw()
		statslabel_15.draw()
		label_16.draw()

	def draw_levChoose(self):

		n = "You have "+str(len(levelSetsList))+u" levelsets.\nSelected levelset N\u00BA "+str(currentLevelSet)+""
		label_2 = pyglet.text.Label(n, font_name='Times New Roman',font_size=15,multiline=True,width=500,
			color=(255, 255, 255, 255), x=485, y=screenSizeY-151,#170
			anchor_x='left', anchor_y='bottom')

		n = "Name: "+str(levelSetsList[currentLevelSet][0])
		label_3 = pyglet.text.Label(n, font_name='Times New Roman',font_size=16,bold=True,
			color=(0, 0, 0, 255), x=200, y=screenSizeY-320-40,#170
			anchor_x='left', anchor_y='bottom')

		n = "No of Levels: "+str(len(levelSetsList[currentLevelSet])-1)
		label_9 = pyglet.text.Label(n, font_name='Times New Roman',font_size=16,bold=True,
			color=(0, 0, 0, 255), x=200, y=screenSizeY-350-40,#170
			anchor_x='left', anchor_y='bottom')

		n = "No of Boxes: "+str(stoneListLevelset[currentLevelSet])
		label_10 = pyglet.text.Label(n, font_name='Times New Roman',font_size=16,bold=True,
			color=(0, 0, 0, 255), x=200, y=screenSizeY-380-40,#170
			anchor_x='left', anchor_y='bottom')

		n = "Current Level: "+str(currentLevel+1)
		label_11 = pyglet.text.Label(n, font_name='Times New Roman',font_size=16,bold=True,
			color=(0, 0, 0, 255), x=200, y=screenSizeY-410-40,#170
			anchor_x='left', anchor_y='bottom')

		n = "Moves so far: "+str(levSetMoves)
		label_12 = pyglet.text.Label(n, font_name='Times New Roman',font_size=16,bold=True,
			color=(0, 0, 0, 255), x=453, y=screenSizeY-320-40,#170
			anchor_x='left', anchor_y='bottom')

		n = "Pushes so far: "+str(levSetPushes)
		label_13 = pyglet.text.Label(n, font_name='Times New Roman',font_size=16,bold=True,
			color=(0, 0, 0, 255), x=453, y=screenSizeY-350-40,#170
			anchor_x='left', anchor_y='bottom')

		n="Time so far: "+str(timeLevelSet)
		label_14 = pyglet.text.Label(n, font_name='Times New Roman',font_size=16,bold=True,
			color=(0, 0, 0, 255), x=453, y=screenSizeY-380-40,#170
			anchor_x='left', anchor_y='bottom')

		n="Score so far: "+str(levSetScore)
		label_15 = pyglet.text.Label(n, font_name='Times New Roman',font_size=16,bold=True,
			color=(0, 0, 0, 255), x=453, y=screenSizeY-410-40,#170
			anchor_x='left', anchor_y='bottom')

		n="Completed: "
		label_16 = pyglet.text.Label(n, font_name='Times New Roman',font_size=16,bold=True,
			color=(0, 0, 0, 255), x=330, y=screenSizeY-410-40-30,#170
			anchor_x='left', anchor_y='bottom')
		esc = pyglet.text.Label('[ESC] to go back', font_name='Times New Roman',font_size=12,bold=True,
			color=(255,255,255, 255), x=680, y=screenSizeY-572,
			anchor_x='left', anchor_y='top')

		levChooseMenu_batch.draw()

		label_2.draw()
		label_3.draw()
		levChooselabel_4.draw()
		levChooselabel_5.draw()
		levChooselabel_6.draw()
		levChooselabel_8.draw()
		label_9.draw()
		label_10.draw()
		label_11.draw()
		label_12.draw()
		label_13.draw()
		label_14.draw()
		label_15.draw()
		levChooselabel_17.draw()
		escLabel.draw()

	def draw_music(self):

		if len(musicNames)==0:
			global displayMusic, time_disturb
			time_disturb=time_disturb+((datetime.datetime.now()-timerDisturb_start))
			displayMusic=False
			return

		n = musicNames[musicCTR][:-4]
		n =n.replace("- ","\n")
		label_3 = pyglet.text.Label(n, font_name='Times New Roman',multiline=True, width=300, font_size=15,bold=True,
			color=(184, 184, 77, 255), x=283-67-50, y=screenSizeY-130-45,#170
			anchor_x='left', anchor_y='bottom')

		if  music_loop_it==-1:
			v="loop"
			c=(0, 255, 0, 255)
		if  music_loop_it==0:
			v="no loop"
			c=(255, 255, 0, 255)
		label_14 = pyglet.text.Label(v, font_name='Times New Roman',font_size=15,bold=True,
			color=c, x=335+10, y=screenSizeY-290-3,#170
			anchor_x='left', anchor_y='bottom')

		musicMenu_batch.draw()

		label_3.draw()
		musiclabel_4.draw()
		musiclabel_5.draw()
		musiclabel_6.draw()
		musiclabel_9.draw()
		escLabel.draw()
		musiclabel_11.draw()
		label_14.draw()

	def draw_main(self):

		mainMenu_batch.draw()
		mainlabel_1.draw()
		mainlabel_2.draw()
		mainlabel_3.draw()
		mainlabel_4.draw()
		mainlabel_5.draw()
		mainlabel_6.draw()
		mainlabel_7.draw()

	def draw_options(self):

		if truckColor==1:
			t="blue"
		if truckColor==2:
			t="green"
		if truckColor==3:
			t="pink"
		if truckColor==4:
			t="yellow"

		n='[T]ruck color: '+t
		optionslabel_3 = pyglet.text.Label(n, font_name='Times New Roman',font_size=20,
			color=(255, 255, 255, 255), x=210, y=screenSizeY-220,
			anchor_x='left', anchor_y='bottom')
		n = "[P]lay sounds: "+str(playSound)
		optionslabel_4 = pyglet.text.Label(n, font_name='Times New Roman',font_size=20,
			color=(255, 255, 255, 255), x=210, y=screenSizeY-288,
			anchor_x='left', anchor_y='bottom')

		n = "[C]lassic KDE Skin: "+str(skinClassic)
		optionslabel_5 = pyglet.text.Label(n, font_name='Times New Roman',font_size=20,
			color=(255, 255, 255, 255), x=210, y=screenSizeY-355,
			anchor_x='left', anchor_y='bottom')

		n = "[U]se plain background: "+str(plainBackground)
		optionslabel_6 = pyglet.text.Label(n, font_name='Times New Roman',font_size=20,
			color=(255, 255, 255, 255), x=210, y=screenSizeY-420,
			anchor_x='left', anchor_y='bottom')

		optionsMenu_batch.draw()
		optionslabel_3.draw()
		optionslabel_4.draw()
		optionslabel_5.draw()
		optionslabel_6.draw()
		escLabel.draw()

	def draw_help_main(self):

		helpMainMenu_batch.draw()
		help_mainlab_1.draw()
		help_maintext1.draw()
		help_mainlab_2.draw()
		help_maintext2.draw()
		help_mainlab_3.draw()
		help_maintext3.draw()
		escLabel.draw()


	def draw_about(self):

		aboutMenu_batch.draw()
		aboutlabel_2.draw()
		escLabel.draw()


	def draw_help(self):

		helpMenu_batch.draw()
		helplabel_2.draw()
		helplabel_3.draw()
		helplabel_4.draw()
		helplabel_5.draw()
		helplabel_6.draw()
		helplabel_7.draw()
		escLabel.draw()

	def y(self, y1, img_Height):
		y2 = screenSizeY-y1-img_Height
		#print y2
		return y2


	def fillLevel(self,curLevSet,curLev):
		#gameObjects[0].setPos(-50,-50)
		global main_batch,  screenSizeX, screenSizeY, background_batch
		# add bg into batch
		# Wierd!!! behavour!!!!
		main_batch = pyglet.graphics.Batch()
		######
		#print "fill level"
		#plainBackground=True
		print plainBackground

		#self.fillBatch(background_batch, 0, 0,0)

		if plainBackground:

			self.fillBatch(background_batch, 20, 0,0)
			self.fillBatch(background_batch, 20, 0,0)
		else:

			self.fillBatch(background_batch, 0, 0,0)

		####
		self.ctr =0
		self.x=0
		self.lengh = len (levelSetsList[curLevSet][curLev])
		#print "fill lev"
		while self.ctr<self.lengh:   #generates Wall obj in gameObj list after player obj
			for tile in levelSetsList[curLevSet][curLev][self.ctr]:
				#print tile,
				if tile == "#":
					gameObjects.append(Wall((self.x,self.y(jumpSize*self.ctr,jumpSize ))))
					self.fillBatch(main_batch, 1, self.x,self.y(jumpSize*self.ctr,jumpSize ))
					self.x+=jumpSize
				else:
					self.x+=jumpSize

			self.ctr+=1
			self.x=0
		self.ctr =0
		while self.ctr<self.lengh:   #generates Stone obj in gameObj list after player Wall obj ---> wall is on top of stone
			for tile in levelSetsList[curLevSet][curLev][self.ctr]:

				#print tile,
				if tile == "$" or tile == "*":
					#print self.x
					number=random.randrange(0, 10, 2)
					if number>5:
						p =True
					else:
						p = False

					if tile == "*":
						gameObjects.append(Stone((self.x,self.y(jumpSize*self.ctr,jumpSize )), True, p))
						#self.fillBatch(main_batch, 8, self.x,self.y(jumpSize*self.ctr,jumpSize ))
						#self.stoneOnTarget()
					else:
						gameObjects.append(Stone((self.x,self.y(jumpSize*self.ctr,jumpSize )),  False, p))
						#self.fillBatch(main_batch, 3, self.x,self.y(jumpSize*self.ctr,jumpSize ))
					self.x+=jumpSize
				else:
					self.x+=jumpSize
					#print "11"
			self.ctr+=1
			self.x=0
		self.ctr =0
		while self.ctr<self.lengh:   #generates Target obj in gameObj list after player Wall Stone obj ---> stone is on top of target
			for tile in levelSetsList[curLevSet][curLev][self.ctr]:

				#print tile,
				if tile == "." or tile == "*" or tile == "+":
					#print self.x
#					if tile == "*":
					gameObjects.append(Target((self.x,self.y(jumpSize*self.ctr,jumpSize ))))
					self.fillBatch(main_batch, 2, self.x,self.y(jumpSize*self.ctr,jumpSize ))

					self.x+=jumpSize
				else:
					self.x+=jumpSize
					#print "11"
			self.ctr+=1
			self.x=0
		self.ctr =0
		while self.ctr<self.lengh:   #generates PlAYER obj in gameObj list after player Wall obj ---> wall is on top of stone
			for tile in levelSetsList[curLevSet][curLev][self.ctr]:

				#print tile,self.ctr
				if tile == "@" or tile == "+":

					gameObjects[0].setPos(self.x,self.y(jumpSize*self.ctr,jumpSize ))#workaround for positioning bug

					self.x+=jumpSize
				else:
					self.x+=jumpSize
					#print "11"
			self.ctr+=1
			self.x=0

		self.findStones_Targets()
		#self.countStones()
		self.chTarget()
		self.fillBatch_dynamic()

	def loadConfig(self): # levelset first

		global skinClassic, playSound, truckColor, plainBackground
		text_file = open(configPath+"conf.dat", "r")

		line = text_file.readline()
		#print "levS", int(line),
		line2 = text_file.readline()
		line3 = text_file.readline()
		line4 = text_file.readline()
		text_file.close()

		#print line, line2, line3, line4

		truckColor=int(line)

		#print "line2", line2
		playSound=bool(int(line2))
		skinClassic=bool(int(line3))
		plainBackground=bool(int(line4))

		#print truckColor, playSound, skinClassic, plainBackground

	def loadLevelFromDisk(self): # levelset first
		text_file = open(configPath+"save.dat", "r")

		line = text_file.readline()
		#print "levS", int(line),
		line =base64.b64decode(line)
		#print "XXXX ", line
		line = line[:-5]
		int1 = int(line)
		#print int1

		line2 = text_file.readline()
		line2 =base64.b64decode(line2)
		line2 = line2[:-5]
		#print "lev", int(line2)
		#print "XXX2 ", line2[:-5]
		int2 =  int(line2)


		text_file.close()
		global currentLevel
		global currentLevelSet
		currentLevel = int2
		currentLevelSet = int1
		#print "###########################"
		#print currentLevel
		#print currentLevelSet
		self.loadNextLevel()

	def loadStatsFromDisk(self):
		"""
		File layout:

		-levelset
		-moves in levelset
		-pushes
		-score
		-reload
		-time in levelset
		"""


		text_file = open(configPath+"stats.dat", "r") # stats file

		line = text_file.readline() # sved levset
		#print "levS", int(line),
		line =base64.b64decode(line)
		#print "XXXX ", line
		line = line[:-5]
		int1 = int(line)
		#print int1

		line2 = text_file.readline() #
		line2 =base64.b64decode(line2)
		line2 = line2[:-5]
		#print "lev", int(line2)
		#print "XXX2 ", line2[:-5]
		int2 =  int(line2)

		line3 = text_file.readline()
		line3 =base64.b64decode(line3)
		line3 = line3[:-5]
		#print "lev", int(line3)
		#print "XXX3 ", line3[:-5]
		int3 =  int(line3)

		line4 = text_file.readline() #score
		line4 =base64.b64decode(line4)
		line4 = line4[:-5]
		#print "lev", int(line4)
		#print "XXX4 ", line4[:-5]
		int4 =  int(line4)

		line6 = text_file.readline() #score
		line6 =base64.b64decode(line6)
		line6 = line6[:-5]
		#print "lev", int(line6)
		#print "XXX4 ", line6[:-5]
		int6 =  int(line6)

		line5 = text_file.readline() #time
		line5 =base64.b64decode(line5)
		line5 = line5[:-5]
		#print "lev", int(line5)
		#print "XXX5 ", line5#[:-5]
		line5int = int(line5)
		#print "now int", line5int

		int5 =  datetime.timedelta(seconds=line5int) # timdelta convert generate new timedelta with saved values

		text_file.close()

		text_file2 = open(configPath+"save.dat", "r") # load levelset and level from safe file

		lineX = text_file2.readline()
		#print "levS", int(line),
		lineX =base64.b64decode(lineX)
		#print "XXXX ", lineX
		lineX = lineX[:-5]
		int1X = int(lineX)
		#print int1X

		line2X = text_file2.readline()
		line2X =base64.b64decode(line2X)
		line2X = line2X[:-5]
		#print "lev", int(line2X)
		#print "XXX2 ", line2X[:-5]
		int2X =  int(line2X)


		text_file2.close()

		global levSetMoves, levSetPushes, levSetScore, timeLevelSet, currentLevel, savedLevSet, levSetReload
		#global currentLevelSet
		savedLevSet=int1X
		# if stats are saved for choosen levset and save file exists
		if int1 == currentLevelSet and currentLevelSet==int1X:
			#print "threre XXXS"
			levSetMoves=int2
			levSetPushes=int3
			levSetScore=int4
			timeLevelSet=int5
			currentLevel=int2X
			levSetReload=int6
		else:
			levSetMoves=0
			levSetPushes=0
			levSetScore=0
			timeLevelSet=datetime.timedelta()
			currentLevel=0
			levSetReload=0

		#currentLevel = int2
		#currentLevelSet = int1
		#print "###########################"
		#print timeLevelSet

	def saveStatsToDisk(self):
		"""
		File layout:

		-levelset
		-moves in levelset
		-pushes
		-score
		-reload
		-time in levelset
		"""
		# Let's create a file and write it to disk.
		filename = configPath+"stats.dat" #test2
		# Let's create some data:
		done = 0
		namelist = []
		name = str(currentLevelSet)+"zaqwd"
		namelist.append((base64.b64encode(name)+"\n"))
		name = str(levSetMoves)+"vrtol"
		namelist.append((base64.b64encode(name)+"\n"))
		name = str(levSetPushes)+"brtxt"
		namelist.append((base64.b64encode(name)+"\n"))
		name = str(levSetScore)+"faero"
		namelist.append((base64.b64encode(name)+"\n"))
		name = str(levSetReload)+"urewq"
		namelist.append((base64.b64encode(name)+"\n"))
		name = str(timeLevelSet.seconds)+"neotz"
		namelist.append(base64.b64encode(name))
		FILE = open(filename,"w")
		FILE.writelines(namelist)
		FILE.close() # this is icing, you can just exit and this will be
		# handled automagically.
		#print "save stats on disk"

	def saveConfig(self):
		# Let's create a file and write it to disk.
		filename = configPath+"conf.dat"# test.dat
		# Let's create some data:
		namelist = []
		name = truckColor
		namelist.append(str(name)+"\n")

		if playSound:
			name=1
		else:
			name =0
		namelist.append(str(name)+"\n")
		if skinClassic:
			name=1
		else:
			name =0
		namelist.append(str(name)+"\n")

		if plainBackground:
			name=1
		else:
			name =0
		namelist.append(str(name))
		FILE = open(filename,"w")
		FILE.writelines(namelist)
		FILE.close() # this is icing, you can just exit and this will be


	def saveLevelToDisk(self):
		# Let's create a file and write it to disk.
		filename = configPath+"save.dat"# test.dat
		# Let's create some data:
		done = 0
		namelist = []
		name = str(currentLevelSet)+"zaqwd"
		namelist.append((base64.b64encode(name)+"\n"))
		name = str(currentLevel-1)+"vrtol"
		namelist.append(base64.b64encode(name))
		FILE = open(filename,"w")
		FILE.writelines(namelist)
		FILE.close() # this is icing, you can just exit and this will be
		# handled automagically.
		#print "save lev on disk"
		global drawSaved,  startTimer_1
		startTimer_1=datetime.datetime.now() # timer to display message --> make drawSaved False again
		drawSaved=True
		#print drawSaved

	def readMusic(self):
		global musicNames
		import dircache
		musicNames = dircache.listdir(configPath+'/music/')


	def readLevel(self):
		#print "read lev"
		global levelSetsList
		levelSetsList = []
		global levelSetList
		levelSetList = []
		firstTime = True
		stopLevelAdd=False
		ctrLevelSetsList=0 # counter for the levelssets
		ctrLevelSetLevels=0 # level of one spec levelset
		text_file = open(sys_path+"level.data", "r")
		for line in text_file:
			if line[0] == "!":# and line[0] != "#" and line[0] != "%": # if line is no level def and no lev end def it must be a name of a set
				if not firstTime:
					ctrLevelSetsList+=1
					ctrLevelSetLevels=0
				levelSetsList.append([])
				line2 = line.replace("\n","")
				line2 = line2.replace("!","")
				levelSetsList[ctrLevelSetsList].append(line2) # add name into levelset without new line token

				firstTime=False
			if line[0] == " " or line[0] == "#":# or line[0] == "*": # first char in a line

				if not stopLevelAdd:
					levelSetsList[ctrLevelSetsList].append([])
					ctrLevelSetLevels+=1
					stopLevelAdd =True
				line2 = line.replace("\n","") # delete new line flag
				levelSetsList[ctrLevelSetsList][ctrLevelSetLevels].append(line2)

			if line[0] == "%" or line[0] == "!": # what todo when level finished
				#print "Level read end: " + line
				stopLevelAdd=False
		text_file.close()

	def targetPointX(self):
		if gameObjects[0].getDir() == 'L':
			return -jumpSize

		if gameObjects[0].getDir() == 'R':
			return jumpSize
		return 0

	def targetPointY(self):
		if gameObjects[0].getDir() == 'U':
			return jumpSize

		if gameObjects[0].getDir() == 'D':
			return -jumpSize
		return 0

	def saveSound(self):
		global soundPush
		global soundApp1
		global soundApp2
		soundPush = self.load_sound(sys_path+"data/snd","Slide.ogg")
		soundApp1= self.load_sound(sys_path+"data/snd","App1.ogg")
		soundApp2= self.load_sound(sys_path+"data/snd","App2.ogg")

	def bufferTrack(self, track): ## drepeached because of speed reasons!!!

		print len(musicNames)
		if len(musicNames)==0:
			return

		global musicBuffer
		musicBuffer=self.load_sound(configPath+"music",musicNames[track])
			#print musicNames[i]

	def load_sound(self, p, name):
		self.fullname = os.path.join(p, name)

		#music = pyglet.resource.media(self.fullname,streaming=False)
		music = pygame.mixer.Sound(self.fullname)
		return music

	#TODO Test scrolling
	def scrolling(self, direction): #wait
		global scrollX
		global scrollY, main_batch
		global scrollCTRX
		global scrollCTRY

		self.beginnToScrollX=(screenSizeX-jumpSize-(jumpSize*2))# 800 - 32 -128 = 640
		self.beginnToScrollY=(screenSizeY-jumpSize-(jumpSize*2))
		#self.beginnToScrollY=(jumpSize+(jumpSize*2))
		lengh2 = len(gameObjects)
		#main_batch = pyglet.graphics.Batch()
		if gameObjects[0].getPosX()>self.beginnToScrollX and  direction== 'R':
			main_batch = pyglet.graphics.Batch()
			scrollX=self.beginnToScrollX
			for i in range(lengh2):
				if i !=0:
					gameObjects[i].setPos((gameObjects[i].getPosX()-scrollX),gameObjects[i].getPosY())
					if gameObjects[i].getType()==8:
						self.fillBatch(main_batch, 1, gameObjects[i].getPosX(),gameObjects[i].getPosY())
					if gameObjects[i].getType()==6:
						self.fillBatch(main_batch, 2, gameObjects[i].getPosX(),gameObjects[i].getPosY())
			gameObjects[0].setPos((gameObjects[0].getPosX()-self.beginnToScrollX),gameObjects[0].getPosY())
			self.fillBatch_move()
			scrollCTRX+=1

		if gameObjects[0].getPosX()<jumpSize*2+1 and  direction== 'L' and scrollCTRX>0: # 800 - 50 -200
			scrollCTRX-=1
			main_batch = pyglet.graphics.Batch()
			for i in range(lengh2):
				if i !=0:
					gameObjects[i].setPos((gameObjects[i].getPosX()+self.beginnToScrollX),gameObjects[i].getPosY());
					if gameObjects[i].getType()==8:
						self.fillBatch(main_batch, 1, gameObjects[i].getPosX(),gameObjects[i].getPosY())
					if gameObjects[i].getType()==6:
						self.fillBatch(main_batch, 2, gameObjects[i].getPosX(),gameObjects[i].getPosY())
			self.fillBatch_move()
			if scrollCTRX==0:
				scrollX=self.beginnToScrollX
			gameObjects[0].setPos((gameObjects[0].getPosX()+scrollX),gameObjects[0].getPosY())
			scrollX-=self.beginnToScrollX
		#################### YYYYY broken
		if gameObjects[0].getPosY()<jumpSize*2+1 and  direction== 'D':
			main_batch = pyglet.graphics.Batch()
			scrollY=self.beginnToScrollY
			for i in range(lengh2):
				if i !=0:
					gameObjects[i].setPos((gameObjects[i].getPosX()),gameObjects[i].getPosY()+scrollY)
					if gameObjects[i].getType()==8:
						self.fillBatch(main_batch, 1, gameObjects[i].getPosX(),gameObjects[i].getPosY())
					if gameObjects[i].getType()==6:
						self.fillBatch(main_batch, 2, gameObjects[i].getPosX(),gameObjects[i].getPosY())
			gameObjects[0].setPos((gameObjects[0].getPosX()),gameObjects[0].getPosY()+self.beginnToScrollY)
			scrollCTRY+=1
			self.fillBatch_move()

		# brokn
		if gameObjects[0].getPosY()>self.beginnToScrollY and  direction== 'U' and scrollCTRY>0: # 800 - 50 -200
			main_batch = pyglet.graphics.Batch()
			scrollCTRY-=1
			#scrollY=self.beginnToScrollY
			for i in range(lengh2):
				if i !=0:
					gameObjects[i].setPos((gameObjects[i].getPosX()),gameObjects[i].getPosY()-self.beginnToScrollY)
					if gameObjects[i].getType()==8:
						self.fillBatch(main_batch, 1, gameObjects[i].getPosX(),gameObjects[i].getPosY())
					if gameObjects[i].getType()==6:
						self.fillBatch(main_batch, 2, gameObjects[i].getPosX(),gameObjects[i].getPosY())
			gameObjects[0].setPos((gameObjects[0].getPosX()),gameObjects[0].getPosY()-self.beginnToScrollY)
			self.fillBatch_move()

#			if scrollCTRY==0: # do we need this????
#				scrollY=self.beginnToScrollY
#			gameObjects[0].setPos((gameObjects[0].getPosX()),gameObjects[0].getPosY()+jumpSize)
#			scrollY-=self.beginnToScrollY

	def releaseTarget(self):
		for elementColStone in gameObjects: # test the elements on the map if they would collide if i wouldpush the stone
			if elementColStone != gameObjects[0]: # dont test yourself
				if elementColStone.getType()==6:
					if (self.isPointInsideRect((gameObjects[0].getCenterPointX()),(gameObjects[0].getCenterPointY()),elementColStone.getPosX(),elementColStone.getPosXLeft(),elementColStone.getPosY(),elementColStone.getPosYDown())):
						if elementColStone.isLocked():
							elementColStone.unsetLock()
	def chTarget(self): #rewrite so 2 arrays are used with the stones and the tagets in so more speed is gained!!!!!
		global levScore
		#print "check trgt"
		global stoneCrt
		global checkTarget
		checkTarget=0
		levScore=0
		#print "Stones on map: " + str(stoneCrt)
		#print stoneList
		for elementT in targetList:
			for elementS in stoneList:
				#if elementT != elementS: # dont collide with yourself
					#print elementT, elementS
					if (self.isPointInsideRect(gameObjects[elementT].getCenterPointX(),gameObjects[elementT].getCenterPointY(),gameObjects[elementS].getPosX(),gameObjects[elementS].getPosXLeft(),gameObjects[elementS].getPosY(),gameObjects[elementS].getPosYDown())):
						#if gameObjects[elementT].getType() == 3 and gameObjects[elementS].getType()==6:
								checkTarget +=1
								levScore=levScore+stoneScore
								#print "cht", checkTarget, stoneCrt
								gameObjects[elementT].setLock()
		global stoneCrt
		global loadNxtLev, displayStats, time_disturb,  timerLevel,  timeLevelSet, levSetMoves, levSetPushes, levSetScore
		if checkTarget==stoneCrt:
			global currentLevelSet
			stoneCrt =0
			#print datetime.datetime.now()
			timerLevel=datetime.datetime.now()-timerLevel-time_disturb
			#print timerLevel

			#print levScore, levMoves, levPushes, pushMulFact,levPushes*pushMulFact
			levScore=levScore-levMoves-levPushes*pushMulFact
			#print levScore, levSetMoves
			timeLevelSet=timeLevelSet+timerLevel
			#print levMoves, levSetMoves
			levSetMoves+=levMoves
			levSetPushes+=levPushes
			#levSetTime+=levTime
			levSetScore=levSetScore+levScore
			self.saveLevelToDisk()
			displayStats=True
			self.saveStatsToDisk()
			if playSound:
				soundApp1.play()
			#print "level complete stats for set have been saved !",loadNxtLev
		#else:
			#print "play"

	def restartLevel(self):
		global currentLevel, stoneCrt, levMoves, levPushes,  levTime
		stoneCrt=levMoves=levPushes=levTime=0
		currentLevel-=1
		self.loadNextLevel()

	def loadNextLevel(self):
		#print "load next lev"
		global currentLevel, stoneCrt, levMoves, levPushes,  levTime, levSetMoves, levSetPushes,  timerLevel, time_disturb, levScore, levSetScore

		levScore=0
		time_disturb=datetime.timedelta()
		stoneCrt=levMoves=levPushes=levTime=0
		#print "load next lev"
		#print currentLevelSet
		#print currentLevel, len (levelSetsList[currentLevelSet])-1
		#print
		lengh2 = len (levelSetsList[currentLevelSet])
		currentLevel+=1 # add level for loading next level
		if lengh2 >currentLevel:
			del gameObjects[:] # delete everything in the list
			#drwScrn.clear() # clean screen
			#self.update()
			gameObjects.append(Player((-jumpSize,-jumpSize)))
			gameObjects[0].move(-jumpSize,-jumpSize,0)
			self.fillLevel(currentLevelSet,currentLevel)
			self.fillBatch_move()
			timerLevel=datetime.datetime.now()
			self.saveLevelToDisk()
			timerLevel=datetime.datetime.now()
			# Take a screenshot of the actual level
			#pygame.image.save(pygame.display.get_surface(), "screenshot.png")
			#print

		else:
			#print "Levelset finished no levels in Levelset"

			self.loadNextLevelSet(False)

	def saveScreenShot(self):
		now = datetime.datetime.now()
		nameScr=now.strftime("%Y-%m-%d %H:%M:%S")
		nameScr2=str(levelSetsList[currentLevelSet-1][0])+" - "+nameScr
		pyglet.image.get_buffer_manager().get_color_buffer().save(configPath+"highscore/"+nameScr2)

	def loadNextLevelSet(self, newLoad):
		#print "next level set!!!"
		global currentLevelSet,currentLevel, displayLevSet, musicCTR, levSetScore
		global loadNxtLev # important otherwise python thinks itmusicCTR is a local var
		#print "##########################"
		#print currentLevelSet, currentLevel
		#print  len (levelSetsList)
		currentLevelSet+=1
		if newLoad:
				currentLevelSet-=1

		lengh2 = len (levelSetsList)
		if  lengh2 >currentLevelSet:

			if newLoad:
				currentLevel=0
				self.loadNextLevel()

			else:
				displayLevSet=True
				#currentLevelSet+=1
				currentLevel=0
				#levSetScore=0
				if playSound:
					soundApp2.play()
				currentLevel=0 # cause load next level will add 1 to the count
			#self.update()
#			if playMusic:
#				musicList[musicCTR].stop()

		else:
			displayLevSet=True
			global endOfLevelSets
			endOfLevelSets=True
			currentLevel=0
			currentLevelSet=0
			#print "no more levelsets break here before exeption"
			#print "//############################################"

	def collWithStone(self,index): # fct is called when player tries to push the stone.
		global levMoves, levPushes, collStone
		self.counter = 0
		collStone=True
		onStepOnTarget=False
		self.lenList = len(gameObjects)-2
		for elementColStone in gameObjects: # test the elements on the map if they would collide if i wouldpush the stone
			if elementColStone != gameObjects[index] and elementColStone != gameObjects[0]: # dont test yourself and player
				#print "object tests another obj not itself"
				if (self.isPointInsideRect((gameObjects[index].getCenterPointX()+self.targetPointX()),(gameObjects[index].getCenterPointY()+self.targetPointY()),elementColStone.getPosX(),elementColStone.getPosXLeft(),elementColStone.getPosY(),elementColStone.getPosYDown())):
					#print "stone collides with .."
					if elementColStone.getType() == 6 and not elementColStone.isLocked() and not onStepOnTarget:
						#print "drk"
						#print "move stone onto target"
						gameObjects[index].setTarget(True)
						gameObjects[index].move(self.targetPointX(),self.targetPointY()) # move stone to new pos
						gameObjects[0].move(self.targetPointX(),self.targetPointY(),0) # move player to new pos so it look
						#self.chTarget()
						onStepOnTarget=True
						if playSound:
							#soundPush.stopp()
							#soundPlayer.queue(soundPush)
							soundPush.play()
						levPushes+=1
						#levMoves-=1
						#self.chTarget()
				else:
					#print "stone does not collide with obj x in list"
					self.counter+=1 # adds one to the ctr
		if self.counter == self.lenList:
			#print "stone does not collide at all"
			#print "move stone around"
			if playSound:
				soundPush.play()
			levPushes+=1
			#levMoves-=1# necesarry cause we do not return false to key_input so they will not reduce moves
			gameObjects[index].setTarget(False)
			gameObjects[index].move(self.targetPointX(),self.targetPointY()) # move stone to new pos
			gameObjects[0].move(self.targetPointX(),self.targetPointY(),0) # move player to new pos so it look like he pushed 0= not in list --> no change in dir var
			#self.chTarget()
		else:
			#print "stone does collide with one or more obj"
			self.chTarget()
		#levMoves-=1# necesarry cause we do not return false to key_input so they will not reduce moves

	def collCheck(self): # checks every item in the list with every item in the list
		global levMoves, collStone
		self.releaseTarget() # checks if player is on target if so target get unlocked
		for element in gameObjects:
			for elementCol in gameObjects:
				if elementCol.getType() == 8 and element.getType() == 8:
					continue
				if elementCol != element: # dont collide with temself
					#print 'index:' + str(gameObjects.index(element)) + " type:" + str(element.getType()) + "is tested with " 'index:' + str(gameObjects.index(elementCol)) +" type:"+ str(elementCol.getType())
					if (self.isPointInsideRect(element.getCenterPointX(),element.getCenterPointY(),elementCol.getPosX(),elementCol.getPosXLeft(),elementCol.getPosY(),elementCol.getPosYDown())):
					#collide with themselves
						if elementCol.getType() == 6: #player can walk on target
							#levMoves+=1

							return False
						if elementCol.getType() == 3:# and element.getType() ==1 or elementCol.getType() == 6 and element.getType() ==1: # anything is colliding
							self.collWithStone(gameObjects.index(elementCol))
							collStone=True
							#print "coll with stone"
							#levMoves+=1
						#print "ficken"

						return True

	def isPointInsideRect(self,centerX,centerY, x1,x2,y1,y2): # check if centerpoint is in  another element
		#print "element 1 xcent " + str(centerX)+ " ycent " + str(centerY)+ " element 2 x " +str(x1) + " y " +str(y1) + " xend "+str(x2)+" yend "+str (y2)
		if (centerX > x1) and (centerX < x2) and (y1 < centerY) and (y2 > centerY):
			return True
		else:
			return False

if __name__ == '__main__':
	start = Game_Basics(width=screenSizeX, height=screenSizeY)
	start.start() # starts threading so timer will work!!!
	pyglet.app.run()
