Moved all bindings to the "bindings" sub-directory

Renamed the CSFML directory to c
Renamed the DSFML directory to d
--> bindings must now be updated to match the new organization!

git-svn-id: https://sfml.svn.sourceforge.net/svnroot/sfml/branches/sfml2@1630 4e206d99-4929-0410-ac5d-dfc041789085
This commit is contained in:
LaurentGom 2010-11-09 17:13:17 +00:00
parent 0cc5563cac
commit 0e2297af28
417 changed files with 0 additions and 0 deletions

Binary file not shown.

After

Width:  |  Height:  |  Size: 868 B

Binary file not shown.

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

View file

@ -0,0 +1,98 @@
# coding=utf-8
from PySFML import sf
import random
# Simple class for an apple.
class Apple:
sprite = None
speed = (2, 2)
rotationstep = 1
def __init__( self, image ):
self.sprite = sf.Sprite( image )
self.sprite.SetOrigin( image.GetWidth() / 2, image.GetHeight() / 2 )
# Set resolution and create the window.
Resolution = (800, 600)
wnd = sf.RenderWindow( sf.VideoMode( Resolution[0], Resolution[1], 32 ), "Hello SFML!" )
wnd.UseVerticalSync( True )
# Load a fancy font.
cheese = sf.Font()
cheese.LoadFromFile( "data/cheeseburger.ttf" )
# Create a text.
text = sf.Text( u"Hello SFML from Python!", cheese, 50 )
text.SetOrigin( text.GetRect().GetSize()[0] / 2, text.GetRect().GetSize()[1] / 2 )
text.SetPosition( 400, 300 )
text.SetColor( sf.Color( 0, 100, 0, 100 ) )
# Create a text for FPS display.
fpstext = sf.Text( u"FPS: --", cheese )
fpstext.SetColor( sf.Color( 0, 0, 0 ) )
currentfps = 0
fpsclock = sf.Clock()
# Load apple image from file.
appleimage = sf.Image()
appleimage.LoadFromFile( "data/apple.png" )
# Create some apples with random position, speed, rotation and color.
apples = [Apple( appleimage ) for num in range( 0, 100 )]
for apple in apples:
apple.sprite.SetOrigin( appleimage.GetWidth() / 2, appleimage.GetHeight() / 2 )
apple.sprite.SetPosition(
random.randint( apple.sprite.GetOrigin()[0], Resolution[0] - apple.sprite.GetOrigin()[0] ),
random.randint( apple.sprite.GetOrigin()[1], Resolution[1] - apple.sprite.GetOrigin()[1] )
)
apple.sprite.SetColor( sf.Color( random.randint( 100, 255 ), random.randint( 100, 255 ), random.randint( 100, 255 ) ) )
randx = random.randint( -3, 3 )
randy = random.randint( -3, 3 )
apple.speed = (1 if randx == 0 else randx, 1 if randy == 0 else randy)
apple.rotationstep = random.uniform( 1.0, 20.0 ) - 10.0
event = sf.Event()
# Main loop.
while wnd.IsOpened():
# Fetch all pending events and process them.
while wnd.GetEvent( event ):
# Quit when window has been closed or Escape has been pressed.
if event.Type == sf.Event.Closed:
wnd.Close()
elif event.Type == sf.Event.KeyPressed and event.Key.Code == sf.Key.Escape:
wnd.Close()
# Clear window to white color.
wnd.Clear( sf.Color( 255, 255, 255 ) )
# Draw all apples and texts.
for apple in apples:
wnd.Draw( apple.sprite )
wnd.Draw( text )
wnd.Draw( fpstext )
wnd.Display() # Display everything.
# Count FPS.
currentfps += 1
if fpsclock.GetElapsedTime() >= 1.0:
fpsclock.Reset()
fpstext.SetString( u"FPS: " + unicode( currentfps ) )
currentfps = 0
# Update apples (for the "bounce effect").
for apple in apples:
apple.sprite.Move( apple.speed[0], apple.speed[1] )
apple.sprite.Rotate( apple.rotationstep )
realpos = (apple.sprite.GetPosition()[0] - apple.sprite.GetOrigin()[0], apple.sprite.GetPosition()[1] - apple.sprite.GetOrigin()[1])
if (apple.speed[0] > 0 and realpos[0] >= Resolution[0] - appleimage.GetWidth()) or (apple.speed[0] < 0 and realpos[0] <= 0):
apple.speed = (apple.speed[0] * -1, apple.speed[1])
if (apple.speed[1] > 0 and realpos[1] >= Resolution[1] - appleimage.GetWidth()) or (apple.speed[1] < 0 and realpos[1] <= 0):
apple.speed = (apple.speed[0], apple.speed[1] * -1)

View file

@ -0,0 +1,165 @@
#!/usr/bin/python
from PySFML import sf
from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *
def main():
# Create main window
App = sf.RenderWindow(sf.VideoMode(800, 600), "SFML OpenGL")
App.SetActive()
# Create a sprite for the background
BackgroundImage = sf.Image()
if not BackgroundImage.LoadFromFile("../../samples/bin/datas/opengl/background.jpg"):
return
Background = sf.Sprite(BackgroundImage)
# Load an OpenGL texture.
# We could directly use a sf.Image as an OpenGL texture (with its Bind() member function),
# but here we want more control on it (generate mipmaps, ...) so we create a new one
Image = sf.Image()
if not Image.LoadFromFile("../../samples/bin/datas/opengl/texture.jpg"):
return
# The next line is a bit different from the C++ version
Texture = glGenTextures(1) # instead of glGenTextures(1, &Texture);
glBindTexture(GL_TEXTURE_2D, Texture)
# It is almost the same line there, except in C++, the last argument was Image.GetPixelsPtr().
# In python, GetPixels simply returns a string.
gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, Image.GetWidth(), Image.GetHeight(), GL_RGBA, GL_UNSIGNED_BYTE, Image.GetPixels())
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR)
# Enable Z-buffer read and write
glEnable(GL_DEPTH_TEST)
glDepthMask(GL_TRUE)
glClearDepth(1.)
# Setup a perspective projection
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(90., 1., 1., 500.)
# Bind our texture
glEnable(GL_TEXTURE_2D)
glBindTexture(GL_TEXTURE_2D, Texture)
glColor4f(1., 1., 1., 1.)
# Create a clock for measuring the time elapsed
Clock = sf.Clock()
# Start game loop
while App.IsOpened():
# Process events
Event = sf.Event()
while App.GetEvent(Event):
# Close window : exit
if Event.Type == sf.Event.Closed:
App.Close()
# Escape key : exit
if (Event.Type == sf.Event.KeyPressed) and (Event.Key.Code == sf.Key.Escape):
App.Close()
# Adjust the viewport when the window is resized
if Event.Type == sf.Event.Resized:
glViewport(0, 0, Event.Size.Width, Event.Size.Height)
# Draw background
App.Draw(Background)
# Active window to be able to perform OpenGL commands.
App.SetActive()
# Clear depth buffer
glClear(GL_DEPTH_BUFFER_BIT)
# Apply some transformations
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
glTranslatef(0, 0, -200)
glRotatef(Clock.GetElapsedTime() * 50, 1, 0, 0)
glRotatef(Clock.GetElapsedTime() * 30, 0, 1, 0)
glRotatef(Clock.GetElapsedTime() * 90, 0, 0, 1)
# Draw a cube
glBegin(GL_QUADS)
glTexCoord2f(0, 0)
glVertex3f(-50., -50., -50.)
glTexCoord2f(0, 1)
glVertex3f(-50., 50., -50.)
glTexCoord2f(1, 1)
glVertex3f( 50., 50., -50.)
glTexCoord2f(1, 0)
glVertex3f( 50., -50., -50.)
glTexCoord2f(0, 0)
glVertex3f(-50., -50., 50.)
glTexCoord2f(0, 1)
glVertex3f(-50., 50., 50.)
glTexCoord2f(1, 1)
glVertex3f( 50., 50., 50.)
glTexCoord2f(1, 0)
glVertex3f( 50., -50., 50.)
glTexCoord2f(0, 0)
glVertex3f(-50., -50., -50.)
glTexCoord2f(0, 1)
glVertex3f(-50., 50., -50.)
glTexCoord2f(1, 1)
glVertex3f(-50., 50., 50.)
glTexCoord2f(1, 0)
glVertex3f(-50., -50., 50.)
glTexCoord2f(0, 0)
glVertex3f(50., -50., -50.)
glTexCoord2f(0, 1)
glVertex3f(50., 50., -50.)
glTexCoord2f(1, 1)
glVertex3f(50., 50., 50.)
glTexCoord2f(1, 0)
glVertex3f(50., -50., 50.)
glTexCoord2f(0, 1)
glVertex3f(-50., -50., 50.)
glTexCoord2f(0, 0)
glVertex3f(-50., -50., -50.)
glTexCoord2f(1, 0)
glVertex3f( 50., -50., -50.)
glTexCoord2f(1, 1)
glVertex3f( 50., -50., 50.)
glTexCoord2f(0, 1)
glVertex3f(-50., 50., 50.)
glTexCoord2f(0, 0)
glVertex3f(-50., 50., -50.)
glTexCoord2f(1, 0)
glVertex3f( 50., 50., -50.)
glTexCoord2f(1, 1)
glVertex3f( 50., 50., 50.)
glEnd()
# Draw some text on top of our OpenGL object
Text = sf.Text("This is a rotating cube")
Text.SetPosition(230., 300.)
Text.SetColor(sf.Color(128, 0, 128))
App.Draw(Text)
# Finally, display the rendered frame on screen
App.Display()
# Don't forget to destroy our texture
# In C++, the call to this function was a bit different
glDeleteTextures(Texture) # instead of glDeleteTextures(1, &Texture);
return
main()

View file

@ -0,0 +1,43 @@
#!/usr/bin/python
# You can notice that here we use PySFML.sf instead of just PySFML
# Therefore it won't be needed to put sf. in front of SFML classes
from PySFML import sf
def Main():
Buffer = sf.SoundBuffer()
if not Buffer.LoadFromFile("data/fart.wav"): # Loads the sound
return
Fart = sf.Sound(Buffer, False)
WindowWidth, WindowHeight = 640, 480
App = sf.RenderWindow(sf.VideoMode(WindowWidth,WindowHeight,32), "Sound with PySFML", sf.Style.Close, sf.ContextSettings(24,8,0))
App.SetFramerateLimit(30)
EventHandler = sf.Event()
InputHandler = App.GetInput()
Text = sf.Text("Turn the sound on.\nClick anywhere on the screen.\nMove the mouse. Click again.\nTry clicking in the corners.")
Text.SetX(30.)
Text.SetY(20.)
Text.SetColor(sf.Color(150, 100, 10, 255))
while App.IsOpened(): # Main loop
while App.GetEvent(EventHandler): # Event Handler
if EventHandler.Type == sf.Event.Closed:
App.Close()
if EventHandler.Type == sf.Event.KeyPressed and EventHandler.Key.Code == sf.Key.Escape:
App.Close()
if EventHandler.Type == sf.Event.MouseButtonPressed and EventHandler.MouseButton.Button == sf.Mouse.Left:
Fart.SetPitch(1.5 - 1.*InputHandler.GetMouseY()/WindowHeight)
Fart.SetPosition( 1.*(InputHandler.GetMouseX() - WindowWidth/2)/(WindowWidth/20), 2., -2.)
Fart.Play()
App.Draw(Text)
App.Display()
App.Clear(sf.Color.Black)
Main()

View file

@ -0,0 +1,68 @@
#!/usr/bin/env python
from PySFML import sf
def Main():
# Check that the device can capture audio
if sf.SoundRecorder.IsAvailable() == False:
print "Sorry, audio capture is not supported by your system"
return
# Choose the sample rate
SampleRate = 0
SampleRate = int(raw_input("Please choose the sample rate for sound capture (44100 is CD quality) : "))
# Wait for user input...
print "Press enter to start recording audio"
raw_input()
# Here we'll use an integrated custom recorder, which saves the captured data into a sfSoundBuffer
Recorder = sf.SoundBufferRecorder()
# Audio capture is done in a separate thread, so we can block the main thread while it is capturing
Recorder.Start(SampleRate)
print "Recording... press enter to stop"
raw_input()
Recorder.Stop()
# Get the buffer containing the captured data
Buffer = Recorder.GetBuffer()
# Display captured sound informations
print "Sound information :"
print " " + str(Buffer.GetDuration()) + " seconds"
print " " + str(Buffer.GetSampleRate()) + " samples / seconds"
print " " + str(Buffer.GetChannelsCount()) + " channels"
# Choose what to do with the recorded sound data
Choice = str(raw_input("What do you want to do with captured sound (p = play, s = save) ? "))
if Choice == 's':
# Choose the filename
Filename = str(raw_input("Choose the file to create : "))
# Save the buffer
Buffer.SaveToFile(Filename);
else:
# Create a sound instance and play it
Sound = sf.Sound(Buffer)
Sound.Play()
# Wait until finished
while Sound.GetStatus() == sf.Sound.Playing:
# Display the playing position - I don't know how to do this in python
# std::cout << "\rPlaying... " << std::fixed << std::setprecision(2) << Sound.GetPlayingOffset() << " sec";
# Leave some CPU time for other threads
sf.Sleep(0.1)
# Finished !
print "Done !"
# Wait until the user presses 'enter' key
print "Press enter to exit..."
raw_input()
return
Main()

View file

@ -0,0 +1,67 @@
#!/usr/bin/env python
from PySFML import sf
def Main():
# Check that the device can capture audio
if sf.SoundRecorder.CanCapture() == False:
print("Sorry, audio capture is not supported by your system")
return
# Choose the sample rate
SampleRate = int(input("Please choose the sample rate for sound capture (44100 is CD quality) : "))
# Wait for user input...
print("Press enter to start recording audio")
input()
# Here we'll use an integrated custom recorder, which saves the captured data into a sfSoundBuffer
Recorder = sf.SoundBufferRecorder()
# Audio capture is done in a separate thread, so we can block the main thread while it is capturing
Recorder.Start(SampleRate)
print("Recording... press enter to stop")
input()
Recorder.Stop()
# Get the buffer containing the captured data
Buffer = Recorder.GetBuffer()
# Display captured sound informations
print("Sound information :")
print(" " + str(Buffer.GetDuration()) + " seconds")
print(" " + str(Buffer.GetSampleRate()) + " samples / seconds")
print(" " + str(Buffer.GetChannelsCount()) + " channels")
# Choose what to do with the recorded sound data
Choice = str(input("What do you want to do with captured sound (p = play, s = save) ? "))
if Choice == 's':
# Choose the filename
Filename = str(input("Choose the file to create : "))
# Save the buffer
Buffer.SaveToFile(Filename);
else:
# Create a sound instance and play it
Sound = sf.Sound(Buffer)
Sound.Play()
# Wait until finished
while Sound.GetStatus() == sf.Sound.Playing:
# Display the playing position - I don't know how to do this in python
# std::cout << "\rPlaying... " << std::fixed << std::setprecision(2) << Sound.GetPlayingOffset() << " sec";
# Leave some CPU time for other threads
sf.Sleep(0.1)
# Finished !
print("Done !")
# Wait until the user presses 'enter' key
print("Press enter to exit...")
input()
return
Main()

View file

@ -0,0 +1,49 @@
#!/usr/bin/python
from PySFML import sf
class MyCustomStream(sf.SoundStream):
def Open(self, Filename):
# Load the sound data into a sound buffer
self.SoundData = sf.SoundBuffer()
if not self.SoundData.LoadFromFile(Filename):
return False
# Initialize the stream with the sound parameters
self.Initialize(self.SoundData.GetChannelsCount(), self.SoundData.GetSampleRate())
# Copy the audio samples into our internal array
self.myBuffer = self.SoundData.GetSamples()
return True
def OnStart(self):
self.myOffset = 0
self.myBufferSize = 80000
return True
def OnGetData(self):
# Check if there is enough data to stream
if self.myOffset > len(self.myBuffer):
# Returning something else than a string means that we want to stop playing the stream
return ""
# Data contains the string of samples we will return
if self.myOffset + self.myBufferSize >= len(self.myBuffer):
print "End of audio data reached"
Data = self.myBuffer[self.myOffset:]
else:
Data = self.myBuffer[self.myOffset:self.myOffset+self.myBufferSize]
# Update the offset
self.myOffset = self.myBufferSize + self.myOffset
return Data
def Main():
Stream = MyCustomStream()
Stream.Open("./data/fart.wav")
Stream.Play()
print "Playing 5 seconds of audio data..."
sf.Sleep(5)
Stream.Stop()
print "Press enter to exit..."
raw_input()
Main()

View file

@ -0,0 +1,49 @@
#!/usr/bin/python
from PySFML import sf
class MyCustomStream(sf.SoundStream):
def Open(self, Filename):
# Load the sound data into a sound buffer
self.SoundData = sf.SoundBuffer()
if not self.SoundData.LoadFromFile(Filename):
return False
# Initialize the stream with the sound parameters
self.Initialize(self.SoundData.GetChannelsCount(), self.SoundData.GetSampleRate())
# Copy the audio samples into our internal array
self.myBuffer = self.SoundData.GetSamples()
return True
def OnStart(self):
self.myOffset = 0
self.myBufferSize = 80000
return True
def OnGetData(self):
# Check if there is enough data to stream
if self.myOffset > len(self.myBuffer):
# Returning something else than a string means that we want to stop playing the stream
return ""
# Data contains the string of samples we will return
if self.myOffset + self.myBufferSize >= len(self.myBuffer):
print("End of audio data reached")
Data = self.myBuffer[self.myOffset:]
else:
Data = self.myBuffer[self.myOffset:self.myOffset+self.myBufferSize]
# Update the offset
self.myOffset = self.myBufferSize + self.myOffset
return Data
def Main():
Stream = MyCustomStream()
Stream.Open("./data/fart.wav")
Stream.Play()
print("Playing 5 seconds of audio data...")
sf.Sleep(5)
Stream.Stop()
print("Press enter to exit...")
input()
Main()

View file

@ -0,0 +1,272 @@
#!/usr/bin/python
from PySFML import sf
import math
import random
class Menu:
def __init__(self, screen_width, screen_height):
self.selection = 0
text_color = sf.Color(220, 220, 20, 255)
self.spacing = screen_height/7
self.title = sf.Text("PyWorm!")
self.title.SetColor(text_color)
self.title.SetPosition(screen_width/2-80., self.spacing)
levels = ["Very Easy", "Easy", "Medium", "Hard"]
x_align = [-80., -50., -70., -50.]
self.strings = []
for i in range(0, 4):
string = sf.Text(levels[i])
string.SetColor(text_color)
string.SetPosition(screen_width/2+x_align[i], (2+i)*self.spacing+20)
self.strings.append(string)
self.rectangle = sf.Shape.Rectangle(0, 0, screen_width, 40, sf.Color(50, 50, 10))
def next_frame(self, win):
self.rectangle.SetY(self.spacing*(2 + self.selection)+20)
win.Draw(self.rectangle)
win.Draw(self.title)
win.Draw(self.strings)
def key_up(self, pressed):
if pressed:
self.selection = (self.selection - 1) % 4
def key_down(self, pressed):
if pressed:
self.selection = (self.selection + 1) % 4
class Apple(sf.Sprite):
def __init__(self):
apple_img = sf.Image() # Apple's image
if not apple_img.LoadFromFile("./data/apple.png"):
pass
# print "Could not load data/apple.png"
sf.Sprite.__init__(self, apple_img)
self.SetOrigin(apple_img.GetWidth()/2, apple_img.GetHeight()/2)
self.size = apple_img.GetWidth()
def random_move(self, arena):
self.SetPosition( \
random.randrange(arena.arena_left+arena.border, arena.arena_right-arena.border), \
random.randrange(arena.arena_top+arena.border, arena.arena_bottom-arena.border) \
)
class Arena(dict):
shrink_value, border, arena_top = 20, 30, 20
def __init__(self, window_width, window_height):
self.window_width = window_width
self.arena_bottom, self.exit_left, self.exit_right = window_height-80, window_width/2 - 50, window_width/2 + 50
self['level_str'] = sf.Text()
self['level_str'].SetColor(sf.Color.White)
self['level_str'].SetPosition(60., window_height-60)
self['score_str'] = sf.Text()
self['score_str'].SetColor(sf.Color.White)
self['score_str'].SetPosition(260., window_height-60)
self.exit_rect = sf.Shape.Rectangle(self.exit_left, 0, self.exit_right, self.arena_top, sf.Color.Black)
self.reset()
self.update_arena_rect()
def update_arena_rect(self):
self['arena_rect'] = sf.Shape.Rectangle(self.arena_left, self.arena_top, self.arena_right, self.arena_bottom, sf.Color.Black)
def reset(self):
self.level, self.score, self.arena_left, self.arena_right = 1, 0, self.shrink_value, self.window_width-self.shrink_value
self.update_arena_rect()
self['level_str'].SetString("Level: 1")
self['score_str'].SetString("Score: 0")
def update_score(self):
self.score += 1
self['score_str'].SetString("Score: " + str(self.score))
def next_level(self):
self.level += 1
self['level_str'].SetString("Level: " + str(self.level))
self.arena_left += self.shrink_value
self.arena_right -= self.shrink_value
self.update_arena_rect()
self.score += 4
self.update_score()
class Part(sf.Sprite):
def __init__(self, rond, x, y):
sf.Sprite.__init__(self, rond)
self.SetOrigin(rond.GetWidth()/2, rond.GetHeight()/2)
self.SetPosition(x, y)
class Worm(list):
parts_spacing, turn_step, part_size, start_x, start_y, required_length, grow_length = 3, 0.15, 6.0, 50., 50., 300, 20
def __init__(self, difficulty):
self.parts_per_frame = 1 + difficulty
self.angle = 0
self.direction = 0 # 0, 1 or -1 according to the key pressed
self.rond = sf.Image()
self.level_completed = False
if not self.rond.LoadFromFile("./data/rond2.png"):
pass
# print "Could not load data/rond2.png"
def reset(self, arena):
self.targeted_length, self.angle, self.direction = 30, 0, 0
self[:] = [Part(self.rond, arena.arena_left+self.start_x, arena.arena_top+self.start_y)]
def left(self, pressed):
if pressed:
self.direction = -1
elif self.direction == -1:
self.direction = 0
def right(self, pressed):
if pressed:
self.direction = 1
elif self.direction == 1:
self.direction = 0
def restart(self, arena):
if self.targeted_length == 0 and not self.level_completed:
arena.reset()
self.reset(arena)
return True
else:
return False
def crash(self):
self.targeted_length = 0
def move(self, arena, apple):
head_x, head_y = -1, -1
if self.is_running(): # Create new parts and check collisions if the worm hasn't crashed yet
for i in range(self.parts_per_frame): # We create PartsPerFrame Worm's parts
self.angle += self.direction*self.turn_step
head_x, head_y = self[-1].GetPosition()
head_x += self.parts_spacing*math.cos(self.angle)
head_y += self.parts_spacing*math.sin(self.angle)
if self.is_running() and self.targeted_length <= self.required_length: # let's check if the worm ate the apple
if math.hypot(apple.GetPosition()[0] - head_x, apple.GetPosition()[1] - head_y) < apple.size/2 + self.part_size/2: # Yes it did
arena.update_score()
self.targeted_length += self.grow_length # The worm gets longer
apple.random_move(arena)
if head_x<arena.arena_left+self.part_size/2 or head_x>arena.arena_right-self.part_size/2 or head_y<arena.arena_top+self.part_size/2 or head_y>arena.arena_bottom-self.part_size/2: # Crash into a wall
if len(self) > self.required_length:
if head_y<arena.arena_top+self.part_size/2:
if head_x<arena.exit_left+self.part_size/2 or head_x>arena.exit_right-self.part_size/2: # Crash into the exit walls
self.crash()
elif head_y < 0:
self.level_completed = True
self.targeted_length = 0
else:
self.crash()
elif self.is_running():
self.crash()
if self.is_running():
self.append(Part(self.rond, head_x, head_y))
if len(self) > self.targeted_length:
if len(self) - self.targeted_length >= self.parts_per_frame:
del self[0:self.parts_per_frame]
else:
del self[0:len(self) - self.targeted_length]
if (head_x, head_y) == (-1, -1) and len(self) > 0:
head_x, head_y = self[-1].GetPosition()
if len(self) > self.part_size/self.parts_spacing + 1:
for i in range(len(self)):
if i < len(self) - self.part_size/self.parts_spacing - 1:
test_x, test_y = self[i].GetPosition()
if math.hypot(head_x-test_x, head_y-test_y) < self.part_size and self.is_running(): # Check for collision
self.crash()
if len(self) == 0:
if self.level_completed:
self.level_completed = False
arena.next_level()
self.reset(arena)
def is_running(self):
return (self.targeted_length > 0) and not self.level_completed
def draw_exit(self):
return self.targeted_length > self.required_length or self.level_completed
class Game:
def __init__(self, difficulty, window_width, window_height):
self.arena = Arena(window_width, window_height)
self.worm = Worm(difficulty)
self.worm.reset(self.arena)
self.apple = Apple()
self.apple.random_move(self.arena)
self.pause = False
def enter(self, pressed):
if pressed:
if not self.worm.restart(self.arena):
self.pause = not self.pause
def next_frame(self, win):
win.Draw(self.arena.values())
if not self.pause:
self.worm.move(self.arena, self.apple)
if self.worm.draw_exit():
win.Draw(self.arena.exit_rect)
elif self.worm.is_running():
win.Draw(self.apple)
win.Draw(self.worm)
class Main:
# Entry Point
def __init__(self):
# Initialize the window
self.win = sf.RenderWindow(sf.VideoMode(800, 600,32), "PyWorm", sf.Style.Close) # Creates the window
self.win.EnableKeyRepeat(False)
background_color = sf.Color(100, 100, 0, 255)
self.win.SetFramerateLimit(30)
event = sf.Event()
self.keys = {} # keys to watch
self.menu_begin()
# Boucle principale
while self.win.IsOpened():
while self.win.GetEvent(event): # Event Handler
if event.Type == sf.Event.Closed:
self.win.Close()
elif event.Type == sf.Event.KeyPressed or event.Type == sf.Event.KeyReleased:
if event.Key.Code in self.keys:
self.keys[event.Key.Code](event.Type == sf.Event.KeyPressed)
self.win.Display()
self.win.Clear(background_color)
self.next_frame(self.win)
# Menu
def menu_begin(self):
self.menu = Menu(self.win.GetWidth(), self.win.GetHeight())
self.keys = {sf.Key.Escape:self.close_window, sf.Key.Up:self.menu.key_up, sf.Key.Down:self.menu.key_down, sf.Key.Return:self.menu_end}
self.next_frame = self.menu.next_frame
def close_window(self, pressed):
if pressed:
self.win.Close()
def menu_end(self, pressed):
if pressed:
selection = self.menu.selection
del self.menu
self.game_begin(selection)
# Game
def game_begin(self, selection):
self.game = Game(selection, self.win.GetWidth(), self.win.GetHeight())
self.keys = {sf.Key.Left:self.game.worm.left, sf.Key.Right:self.game.worm.right, sf.Key.Return:self.game.enter, sf.Key.Escape:self.game_end}
self.next_frame = self.game.next_frame
def game_end(self, pressed):
if pressed:
del self.game
self.menu_begin()
Main()