def main(): random.seed(datetime.datetime.now()) window = sf.RenderWindow(sf.VideoMode(WIDTH, HEIGHT), "A Walk In The Dark") sound.ambient.loop = True sound.ambient.volume = 10 sound.ambient.play() state_counter = 0 current_state = IntroState(window) last_state = None step_timer = sf.Clock() while window.is_open: dt = step_timer.elapsed_time.milliseconds / 16.0 step_timer.restart() current_state.step(dt) window.clear() current_state.draw() window.display() if current_state.has_ended: old_current_state = current_state if current_state.next_state is None: window.close() elif current_state.next_state == State.PREVIOUS_STATE: print("restoring previous state") current_state = last_state else: current_state = current_state.next_state(window) last_state = old_current_state last_state.has_ended = False
def run(self): clock = sf.Clock() time_since_last_update = sf.seconds(0) for i in range(settings.INITIAL_ENTITIES): self.entities.append(Entity(sf.Vector2( random.randrange(width), random.randrange(height)))) while self.window.is_open: dt = clock.restart() time_since_last_update += dt while time_since_last_update > time_per_update: time_since_last_update -= time_per_update t = clock.elapsed_time self.update(time_per_update) t = clock.elapsed_time - t self.statistics.t_update.append(t.microseconds) self.process_events() self.statistics.update_texts(dt) t = clock.elapsed_time self.render() self.statistics.num_frames += 1 t = clock.elapsed_time - t self.statistics.t_render.append(t.microseconds)
def __init__(self): self.window = sf.RenderWindow(sf.VideoMode(WIDHT, HEIGHT), TITLE, sf.Style.DEFAULT, settings) self.window.framerate_limit = FPS self.clock = sf.Clock() self.ball = sf.CircleShape(30) self.ball.origin = self.ball.radius, self.ball.radius self.ball.position = self.window.size / 2 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 #sol çubuk self.p_left = sf.RectangleShape((30, 200)) x = self.p_left.size.x / 2 y = (HEIGHT - self.p_left.size.y) / 2 self.p_left.position = sf.Vector2(x, y) self.left_score = 0 #sağ çubuk self.p_right = sf.RectangleShape((30, 200)) x = WIDHT - (self.p_right.size.x * 1.5) y = (HEIGHT - self.p_left.size.y) / 2 self.p_right.position = sf.Vector2(x, y) self.right_score = 0 self.font = None
def __init__(self, window, dt=0.01): self.use_mpc = True self.clock = sf.Clock() self.window = window self.dt = dt self.time = 0 self.mpc_horizon = 10 self.counter = -1 spring_damper = SpringDamper(window, pos_x=0.9, pos_y=0.5) spring_damper.set_properties(k=10., m=1., c=0.1, x0=0.5) spring_damper.integration_type = spring_damper.RUNGE_KUTTA pendulum = Pendulum(window) pendulum.set_properties(m=1.0, g=-9.8, L=0.25, k=0.1) pendulum.set_position(0.5, 0.5) pendulum.set_rotation(np.pi * 0.95) pendulum.integration_type = pendulum.RUNGE_KUTTA pendulum.nonlinear_mode = True cart = CartPole(window) cart.set_properties(m=0.2, M=0.5, I=0.006, g=-9.8, l=0.25, b=0.5) cart.set_position(0.5, 0.5) cart.set_rotation(np.pi * 0.99) cart.nonlinear_mode = True cart.integration_type = cart.RUNGE_KUTTA self.mpc = MPC(dt, self.mpc_horizon) # This works for springdamper and pendulum R = np.matrix(np.eye(2) * 1e-5) Q = np.matrix(np.matrix([[100, 0], [0.0, 1.0]])) T = np.matrix(np.eye(2) * 1e-5) self.mpc.set_cost_weights(Q, R, T) self.mpc.Y_prime = np.matrix(np.zeros(shape=(2, self.mpc_horizon))) self.mpc.Y_prime[0, :] = 0.7 self.mpc.C = np.matrix(np.eye(2)) # cartpole # R = np.matrix(np.eye(4)*0.001) # Q = np.matrix([[100, 0, 0, 0], # [0, 0, 0, 0], # [0, 0, 100, 0], # [0, 0, 0, 0]]) # # self.mpc.set_cost_weights(Q, R) # self.mpc.set_constraints(cart.cons) # # self.mpc.Y_prime = np.matrix(np.zeros(shape=(4, self.mpc_horizon))) # self.mpc.Y_prime[0,:] = np.pi # self.mpc.Y_prime[2,:] = 0.5 # self.C = np.matrix([[1,0, 1, 0]]) # self.bodies = [spring_damper, pendulum] self.bodies = [spring_damper] self.mpc.set_body(self.bodies[0])
def __init__(self): sf.RenderWindow.__init__(self, sf.VideoMode(*SCREEN_SIZE), CAPTION) ## self.vertical_synchronization = True self.framerate_limit = 60 self.active = True self.clock = sf.Clock() self.player = Player(SCREEN_SIZE / 2, 100, 300) self.done = False
def jump(self): if self.is_dead: self.is_dead = False SoundManager.play_player_appear_sound() if not self.plane_jumped: self.plane_jumped = True self.jump_time = sf.Clock()
def __init__(self, window): State.__init__(self, window) #self.debug = [] self.busses = [] self.creatures = [] self.lives = [] self.player = Player(WIDTH / 2, HEIGHT / 2) for i in range(0, random.randint(MIN_GRUES, MAX_GRUES)): creature = Grue(*random_point_not_near(self.player.position)) #print("New Grue at (%s)" % (creature.position)) self.creatures.append(creature) for i in range(0, random.randint(MIN_HEALS, MAX_HEALS)): heal = Lives(random.randrange(0, MAP_WIDTH), random.randrange(0, MAP_HEIGHT)) self.lives.append(heal) self.background = sf.Sprite(sf.Texture.from_file("map2.png")) self.view = sf.View() self.view.reset(sf.Rectangle((0, 0), (WIDTH, HEIGHT))) self.window.view = self.view self.overlay = Overlay(self.player) self.dark_overlay = Overlay(self.player, dark=True) self.life_point_display = PointDisplay( sf.Rectangle((10, 10), (100, 10)), self.player.health, sf.Color.RED) self.stamina_display = PointDisplay( sf.Rectangle((WIDTH - 60 - 10, 10), (60, 10)), self.player.max_stamina, sf.Color.GREEN) self.boss_time = sf.Clock() self.run_timer = sf.Clock() self.treasure_time = sf.Clock() self.stamina_regeneration_timer = sf.Clock() self.is_running = False self.is_dark = False self.has_boss = False self.has_treasure = False
def __init__(self, window): self._window = window self._clear_color = sf.Color(255, 255, 255) self._background_sprite = None self._background_texture = None self._window_opened = True self._clock = sf.Clock() self._fps = 30 self._frame_time = sf.milliseconds(1000 / self._fps)
def __init__(self): self.window = sf.RenderWindow(sf.VideoMode(WIDHT, HEIGHT), TITLE, sf.Style.DEFAULT, settings) self.window.framerate_limit = 20 self.circle = sf.CircleShape(50) self.circle.origin = self.circle.radius, self.circle.radius self.circle.position = self.window.size / 2 self.c_vel = sf.Vector2(5, 5) self.clock = sf.Clock()
def run(): SIZE = 0 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 = [] b_texture.append(sf.Texture.from_file("assets/bln/balon0.png")) b_texture.append(sf.Texture.from_file("assets/bln/balon1.png")) b_texture.append(sf.Texture.from_file("assets/bln/balon2.png")) b_texture.append(sf.Texture.from_file("assets/bln/balon3.png")) balls = [] # 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() for ball in balls: ball.position = ball.position.x, (ball.position.y + BALL_SPEED) if ball.position.y > WHEIGHT: balls.remove(ball) SIZE -= 1 if SIZE < MAX_SIZE: ball = sf.CircleShape(rm.randint(20, 60)) ball.texture = rm.choice(b_texture) ball.origin = 20, 20 ball.position = rm.randint(40, WWIDTH - 80), rm.randint( -300, 0) #WHEIGHT / 8.0 balls.append(ball) SIZE += 1 # Rendering window.clear(sf.Color.BLACK) window.draw(background) for ball in balls: window.draw(ball) window.display()
def __init__(self): self.window = sf.RenderWindow(sf.VideoMode(WIDTH, HEIGHT), TITLE) self.window.framerate_limit = FPS self.backgrounds = [None, None] self.grounds = [None, None] self.bird_texture = None self.bird_animation = None self.bird_sprite = None self.clock = sf.Clock()
def collide(self, other): if isinstance(other, ObstacleLine) or (isinstance(other, Player) and self.direction != other.direction): if self.immortal: return if not isinstance(other, ObstacleLine): SoundManager.play_death_sound() self.reset() elif isinstance(other, Bonus): if other.type == BonusType.IMMORTALITY: self.immortal = sf.Clock() self.plane.color = sf.Color(255, 255, 255) elif other.type == BonusType.BULLET: bullet = Bullet(self.plane.position, self.speed * 2) self.collision_manager.add(bullet) self.bullets.add(bullet) self.immortal = sf.Clock() elif isinstance(other, Bullet): if self.immortal or not other.alive: return SoundManager.play_death_sound() self.reset()
def scanner_test(): w = sf.RenderWindow(sf.VideoMode(400, 400), "Scanner Test") clock = sf.Clock() em = MyEntityManager() sm = SystemManager(em) car1 = em.create_entity() em.add_component(car1, PositionComponent(0, 0, 0)) em.add_component(car1, VelocityComponent(0, 0, 0)) car1_circle = sf.CircleShape() car1_circle.radius = 10 car1_circle.fill_color = sf.Color.RED em.add_component(car1, DrawableComponent(car1_circle)) em.add_component(car1, MovementControlComponent()) em.add_component(car1, ScanSoundComponent("engine_idle_freesound_loop.wav")) car1_engine_sound = PositionSoundComponent( "engine_idle_freesound_loop.wav") car1_engine_sound.sound.loop = True em.add_component(car1, car1_engine_sound) player = em.create_entity() em.add_component(player, PositionComponent(100, 100, 0)) em.add_component(player, VelocityComponent(0, 0, 0)) em.add_component(player, DirectionComponent(radians(180))) player_circle = sf.CircleShape() player_circle.radius = 10 player_circle.fill_color = sf.Color.WHITE em.add_component(player, DrawableComponent(player_circle)) #em.add_component(player, MovementControlComponent()) em.add_component(player, AudioListenerComponent()) em.add_component(player, HydrophoneComponent(radians(0))) sm.add_system(InputSystem(w)) sm.add_system(PhysicsSystem()) sm.add_system(AudioSystem()) sm.add_system(RenderSystem(w)) while w.is_open: sm.update(clock.restart()) for event in w.events: if type(event) is sf.CloseEvent: w.close() # w.display()
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 # Clock self.clock = sf.Clock() # View self.view = sf.View(sf.Rectangle((0, 0), (WWIDTH, WHEIGHT))) self.window.view = self.view # Loading assets self.load_assets() self.backgrounds = [sf.Sprite(self.bg_texture) for i in xrange(2)] self.grounds = [sf.Sprite(self.ground_texture) for i in xrange(2)] self.grounds[0].position = 0, 409 self.grounds[1].position = 0, 409 # Plane fly_anim = Animation() fly_anim.texture = self.plane_sheet fly_anim.add_frame(sf.Rectangle((0, 0), (88, 73))) fly_anim.add_frame(sf.Rectangle((88, 0), (88, 73))) fly_anim.add_frame(sf.Rectangle((176, 0), (88, 73))) fly_anim.add_frame(sf.Rectangle((88, 0), (88, 73))) self.plane = AnimatedSprite(sf.seconds(0.2), False, True) self.plane.play(fly_anim) self.plane.origin = self.plane.global_bounds.width / 2.0, self.plane.global_bounds.height / 2.0 self.plane.position = sf.Vector2(150, 200) self.plane_speed = sf.Vector2(0.0, 0.0) self.jump_time = None self.plane_jumped = False # Rocks self.rocks = [] self.spawn_rocks()
def __init__(self, mainScreen, ruleTables, x=0, y=200, width=200, height=75, text="DEEP IQ's Turn"): self.tables = RuleTables(self, mainScreen) self.x = x self.y = y self.width = width self.height = height self.text = text self.message = "DEEP IQ waits idly. " self.coolDown = sf.Clock() self.canBeClicked = True self.mainScreen = mainScreen box = sf.RectangleShape() box.size = (self.width, self.height) box.outline_color = sf.Color.WHITE box.outline_thickness = 3 box.fill_color = sf.Color.TRANSPARENT box.position = (self.x, self.y) self.box = box buffers = [ sf.SoundBuffer.from_file( os.path.join(os.getcwd(), "res", "dice0.ogg")), sf.SoundBuffer.from_file( os.path.join(os.getcwd(), "res", "dice0.ogg")), sf.SoundBuffer.from_file( os.path.join(os.getcwd(), "res", "dice1.ogg")), sf.SoundBuffer.from_file( os.path.join(os.getcwd(), "res", "dice2.ogg")), sf.SoundBuffer.from_file( os.path.join(os.getcwd(), "res", "dice3.ogg")), sf.SoundBuffer.from_file( os.path.join(os.getcwd(), "res", "dice4.ogg")) ] self.sounds = [] for buffer in buffers: sound = sf.Sound() sound.buffer = buffer self.sounds.append(sound)
def __init__(self, swarm, size=(800, 600)): self.swarm = swarm self.window = sf.RenderWindow(sf.VideoMode(*size), argv[0]) w = self.window self.view = w.view self.is_open = w.is_open self.close = w.close self.paused = False self.clock = sf.Clock() self.sfVert = SFVert(self.window, Red) self.sfNVert = SFVert(self.window, Blue) self.view.size = 2, 2 self.view.center = 0, 0 self.drawNeighbors = False self.drawCentroids = False self.drawPolies = True self.wClicked = None
def main(self): # load big resources first cardPath = os.path.join(os.getcwd(), "res", "cardData.json") allCardData = None with open(cardPath, 'r', encoding="utf-8") as f: allCardData = json.load(f) # SET UP THE GRAPHICS WINDOW window = sf.RenderWindow(sf.VideoMode(1100, 800), 'Mana Burn') window.framerate_limit = 60 window.clear() view = sf.View() view.reset(sf.Rectangle((0, 0), (1100, 850))) window.view = view window.display() # figure out the save game situation currentSavedGame = SavedGame() currentScreen = MainScreen(window, view, currentSavedGame, allCardData) # A clock runs and cleans up dead objects periodically cleanupClock = sf.Clock() # THE UPDATE AND GAME LOOP while window.is_open: for event in window.events: if type(event) is sf.CloseEvent: window.close() if type(event ) is sf.KeyEvent and event.code is sf.Keyboard.ESCAPE: window.close() if type(currentScreen) is MainScreen: if type(event) is sf.MouseButtonEvent: currentScreen.checkClicks(window, event) if type(event) is sf.MouseWheelEvent: currentScreen.checkScroll(window, event) window.clear() currentScreen.update() window.display() if cleanupClock.elapsed_time.seconds >= .5: currentScreen.cleanUp() cleanupClock.restart()
def main(): window = sf.RenderWindow(sf.VideoMode(800, 600), 'Shape example') window.framerate_limit = 60 running = True clock = sf.Clock() custom_shapes = [CustomShape()] rectangles = [] circles = [] for i in range(30): circle = sf.CircleShape(randint(5, 20)) circle.fill_color = random_color() circle.position = random_position(window) circles.append(circle) for i in range(100): rectangle = sf.RectangleShape((randint(10, 30), randint(10, 30))) rectangle.position = random_position(window) rectangle.fill_color = random_color() rectangle.outline_color = random_color() rectangle.outline_thickness = randint(1, 2) rectangles.append(rectangle) while running: for event in window.iter_events(): if event.type == sf.Event.CLOSED: running = False frame_time = clock.restart().as_milliseconds() for r in rectangles: r.rotate(frame_time * 0.3) window.clear(sf.Color.WHITE) for shape in custom_shapes + rectangles + circles: window.draw(shape) 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))
else: percent = 1.0 if percent >= 1.0: complete.append(a) else: a.update(time, percent) for a in complete: a.final() self.animations.remove(a) if len(self.animations) == 0: self.complete = True _clock = sf.Clock() _positionAnimations = [AppearAnimation, LinearAnimation, SpiralAnimation] _scaleAnimations = [NoScaleAnimation, InAndOutAnimation] _rotationAnimations = [NoRotationAnimation, SpinAnimation] def _now(): return _clock.elapsed_time.seconds def createRandomGroup(target): duration = _randVal("duration") g = AnimationGroup(duration) g.add(random.choice(_positionAnimations)(target)) g.add(random.choice(_scaleAnimations)(target))
ball.fill_color = sf.Color.WHITE ball.origin = (ball_radius / 2, ball_radius / 2) # load the font font = sf.Font.from_file("data/sansation.ttf") # initialize the pause message pause_message = sf.Text() pause_message.font = font pause_message.character_size = 40 pause_message.position = (170, 150) pause_message.color = sf.Color.WHITE pause_message.string = "Welcome to pySFML pong!\nPress space to start the game" # define the paddles properties ai_timer = sf.Clock() ai_time = sf.seconds(0.1) paddle_speed = 400. right_paddle_speed = 0. ball_speed = 400. ball_angle = 0. # to be changed later clock = sf.Clock() is_playing = False while window.is_open: # handle events for event in window.events: # window closed or escape key pressed: exit if type(event) is sf.CloseEvent:
pause_message.color = sf.Color.WHITE pause_message.string = "Welcome to Blizzard Blaster!\nPress space to start the game" game_over_message = sf.Text() game_over_message.font = font game_over_message.character_size = 40 game_over_message.position = (170, 150) game_over_message.color = sf.Color.WHITE score_display = sf.Text() score_display.font = font score_display.character_size = 14 score_display.position = (game_size.x - 100, 20) score_display.color = sf.Color.WHITE # define the paddles properties dray_clock = sf.Clock() ai_time = sf.seconds(0.1) tank_speed = 800. high_score = 0 skill_clock = sf.Clock() clock = sf.Clock() dray_time_delta = 0 is_playing = False game_over = False while window.is_open: # handle events
def __init__(self): Actor.__init__(self) self.direction = random_unit_vector() self.direction_timer = sf.Clock()
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])
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()
# Lives lives = 5 lives_text = sfml.Text('Lives: ' + str(lives), bangers_ft, 60) lives_text.position = (20, 10) # Player player = sfml.Sprite(rainbow_dash_tx) player.position = (50, window.size.y / 2) player.ratio = (0.5, 0.5) player_speed = 10 # Enemies enemies = [] enemy_speed = (-5, 0) spawn_clock = sfml.Clock() spawn_time = 1000 # Blasts blasts = [] blast_speed = (15, 0) fire_clock = sfml.Clock() fire_cooldown = 500 # Bullets bullets = [] bullet_speed = (-10, 0) bullet_clock = sfml.Clock() bullet_interval = random.randint(500, 1000) # Title screen
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_events(self, event): if type(event) is sf.CloseEvent: self.window.close() if type(event) is sf.KeyEvent and event.code is sf.Keyboard.SPACE: self.plane_jumped = True self.jump_time = sf.Clock()
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()
def __init__(self): self.clock = sfml.Clock() self.delta = 0.0