def main(): window = sf.RenderWindow(sf.VideoMode(640, 480), 'Title') window.framerate_limit = 60 text = sf.Text(u'éèà', sf.Font.DEFAULT_FONT, 100) text.color = sf.Color.BLACK text.style = sf.Text.UNDERLINED | sf.Text.BOLD | sf.Text.ITALIC text.x = window.width / 2.0 - text.global_bounds.width / 2.0 text.y = window.height / 2.0 - text.global_bounds.height / 2.0 running = True while running: for event in window.iter_events(): if event.type == sf.Event.CLOSED: running = False window.clear(sf.Color.WHITE) window.draw(text) window.display() window.close()
def __init__(self): self.window = sf.RenderWindow(sf.VideoMode(WIDTH, HEIGHT), TITLE, sf.Style.DEFAULT, settings) self.window.framerate_limit = FPS self.clock = sf.Clock() # Top self.ball = sf.CircleShape(30) self.ball.origin = self.ball.radius, self.ball.radius self.ball.position = self.window.size / 2 # Sol Çubuk self.p_left = sf.RectangleShape((50, 200)) x = self.p_left.size.x / 2 y = (HEIGHT - self.p_left.size.y) / 2 self.p_left.position = sf.Vector2(x, y) # Sağ Çubuk self.p_right = sf.RectangleShape((50, 200)) x = WIDTH - (self.p_right.size.x * 1.5) y = (HEIGHT - self.p_right.size.y) / 2 self.p_right.position = sf.Vector2(x, y) x = randint(1, 5) y = randint(1, 5) if randint(0, 1) % 2 == 0: x *= -1.0 if randint(0, 1) % 2 == 0: y *= -1.0 self.ball_vel = sf.Vector2(x, y) self.ball_sound = None # Skor Değişkenleri self.left_score = 0 self.right_score = 0 self.font = None
def run(): """ Read settings from a file, initialize the components and run the game. """ config = cp.ConfigParser() config.read("data/settings.ini") window_width = int(config["window"]["width"]) window_height = int(config["window"]["height"]) flags = sf.Style.DEFAULT fullscreen = du.strtobool(config["window"]["fullscreen"]) if fullscreen: flags |= sf.Style.FULLSCREEN window = sf.RenderWindow(sf.VideoMode(window_width, window_height), "Pymazing", flags) window.vertical_synchronization = du.strtobool(config["window"]["vsync"]) window.mouse_cursor_visible = not du.strtobool( config["window"]["hide_mouse"]) window.key_repeat_enabled = False framebuffer_scale = float(config["window"]["framebuffer_scale"]) framebuffer_width = int(framebuffer_scale * window_width) framebuffer_height = int(framebuffer_scale * window_height) framebuffer_ = framebuffer.FrameBuffer() framebuffer_.resize(framebuffer_width, framebuffer_height) game_state_simple_cube_ = game_state_simple_cube.GameStateSimpleCube( config) game_state_loaded_level_ = game_state_loaded_level.GameStateLoadedLevel( config) game_engine_ = game_engine.GameEngine(window, framebuffer_, config) game_engine_.game_states.append(game_state_simple_cube_) game_engine_.game_states.append(game_state_loaded_level_) #game_engine_.active_game_state = game_state_simple_cube_ game_engine_.active_game_state = game_state_loaded_level_ game_engine_.run()
def main(): window = sf.RenderWindow(sf.VideoMode(640, 480), 'SFML vertices example') window.framerate_limit = 60 running = True vertices = [ sf.Vertex((200, 150), sf.Color.RED), sf.Vertex((200, 350), sf.Color.BLUE), sf.Vertex((400, 350), sf.Color.GREEN), sf.Vertex((400, 150), sf.Color.YELLOW) ] while running: for event in window.iter_events(): if event.type == sf.Event.CLOSED: running = False window.clear(sf.Color.WHITE) window.draw(vertices, sf.TRIANGLES) window.display() window.close()
def __init__(self): # Window self.window = sf.RenderWindow(sf.VideoMode(WWIDTH, WHEIGHT), WTITLE, sf.Style.CLOSE | sf.Style.TITLEBAR, SETTINGS) self.window.framerate_limit = 60 SoundManager.play_background_music() # Clock self.clock = sf.Clock() # View self.view = sf.View(sf.Rectangle((0, 0), (WWIDTH, WHEIGHT))) self.window.view = self.view # Loading assets self.textures = self.load_assets() self.bg = create_sprite(self.textures['bg'], WWIDTH, WHEIGHT, (0, 0)) self.collision_manager = CollisionManager() self.bonus_manager = BonusManager( self.window, { 'life': sf.Texture.from_file("assets/images/red03.png"), 'bullet': sf.Texture.from_file("assets/images/bulletBonus.png"), 'immortality': sf.Texture.from_file("assets/images/heart.png") }, self.collision_manager) self.obstacles = self.create_obstacles() self.bases = self.create_bases() self.player_manager = PlayerManager(self.window.size, DIST_FROM_BASE, self.textures['plane'], self.textures['human'], SPEED) self.obstacles = list(self.create_obstacles()) self.stopped = False self.gameover = create_sprite(self.textures['aliens_win'], self.window.width, self.window.height, (0, 0))
def main(): window = sf.RenderWindow(sf.VideoMode(800, 600), 'SFML Events example') window.framerate_limit = 60 running = True events = EventQueue(50) while running: for event in window.iter_events(): # Stop running if the application is closed # or if the user presses Escape if (event.type == sf.Event.CLOSED or (event.type == sf.Event.KEY_PRESSED and event.code == sf.Keyboard.ESCAPE)): running = False events.add(event) window.clear(sf.Color.WHITE) events.draw(window) window.display() window.close()
# -*- coding: utf-8 -*- import sfml as sf window = sf.RenderWindow(sf.VideoMode(800, 400), "Merhaba") while window.is_open: for event in window.events: if type(event) is sf.CloseEvent: window.close() if type(event) is sf.KeyEvent: if event.released and event.code is sf.Keyboard.ESCAPE: window.close() pos = sf.Mouse.get_position(window) if sf.Keyboard.is_key_pressed(sf.Keyboard.SPACE): print "Space tuşuna basılıyor" if sf.Keyboard.is_key_pressed(sf.Keyboard.M): print("Farenin anlık pozisyonu {0} ".format(pos)) if sf.Keyboard.is_key_pressed(sf.Keyboard.W): print "M ve W birlikte basılıyor" window.clear(sf.Color.BLACK) window.display()
def setUp(self): self.window = sf.RenderWindow(sf.VideoMode(100, 100), "Hack the Planet") self.window.close() self.game_state = draw_main_menu(self.window)
def run(): window = sf.RenderWindow(sf.VideoMode(WWIDTH, WHEIGHT), WTITLE) window.framerate_limit = 60 # Background bg_texture = sf.Texture.from_file("assets/images/background.png") background = sf.Sprite(bg_texture) # Ball b_texture = sf.Texture.from_file("assets/images/ball.png") ball = sf.CircleShape(35) ball.texture = b_texture ball.origin = 35, 35 ball.position = WWIDTH / 2.0, WHEIGHT / 2.0 speed = sf.Vector2(randint(-5, 5), randint(-5, 5)) * 50.0 # Paddle 1 paddle_1 = sf.RectangleShape((50, 175)) paddle_1.origin = 25.0, 82.5 paddle_1.position = 50, WHEIGHT / 2.0 # Paddle 2 paddle_2 = sf.RectangleShape((50, 175)) paddle_2.origin = 25.0, 82.5 paddle_2.position = WWIDTH - 50, WHEIGHT / 2.0 # Scores scored = False p1_score, p2_score = 0, 0 # Font font = sf.Font.from_file("assets/fonts/kenvector.ttf") # Texts p1_score_text = sf.Text(str(p1_score)) p1_score_text.font = font p1_score_text.character_size = 72 p1_score_text.color = sf.Color.WHITE p1_score_text.position = 170, 100 p2_score_text = sf.Text(str(p2_score)) p2_score_text.font = font p2_score_text.character_size = 72 p2_score_text.color = sf.Color.WHITE p2_score_text.position = 570, 100 # Sound s_buffer = sf.SoundBuffer.from_file("assets/sounds/tone1.ogg") sound = sf.Sound(s_buffer) # Clock clock = sf.Clock() while window.is_open: for event in window.events: if type(event) is sf.CloseEvent: window.close() # Close if sf.Keyboard.is_key_pressed(sf.Keyboard.ESCAPE): window.close() elapsed = clock.elapsed_time.seconds clock.restart() # Inputs if sf.Keyboard.is_key_pressed(sf.Keyboard.W): paddle_1.move(sf.Vector2(0, -PADDLE_SPEED)) if paddle_1.position.y < paddle_1.origin.y: paddle_1.position = sf.Vector2(paddle_1.position.x, paddle_1.origin.y) if sf.Keyboard.is_key_pressed(sf.Keyboard.S): paddle_1.move(sf.Vector2(0, PADDLE_SPEED)) if paddle_1.position.y > WHEIGHT - paddle_1.origin.y: paddle_1.position = sf.Vector2(paddle_1.position.x, WHEIGHT - paddle_1.origin.y) if sf.Keyboard.is_key_pressed(sf.Keyboard.UP): paddle_2.move(sf.Vector2(0, -PADDLE_SPEED)) if paddle_2.position.y < paddle_2.origin.y: paddle_2.position = sf.Vector2(paddle_2.position.x, paddle_2.origin.y) if sf.Keyboard.is_key_pressed(sf.Keyboard.DOWN): paddle_2.move(sf.Vector2(0, PADDLE_SPEED)) if paddle_2.position.y > WHEIGHT - paddle_2.origin.y: paddle_2.position = sf.Vector2(paddle_2.position.x, WHEIGHT - paddle_2.origin.y) if scored: speed = sf.Vector2(randint(-5, 5), randint(-5, 5)) * 50.0 ball.position = WWIDTH / 2.0, WHEIGHT / 2.0 paddle_1.position = 50, WHEIGHT / 2.0 paddle_2.position = WWIDTH - 50, WHEIGHT / 2.0 scored = False ball.move(speed * elapsed) if ball.position.x < ball.origin.x or ball.position.x > WWIDTH - ball.origin.x: scored = True if ball.position.x < ball.origin.x: p2_score += 1 else: p1_score += 1 p1_score_text.string = str(p1_score) p2_score_text.string = str(p2_score) if ball.position.y < ball.origin.y or ball.position.y > WHEIGHT - ball.origin.y: speed = sf.Vector2(speed.x, speed.y * -1.0) p1_col = ball.global_bounds.intersects(paddle_1.global_bounds) if p1_col: sound.play() if p1_col.top + p1_col.height / 2.0 > paddle_1.position.y: y = (-1.0, 1.0)[speed.y > 0] else: y = (1.0, -1.0)[speed.y > 0] x_factor = (1.0, 1.05)[-MAX_BALL_SPEED < speed.x < MAX_BALL_SPEED] speed = sf.Vector2(speed.x * -1.0 * x_factor, speed.y * y) p2_col = ball.global_bounds.intersects(paddle_2.global_bounds) if p2_col: sound.play() if p2_col.top + p2_col.height / 2.0 > paddle_2.position.y: y = (-1.0, 1.0)[speed.y > 0] else: y = (1.0, -1.0)[speed.y > 0] x_factor = (1.0, 1.05)[-MAX_BALL_SPEED < speed.x < MAX_BALL_SPEED] speed = sf.Vector2(speed.x * -1.0 * x_factor, speed.y * y) # Rendering window.clear(sf.Color.BLACK) window.draw(background) window.draw(ball) window.draw(paddle_1) window.draw(paddle_2) window.draw(p1_score_text) window.draw(p2_score_text) window.display()
from __future__ import division from math import cos, sin, fabs, pi from random import randint import sfml as sf # define some constants game_size = sf.Vector2(800, 600) paddle_size = sf.Vector2(25, 100) ball_radius = 10. # create the window of the application w, h = game_size window = sf.RenderWindow(sf.VideoMode(w, h), "pySFML - Pong") window.vertical_synchronization = True # load the sounds used in the game ball_sound_buffer = sf.SoundBuffer.from_file("data/ball.wav") ball_sound = sf.Sound(ball_sound_buffer) # create the left paddle left_paddle = sf.RectangleShape() left_paddle.size = paddle_size - (3, 3) left_paddle.outline_thickness = 3 left_paddle.outline_color = sf.Color.BLACK left_paddle.fill_color = sf.Color(100, 100, 200) left_paddle.origin = paddle_size / 2 # create the right paddle right_paddle = sf.RectangleShape()
start_time = 0 # Starting global time t = 0 # Time since start_time dt = 0.01 # Time increment (in seconds) when using fake_time next_time1 = 0 # Time of next θ₁ step next_time2 = 0 # Time of next θ₂ step x_list = [] # History of all t,x points for graphing y_list = [] th1_list = [] th2_list = [] ideal_x_list = [] # Ideal curves, for comparison with actual path ideal_y_list = [] ideal_th1_list = [] ideal_th2_list = [] # Initialize Graphics window = sf.RenderWindow(sf.VideoMode(window_width, window_height), "SpinSim") time.sleep(0.1) # Window doesn't draw right without a short delay # Set background window.clear(sf.Color.BLACK) window.display() # Draw platter outline circle = sf.CircleShape() circle.radius = radius * window_scale circle.outline_color = sf.Color.WHITE circle.outline_thickness = 1 circle.position = (0, 0) circle.fill_color = sf.Color.BLACK window.draw(circle) window.display() # Initialize Graphing
import sfml import random import time import math # Initialize the window window = sfml.RenderWindow(sfml.VideoMode.get_desktop_mode(), 'Rainbow Fire', sfml.window.Style.FULLSCREEN) visible_area = sfml.Rectangle(sfml.Vector2(0, 0), window.size) # Seed random random.seed(time.time()) # Load textures rainbow_dash_tx = sfml.Texture.from_file('rainbow_dash.png') evil_pony_tx = sfml.Texture.from_file('evil_pony.png') blast_tx = sfml.Texture.from_file('blast.png') bullet_tx = sfml.Texture.from_file('bullet.png') # Load sounds blast_sound = sfml.Sound(sfml.SoundBuffer.from_file('blast.wav')) shot_sound = sfml.Sound(sfml.SoundBuffer.from_file('shot.wav')) smash_sound = sfml.Sound(sfml.SoundBuffer.from_file('smash.wav')) # Load font bangers_ft = sfml.Font.from_file('Bangers.ttf') # Score score = 0 score_text = sfml.Text('Score: ' + str(score), bangers_ft, 60) score_text.position = (window.size.x - score_text.global_bounds.width - 20, 10)
def main(): window = sf.RenderWindow( sf.VideoMode(GameManager.window_width, GameManager.window_height), "Connect 4") menu = MainMenu(window) menu.open()
target.draw(self.logo) target.draw(self.princess) class LowLevelDrawable(object): def draw(self, target, states): vertices = [ sf.Vertex((200, 150), sf.Color.BLACK), sf.Vertex((400, 150), sf.Color.RED), sf.Vertex((400, 350), sf.Color.BLUE), sf.Vertex((200, 350), sf.Color.MAGENTA) ] target.draw(vertices, sf.TRIANGLES_FAN) window = sf.RenderWindow(sf.VideoMode(640, 480), 'User defined drawable') window.framerate_limit = 60 running = True drawable = Drawable() low_level_drawable = LowLevelDrawable() while running: for event in window.iter_events(): if event.type == sf.Event.CLOSED: running = False window.clear(sf.Color.WHITE) window.draw(drawable) window.draw(low_level_drawable) window.display()
class Window: hasFocus=False window = sf.RenderWindow(sf.VideoMode(800, 600), "pySFML - OpenGL", sf.Style.DEFAULT, sf.ContextSettings(32)) window.vertical_synchronization = True window.framerate_limit=15 window.mouse_cursor_visible= False sf.Mouse.set_position(window.size/2, window) window.active = True size= window.size @staticmethod def getMousePos(): return sf.Mouse.get_position(Window.window) @staticmethod def setMousePos(p): sf.Mouse.set_position(p, Window.window) @staticmethod def isOpen(): for event in Window.window.events: if event == sf.CloseEvent: Window.window.close() if event == sf.ResizeEvent: Window.size= event.size glViewport(0, 0, event.width, event.height ) if event == sf.FocusEvent: Window.hasFocus= event.gained # in theory, anyway if True or Window.hasFocus: if event == sf.KeyEvent and event.code == sf.Keyboard.ESCAPE: Window.window.close() return Window.window.is_open @staticmethod def display(): Window.window.display() clock=sf.Clock() @staticmethod def Input(lookCurve=1.4): t=Window.clock.restart().seconds """ The actual camera setting cycle """ wc= Window.size/2 mouse_dx,mouse_dy = (Window.getMousePos()-wc)*t #mouse_dx= copysign(abs(mouse_dx)**lookCurve,mouse_dx) #mouse_dy= copysign(abs(mouse_dy)**lookCurve,mouse_dy) Window.setMousePos(wc) buffer = glGetDoublev(GL_MODELVIEW_MATRIX) c = (-1 * numpy.mat(buffer[:3,:3]) * numpy.mat(buffer[3,:3]).T).reshape(3,1) # c is camera center in absolute coordinates, # we need to move it back to (0,0,0) # before rotating the camera glTranslate(c[0],c[1],c[2]) m = buffer.flatten() glRotate( -mouse_dx, m[1],m[5],m[9]) glRotate( -mouse_dy, m[0],m[4],m[8]) # compensate roll glRotated(-atan2(-m[4],m[5]) * 57.295779513082320876798154814105 ,m[2],m[6],m[10]) glTranslate(-c[0],-c[1],-c[2]) t*=10.0 kb,k = sf.Keyboard.is_key_pressed,sf.Keyboard x= t if kb(k.A) else -t if kb(k.D) else .0 z= t if kb(k.W) else -t if kb(k.S) else .0 y= t if kb(k.L_SHIFT) else -t if kb(k.SPACE) else .0 if z or x or y: #m = glGetDoublev(GL_MODELVIEW_MATRIX).flatten() glTranslate(z*m[2],z*m[6],z*m[10]) glTranslate(x*m[0],x*m[4],x*m[8]) glTranslate(y*m[1],y*m[5],y*m[9])
#constants game_size = sf.Vector2(800,600) #colors black = sf.Color.BLACK white = sf.Color.WHITE red = sf.Color.RED blue = sf.Color.BLUE green = sf.Color.GREEN yellow = sf.Color.YELLOW #setup window w,h = game_size window = sf.RenderWindow(sf.VideoMode(w,h),"Start Window") #load Font|check font filepath os.chdir("C:\Users\Kyle\Documents\LiClipse Workspace") font = sf.Font.from_file("arial.ttf") if os.path.exists("arial.ttf") == True: print "found font file path" else: print "could not find font file path" def get_mouse_pos(): mousepos = sf.window.Mouse.get_position() return mousepos def mouse_clicked(): if sf.Mouse.is_button_pressed(sf.Mouse.LEFT) == True:
def main(): window = sf.RenderWindow(sf.VideoMode(800, 600), "PySFML Animation") window.framerate_limit = 60 texture = sf.Texture.from_file("assets/images/player.png") walking_down = Animation() walking_down.texture = texture walking_down.add_frame(sf.Rectangle((32, 0), (32, 32))) walking_down.add_frame(sf.Rectangle((64, 0), (32, 32))) walking_down.add_frame(sf.Rectangle((32, 0), (32, 32))) walking_down.add_frame(sf.Rectangle((0, 0), (32, 32))) walking_up = Animation() walking_up.texture = texture walking_up.add_frame(sf.Rectangle((32, 96), (32, 32))) walking_up.add_frame(sf.Rectangle((64, 96), (32, 32))) walking_up.add_frame(sf.Rectangle((32, 96), (32, 32))) walking_up.add_frame(sf.Rectangle((0, 96), (32, 32))) walking_left = Animation() walking_left.texture = texture walking_left.add_frame(sf.Rectangle((32, 32), (32, 32))) walking_left.add_frame(sf.Rectangle((64, 32), (32, 32))) walking_left.add_frame(sf.Rectangle((32, 32), (32, 32))) walking_left.add_frame(sf.Rectangle((0, 32), (32, 32))) walking_right = Animation() walking_right.texture = texture walking_right.add_frame(sf.Rectangle((32, 64), (32, 32))) walking_right.add_frame(sf.Rectangle((64, 64), (32, 32))) walking_right.add_frame(sf.Rectangle((32, 64), (32, 32))) walking_right.add_frame(sf.Rectangle((0, 64), (32, 32))) current_anim = walking_down anim_sprite = AnimatedSprite(sf.seconds(0.2), True, False) anim_sprite.position = sf.Vector2(400, 300) frame_clock = sf.Clock() speed = 80.0 no_key_pressed = True while window.is_open: for event in window.events: if type(event) is sf.CloseEvent: window.close() delta = frame_clock.elapsed_time frame_clock.restart() movement = sf.Vector2(0.0, 0.0) if sf.Keyboard.is_key_pressed(sf.Keyboard.DOWN): current_anim = walking_down movement += sf.Vector2(0.0, speed) no_key_pressed = False if sf.Keyboard.is_key_pressed(sf.Keyboard.UP): current_anim = walking_up movement += sf.Vector2(0.0, -speed) no_key_pressed = False if sf.Keyboard.is_key_pressed(sf.Keyboard.LEFT): current_anim = walking_left movement += sf.Vector2(-speed, 0.0) no_key_pressed = False if sf.Keyboard.is_key_pressed(sf.Keyboard.RIGHT): current_anim = walking_right movement += sf.Vector2(speed, 0.0) no_key_pressed = False anim_sprite.play(current_anim) anim_sprite.move(movement * delta.seconds) if no_key_pressed: anim_sprite.stop() no_key_pressed = True anim_sprite.update(delta) window.clear() window.draw(anim_sprite) window.display()
def __init__(self): self.window = sf.RenderWindow(sf.VideoMode(WIDTH, HEIGHT), TITLE) self.circle = sf.CircleShape(50) self.circle.origin = self.circle.radius, self.circle.radius
def main(): # Create the window of the application window = sf.RenderWindow(sf.VideoMode(800, 600, 32), 'PySFML Pong'); # Load the sounds used in the game ball_sound_buffer = sf.SoundBuffer.load_from_file("resources/ball.wav") ball_sound = sf.Sound(ball_sound_buffer); # Load the textures used in the game background_texture = sf.Texture.load_from_file('resources/background.jpg') left_paddle_texture = sf.Texture.load_from_file('resources/paddle_left.png') right_paddle_texture = sf.Texture.load_from_file( 'resources/paddle_right.png') ball_texture = sf.Texture.load_from_file('resources/ball.png') # Load the text font font = sf.Font.load_from_file('resources/sansation.ttf') # Initialize the end text end = sf.Text() end.font = font end.character_size = 60 end.move(150, 200); end.color = sf.Color(50, 50, 250) # Create the sprites of the background, the paddles and the ball background = sf.Sprite(background_texture) left_paddle = sf.Sprite(left_paddle_texture) right_paddle = sf.Sprite(right_paddle_texture) ball = sf.Sprite(ball_texture) left_paddle.move( 10, (window.view.size[1] - left_paddle.global_bounds.height) / 2) right_paddle.move( window.view.size[0] - right_paddle.global_bounds.width - 10, (window.view.size[1] - right_paddle.global_bounds.height) / 2) ball.move((window.view.size[0] - ball.global_bounds.width) / 2, (window.view.size[1] - ball.global_bounds.height) / 2) # Define the paddles properties ai_timer = sf.Clock() ai_time = sf.Time(milliseconds=100) left_paddle_speed = 0.4 right_paddle_speed = 0.4 # Define the ball properties ball_speed = 0.4 ball_angle = 0.0 clock = sf.Clock() while True: # Make sure the ball initial angle is not too much vertical ball_angle = random.uniform(0.0, 2 * math.pi) if abs(math.cos(ball_angle)) < 0.7: break is_playing = True while window.open: # Handle events for event in window.iter_events(): # Window closed or escape key pressed : exit if ((event.type == sf.Event.CLOSED) or (event.type == sf.Event.KEY_PRESSED and event.code == sf.Keyboard.ESCAPE)): window.close() break frame_time = clock.restart().as_milliseconds() if is_playing: # Move the player's paddle if (sf.Keyboard.is_key_pressed(sf.Keyboard.UP) and left_paddle.y > 5.0): left_paddle.move(0.0, -left_paddle_speed * frame_time) if (sf.Keyboard.is_key_pressed(sf.Keyboard.DOWN) and (left_paddle.y < window.view.size[1] - left_paddle.global_bounds.height - 5.0)): left_paddle.move(0.0, left_paddle_speed * frame_time) # Move the computer's paddle if (((right_paddle_speed < 0.0) and (right_paddle.y > 5.0)) or ((right_paddle_speed > 0.0) and (right_paddle.y < window.view.size[1] - right_paddle.global_bounds.height - 5.0))): right_paddle.move(0.0, right_paddle_speed * frame_time) # Update the computer's paddle direction according # to the ball position if ai_timer.elapsed_time > ai_time: ai_timer.restart() if (right_paddle_speed < 0 and (ball.y + ball.global_bounds.height > right_paddle.y + right_paddle.global_bounds.height)): right_paddle_speed = -right_paddle_speed if right_paddle_speed > 0 and ball.y < right_paddle.y: right_paddle_speed = -right_paddle_speed; # Move the ball factor = ball_speed * frame_time ball.move(math.cos(ball_angle) * factor, math.sin(ball_angle) * factor) # Check collisions between the ball and the screen if ball.x < 0.0: is_playing = False end.string = "You lost !\n(press escape to exit)" if ball.x + ball.global_bounds.width > window.view.size[0]: is_playing = False end.string = "You won !\n(press escape to exit)" if ball.y < 0.0: ball_sound.play(); ball_angle = -ball_angle ball.y = 0.1 if ball.y + ball.global_bounds.height > window.view.size[1]: ball_sound.play() ball_angle = -ball_angle ball.y = window.view.size[1] - ball.global_bounds.height - 0.1 # Check the collisions between the ball and the paddles # Left Paddle if (ball.x < left_paddle.x + left_paddle.global_bounds.width and ball.x > left_paddle.x + (left_paddle.global_bounds.width / 2.0) and ball.y + ball.global_bounds.height >= left_paddle.y and ball.y <= left_paddle.y + left_paddle.global_bounds.height): ball_sound.play() ball_angle = math.pi - ball_angle ball.x = left_paddle.x + left_paddle.global_bounds.width + 0.1 # Right Paddle if (ball.x + ball.global_bounds.width > right_paddle.x and ball.x + ball.global_bounds.width < right_paddle.x + (right_paddle.global_bounds.width / 2.0) and ball.y + ball.global_bounds.height >= right_paddle.y and ball.y <= right_paddle.y + right_paddle.global_bounds.height): # ball_sound.play(); ball_angle = math.pi - ball_angle ball.x = right_paddle.x - ball.global_bounds.width - 0.1 # Clear the window window.clear() # Draw the background, paddles and ball sprites window.draw(background) window.draw(left_paddle) window.draw(right_paddle) window.draw(ball) # If the game is over, display the end message if not is_playing: window.draw(end) # Display things on screen window.display()
#START OF PROGRAM globalTime = 0 winner = None extinct = False array = np.zeros((50,50)) foodList = [] antList = [] window = sf.RenderWindow(sf.VideoMode(500, 500), "anthill") window.view = sf.View(sf.Rectangle((0, 0), (500, -500))) window.view.center = (250, 250) running = True arraysize = int(array.size ** 0.5) shape = sf.RectangleShape((10, 10)) startup() show = input("Display? ")
from __future__ import division from math import cos, sin, fabs, pi from random import randint import sfml as sf import time # define some constants game_size = sf.Vector2(800, 900) tank_size = sf.Vector2(100, 25) # create the window of the application w, h = game_size window = sf.RenderWindow(sf.VideoMode(w, h), "Blizzard Blaster") window.vertical_synchronization = True # load the sounds used in the game dray_sound_buffer = sf.SoundBuffer.from_file("data/laser.wav") dray_sound = sf.Sound(dray_sound_buffer) rampage_sound_buffer = sf.SoundBuffer.from_file("data/rampage.wav") rampage_sound = sf.Sound(rampage_sound_buffer) unstoppable_sound_buffer = sf.SoundBuffer.from_file("data/unstoppable.wav") unstoppable_sound = sf.Sound(unstoppable_sound_buffer) whicked_sick_sound_buffer = sf.SoundBuffer.from_file("data/whickedsick.wav") whicked_sick_sound = sf.Sound(whicked_sick_sound_buffer) play_sound_buffer = sf.SoundBuffer.from_file("data/prepare4.wav")
import sfml as sf from MoveBlocker import MoveBlocker from PathfinderPlayer import PathfinderPlayer game_size = sf.Vector2(800, 600) # define game window w, h = game_size window = sf.RenderWindow(sf.VideoMode(w, h), "sight test") window.vertical_synchronization = True sb1 = MoveBlocker((200, 100)) sb1.set_position((400, 300)) sb2 = MoveBlocker((100, 100)) sb2.set_position((150, 250)) sb_list = [sb1, sb2] pp = PathfinderPlayer(100, 100) while window.is_open: # handle events for event in window.events: # window closed or escape key pressed: exit if type(event) is sf.CloseEvent: window.close() if sf.Keyboard.is_key_pressed(sf.Keyboard.ESCAPE): window.close() window.clear(sf.Color(50, 200, 50)) pp.update(sb_list, sf.Mouse.get_position(window))
self.set_position(X[0, 0], self.render_y) self.set_velocity(X[1, 0], 0.0) self.set_rotation(X[2, 0]) def set_rotation(self, theta): self.theta.value = theta for body in self.renderables[1:]: body.rotation = -self._rad_to_degree(theta) + 90 if __name__ == '__main__': window_x = 800 window_y = 800 window = sf.RenderWindow(sf.VideoMode(window_x, window_y), "PySFML test") window.position = sf.Vector2(10, 50) window.title = 'MPC window' window.framerate_limit = 60 g = SpringDamper(window) print g.state a = Param('a', 2.0) b = Param('b', 1.0) print a, b print 'A - B : ', a - b print 'A * B : ', a * b print 'B * A : ', b * a print 'A / B : ', a / b print 'B / A : ', b / a
import sfml as sf import numpy as np from bodies import SpringDamper, Pendulum, CartPole from mpc import MPC # Create the main window settings = sf.ContextSettings() settings.antialiasing_level = 8 # doesn't seem to do anything window_x = 800 window_y = 800 window = sf.RenderWindow(sf.VideoMode(window_x, window_y), "PySFML test", sf.Style.DEFAULT, settings) window.position = sf.Vector2(10, 50) window.title = 'MPC window' window.framerate_limit = 60 def add_time(window, time): text = "Time : %.2f" % time sf_text = sf.Text(text) sf_text.color = sf.Color.BLACK window.draw(sf_text) class System(object): def __init__(self, window, dt=0.01): self.use_mpc = True self.clock = sf.Clock() self.window = window self.dt = dt
# python 2.7 import sfml as sf from cellmap import Cellmap paused = False # scalar for cell size, bigger means smaller cells m = 1 # 1, 2, 4, 8 or 16 (2 or more is very slow) CS = 16 / m # cell size GW = 80 * m # grid width GH = 50 * m # grid height cm = Cellmap(GW, GH, CS) window = sf.RenderWindow(sf.VideoMode(GW * CS, GH * CS), "Game of Life (pySFML)") while window.is_open: for event in window.events: if type(event) is sf.CloseEvent or type(event) is sf.KeyEvent \ and (event.code in (sf.Keyboard.ESCAPE, sf.Keyboard.Q)): window.close() if type(event) is sf.KeyEvent: if event.pressed: if event.code is sf.Keyboard.SPACE: paused = not paused window.clear() if not paused: cm.pass_generation()
def main(): if not sf.Shader.IS_AVAILABLE: display_error() # Create the main window window = sf.RenderWindow(sf.VideoMode(800, 600), 'SFML shader example') clock = sf.Clock() # Create the render texture texture = sf.RenderTexture(window.width, window.height) # Load a background texture to display background_texture = sf.Texture.load_from_file('resources/background.jpg') background = sf.Sprite(background_texture) # Load a sprite which we'll move into the scene entity_texture = sf.Texture.load_from_file('resources/sprite.png') entity = sf.Sprite(entity_texture) # Load the text font font = sf.Font.load_from_file('resources/sansation.ttf') # Load the texture needed for the wave shader wave_texture = sf.Texture.load_from_file('resources/wave.jpg') # Load all shaders shaders = [None] * 7 shaders[NOTHING] = sf.Shader.load_from_file('resources/nothing.sfx', sf.Shader.FRAGMENT) shaders[BLUR] = sf.Shader.load_from_file('resources/blur.sfx', sf.Shader.FRAGMENT) shaders[COLORIZE] = sf.Shader.load_from_file('resources/colorize.sfx', sf.Shader.FRAGMENT) shaders[EDGE] = sf.Shader.load_from_file('resources/edge.sfx', sf.Shader.FRAGMENT) shaders[FISHEYE] = sf.Shader.load_from_file('resources/fisheye.sfx', sf.Shader.FRAGMENT) shaders[WAVE] = sf.Shader.load_from_file('resources/wave.sfx', sf.Shader.FRAGMENT) shaders[PIXELATE] = sf.Shader.load_from_file('resources/pixelate.sfx', sf.Shader.FRAGMENT) background_shader = ShaderSelector(shaders) entity_shader = ShaderSelector(shaders) global_shader = ShaderSelector(shaders) # Do specific initializations shaders[NOTHING].set_parameter('texture', sf.Shader.CURRENT_TEXTURE) shaders[BLUR].set_parameter('texture', sf.Shader.CURRENT_TEXTURE) shaders[BLUR].set_parameter('offset', 0.0) shaders[COLORIZE].set_parameter('texture', sf.Shader.CURRENT_TEXTURE) shaders[COLORIZE].set_parameter('color', 1.0, 1.0, 1.0) shaders[EDGE].set_parameter('texture', sf.Shader.CURRENT_TEXTURE) shaders[FISHEYE].set_parameter('texture', sf.Shader.CURRENT_TEXTURE) shaders[WAVE].set_parameter('texture', sf.Shader.CURRENT_TEXTURE) shaders[WAVE].set_parameter('wave', wave_texture) shaders[PIXELATE].set_parameter('texture', sf.Shader.CURRENT_TEXTURE) # Define a string for displaying the description of the current shader shader_str = sf.Text() shader_str.font = font shader_str.character_size = 20 shader_str.position = (5.0, 0.0) shader_str.color = sf.Color(250, 100, 30) shader_str.string = ("Background shader: \"{0}\"\n" "Flower shader: \"{1}\"\n" "Global shader: \"{2}\"\n".format( background_shader.get_name(), entity_shader.get_name(), global_shader.get_name())) # Define a string for displaying help info_str = sf.Text() info_str.font = font info_str.character_size = 20 info_str.position = (5.0, 500.0) info_str.color = sf.Color(250, 100, 30) info_str.string = ("Move your mouse to change the shaders' parameters\n" "Press numpad 1/4 to change the background shader\n" "Press numpad 2/5 to change the flower shader\n" "Press numpad 3/6 to change the global shader") # Create a clock to measure the total time elapsed clock = sf.Clock() # Start the game loop while window.open: # Process events for event in window.iter_events(): # Close window : exit if event.type == sf.Event.CLOSED: window.close() if event.type == sf.Event.KEY_PRESSED: # Escape key : exit if event.code == sf.Keyboard.ESCAPE: window.close() # Numpad : switch effect if event.code == sf.Keyboard.NUMPAD1: background_shader.go_to_previous() elif event.code == sf.Keyboard.NUMPAD4: background_shader.go_to_next() elif event.code == sf.Keyboard.NUMPAD2: entity_shader.go_to_previous() elif event.code == sf.Keyboard.NUMPAD5: entity_shader.go_to_next() elif event.code == sf.Keyboard.NUMPAD3: global_shader.go_to_previous() elif event.code == sf.Keyboard.NUMPAD6: global_shader.go_to_next() # Update the text shader_str.string = ("Background shader: \"{0}\"\n" "Entity shader: \"{1}\"\n" "Global shader: \"{2}\"\n".format( background_shader.get_name(), entity_shader.get_name(), global_shader.get_name())) frame_time = clock.restart().as_milliseconds() # Get the mouse position in the range [0, 1] if window.width and window.height: mouse_x = sf.Mouse.get_position(window)[0] / float(window.width) mouse_y = sf.Mouse.get_position(window)[1] / float(window.height) # Update the shaders background_shader.update(mouse_x, mouse_y) entity_shader.update(mouse_x, mouse_y) global_shader.update(mouse_x, mouse_y) # Animate the entity entity_x = ( (math.cos(clock.elapsed_time.as_milliseconds() * 0.0013) + 1.2) * 300) entity_y = ( (math.cos(clock.elapsed_time.as_milliseconds() * 0.0008) + 1.2) * 200) entity.position = (entity_x, entity_y) entity.rotate(frame_time * 0.1) # Draw the background and the moving entity to the render texture texture.clear() texture.draw(background, background_shader.get_shader()) texture.draw(entity, entity_shader.get_shader()) texture.display() # Draw the contents of the render texture to the window screen = sf.Sprite(texture.texture) window.draw(screen, global_shader.get_shader()) # Draw the interface texts window.draw(shader_str) window.draw(info_str) # Finally, display the rendered frame on screen window.display()
def handle_key_event(rectangle): if sf.Keyboard.is_key_pressed(sf.Keyboard.LEFT): return (rectangle.position.x - global_speed, rectangle.position.y) if sf.Keyboard.is_key_pressed(sf.Keyboard.RIGHT): return (rectangle.position.x + global_speed, rectangle.position.y) if sf.Keyboard.is_key_pressed(sf.Keyboard.DOWN): return (rectangle.position.x, rectangle.position.y + global_speed) if sf.Keyboard.is_key_pressed(sf.Keyboard.UP): return (rectangle.position.x, rectangle.position.y - global_speed) return (rectangle.position.x, rectangle.position.y) # create the main window window = sf.RenderWindow(sf.VideoMode(800, 600), "pySFML Window") # play the music # music.play() font = sf.Font.from_file("abc.ttf") p1 = Player(init_rectangle((100, 50), (10, 20), sf.Color.RED), 0, 'Hans') button1 = Button(init_rectangle((200, 100), (300, 20), sf.Color.GREEN), 'function not implemented yet', 'Test 1') button2 = Button(init_rectangle((200, 100), (300, 220), sf.Color.GREEN), 'function not implemented yet', 'Test 2') button3 = Button(init_rectangle((200, 100), (300, 420), sf.Color.GREEN), 'function not implemented yet', 'Test 3') text = sf.Text("0") text.font = font text.character_size = 20 text.style = sf.Text.BOLD
# -*- coding: utf-8 -*- import sfml as sf import pymunk # Chipmunk C/C++ # Box2D import sys window = sf.RenderWindow(sf.VideoMode(640, 480), "SFML Pymunk") window.framerate_limit = 60 rad = 14 ball_elasticity = 0.8 friction = 0.8 space = pymunk.Space() space.gravity = (0.0, -900.0) circles = [] def create_circle(position): mass = 1 inertia = pymunk.moment_for_circle(mass, 0, rad) body = pymunk.Body(mass, inertia) body.position = position # body.position = position shape = pymunk.Circle(body, rad) shape.elasticity = ball_elasticity shape.friction = friction space.add(body, shape) return shape
# -*- coding:utf-8 -*- import sfml as sf WIDTH = 800 HEIGHT = 480 TITLE = "Cindiii" window = sf.RenderWindow(sf.VideoMode(WIDTH, HEIGHT), TITLE) alpha = 255 circle = sf.CircleShape(50) circle.origin = circle.radius, circle.radius circle.fill_color = sf.Color(18, 74, 34, alpha) rectangle = sf.RectangleShape((50, 50)) rectangle.fill_color = sf.Color.BLUE rectangle.origin = rectangle.size.x / 2, rectangle.size.y / 2 rectangle.position = 200, 200 while window.is_open: for event in window.events: if type(event) is sf.CloseEvent: window.close() if type(event) is sf.MouseWheelEvent: alpha += event.delta if not 0 <= alpha <= 255: print "Al kırdın kırdııın!" alpha = 0 circle.fill_color = sf.Color(18, 74, 34, alpha) if type(event) is sf.KeyEvent: if event.released and event.code is sf.Keyboard.ESCAPE: window.close() circle.position = sf.Mouse.get_position(window)
# -*- coding: utf-8 -*- import sfml as sf import sys WIDTH = 800 HEIGHT = 480 TITLE = "AB2015 Python Oyun - Tappy Plane" GRAVITY = sf.Vector2(0, 0.1) video_mode = sf.VideoMode(WIDTH, HEIGHT) window = sf.RenderWindow(video_mode, TITLE) try: bg_texture = sf.Texture.from_file('assets/images/background.png') plane_texture = sf.Texture.from_file('assets/images/planeRed1.png') s_buffer = sf.SoundBuffer.from_file('assets/sounds/tone1.ogg') music = sf.Music.from_file('assets/sounds/spaceTrash3.ogg') font = sf.Font.from_file('assets/fonts/kenvector_future_thin.ttf') except IOError: print("HATA VERDİ!!") sys.exit(-1) background = sf.Sprite(bg_texture) plane = sf.Sprite(plane_texture) plane.position = 100, 100 plane_vel = sf.Vector2(0.0, 0.0) sound = sf.Sound(s_buffer)