def main(): ## read settings from settings.json and store them settings = resource.parse_json("settings.json") ## initialize resource manager res_man = resource.Manager() ## open window scn = scene.Scene() scn.open_window( sf.VideoMode(settings["window"]["width"], settings["window"]["height"]), settings["window"]["name"], sf.Style.CLOSE, sf.ContextSettings(0, 0, settings["window"]["antialias"], 2, 0)) scn.set_window_icon(sf.Image.from_file("sun.png")) ## send all that to the app app = solar.Solar(res_man, scn) app.init() while scn.running(): scn.handle_events() app.update() app.render()
def key_poller(): shutdown = False key_map = {} for c in range(97, 123): key_map[chr(c)] = False rate = rospy.Rate(10) w = sf.RenderWindow(sf.VideoMode(640, 480), "tele-op", sf.Style.TITLEBAR | sf.Style.RESIZE) while not rospy.is_shutdown() and not shutdown: for event in w.events: # Handle shutdown if type(event) is sf.KeyEvent and event.code is sf.Keyboard.ESCAPE: w.close() shutdown = True if type(event ) is sf.KeyEvent and 0 <= event.code and event.code < 26: key = chr(event.code + 97) if (event.pressed): key_map[key] = True if (event.released): key_map[key] = False publish_cmd_vel(key_map) sf.sleep(sf.seconds(0.05))
def __init__(self, width=800, height=600): self.window_size = Vector2(width, height) self.window = sf.RenderWindow(sf.VideoMode(*self.window_size), "PettingZoo") self.window.key_repeat_enabled = False self.window.framerate_limit = 60 self.player = None self.level_tilemap = None self.tilegrid = None self.textures = {} self.font = None self.debug_hud_text = None self.keys = [0, 0, 0] self.zoom = 1 self.show_debug = False self.show_grid = False self.show_help = True self.load_assets() self.running = True self.game_seed = None
def __init__(self): self.render = True self.nRounds = 0 self.touched_this_round = False radius = 15.0 self.ball = Ball(radius=radius, pos_x=random.uniform(radius, window_size_x - radius), pos_y=radius) self.ball.set_vel(random.uniform(-5.0, 5.0), 10.0) controller_height = 1.0 controller_width = 15.0 self.controller = Controller(height=controller_height, width=controller_width, pos_x=window_size_x / 2, pos_y=window_size_y - controller_height / 2) if self.render: self.ball_draw = sfml.graphics.RectangleShape((radius, radius)) self.ball_draw.origin = (radius / 2, radius / 2) self.ball_draw.fill_color = sfml.graphics.Color(255, 0, 0) self.controller_draw = sfml.graphics.RectangleShape( (controller_width, controller_height)) self.controller_draw.origin = (controller_width / 2, controller_height / 2) self.controller_draw.fill_color = sfml.graphics.Color(255, 0, 0) self.render_window = sf.RenderWindow( sf.VideoMode(window_size_x, window_size_y), "pySFML Window")
def __call__(self): window = sf.RenderWindow(sf.VideoMode(640, 480), "Bezier Draw Application.", sf.Style.TITLEBAR + sf.Style.CLOSE) while window.is_open: for event in window.events: if type(event) is sf.CloseEvent: window.close() elif type(event) is sf.MouseButtonEvent and event.pressed: if self._state == self.POINT_COLLECTING: self._add_basic_point(event.position) elif type(event) is sf.KeyEvent and event.pressed and event.code: if sf.Keyboard.is_key_pressed(sf.Keyboard.DELETE): self._state = self.POINT_COLLECTING self._clear_basic_points() self._clear_bezier_points() elif sf.Keyboard.is_key_pressed(sf.Keyboard.RETURN): if len(self._basic_bezier_points) > 1: self._state = self.DISPLAYING self._calculate_bezier_points() self._calculate_basic_points_connections() window.clear(sf.Color.WHITE) if self._state == self.DISPLAYING: window.draw(self._basic_point_connections) window.draw(self._draw_bezier_points) for mark in self._draw_bezier_nodes: window.draw(mark) window.display()
def __init__(self): self.s = None self.width = SCREEN_W self.height = SCREEN_H self.hwnd_context = sf.ContextSettings() self.hwnd_context.antialiasing_level = 4 self.hwnd = sf.RenderWindow(sf.VideoMode(self.width, self.height), "Tankz2D", sf.Style.DEFAULT, self.hwnd_context) self.hwnd.framerate_limit = 60 self.hwnd.vertical_synchronization = True self.state = STATE.IN_MENU self.turn = GameTurn() self.tank_sprites = [0] * 4 self.winner = -1 self.map_scroll = 0 for x in range(4): self.tank_sprites[x] = sf.Sprite(texture_manager.textures[x + 1]) self.tank_sprites[x].origin = (11, 6) self.tank_sprites[x].position = (SCREEN_W / 2, SCREEN_H / 2) self.tank_sprites[x].scale((16, 16)) try: with open('./data/cfg.yaml', 'r') as stream: self.cfg = yaml.safe_load(stream) except Exception as e: print(f'reading config failed: [{e}]') os._exit(-1) self.ui = GUI(self.cfg['ui']) self.ui.set_scene('main_menu') self.map = None self.map = GameMap(MAP_W, MAP_H) self.tanks = [] self.tank_id = 0 self.timer = sf.Clock() self.timer.restart() self.finished = False self.bg = Background(texture_manager.textures[TEXTURE.BACKGROUND]) self.landscape = sf.Sprite(texture_manager.textures[TEXTURE.LANDSCAPE]) self.think_callbacks = { STATE.IN_MENU: self.menu_callback, STATE.WAIT_FOR_START: self.wait_for_start_callback, STATE.IN_GAME: self.ingame_callback, STATE.RESULT: self.results_callback, } self.render_callbacks = { STATE.IN_MENU: self.menu_render_callback, STATE.WAIT_FOR_START: self.wait_for_start_render_callback, STATE.IN_GAME: self.ingame_render_callback, STATE.RESULT: self.results_render_callback } self.projectiles = [] self.cheat_active = False
def main(): w = sf.RenderWindow(sf.VideoMode(640, 480), "Test") while w.is_open: w.clear(sf.Color.BLUE) w.display() for event in w.events: if event == sf.CloseEvent: w.close()
def setup(self, startWindow=None, playerName=None): self.score = 0 self.scoreKeeper = ScoreKeeper() self.scoreKeeper.setFile('snakeScore.txt') self.params = GameParams() # To be filled by user input width = 800 height = 600 font = sf.Font.from_file("rust.ttf") if startWindow is None: # startWindow is None unless this is a restart startWindow = sf.RenderWindow(sf.VideoMode(width, height), "Snake") startWindow.framerate_limit = 60 startWindow.clear(sf.Color.BLACK) #Display Welcome welcomeText = utils.drawText(startWindow, string="Snake", size=60, font=font, position='center') startWindow.display() while(True): setup = False for event in startWindow.events: if type(event) is sf.CloseEvent: exit() elif (type(event) is sf.MouseButtonEvent or type(event) is sf.KeyEvent): setup = True if setup: break #TODO Choose PlayerName if playerName is None: playerName = utils.textInput(startWindow, "Enter Name:", font, maxLength=10) self.params.setPlayerName(playerName) #Choose Difficulty difficulty = utils.selectOptions(startWindow, ["Easy", "Medium", "Hard"], [0, 1, 2], font) frameRates = [20, 25, 30] self.params.setDifficulty(difficulty) self.params.setFrameRate(frameRates[difficulty]) #Choose Board Size boardSize = utils.selectOptions(startWindow, ["Small", "Medium", "Large"], [(40,30), (50,40), (60,50)], font) self.params.setBoardSize(boardSize) self.params.setSquareSize(15) self.params.setFont(font) self.snake = Snake(5, self.params.squareSize, sf.Vector2(10,10)) self.board = Board(width=self.params.boardWidth, height=self.params.boardHeight, squareSize=self.params.squareSize, frameRate=self.params.frameRate) self.board.initSnake(self.snake) startWindow.close() self.playGame()
def __init__(self, width=600, height=600, title="", color="Black", frameRate=60): self.winWidth = width self.winHeight = height if (color.lower() == 'black'): self.bgColor = sf.Color.BLACK else: self.bgColor = sf.Color.WHITE self.window = sf.RenderWindow(sf.VideoMode(self.winWidth, self.winHeight), title) self.window.framerate_limit = frameRate
def __call__(self): window = sf.RenderWindow(sf.VideoMode(800, 800), "Primitives", sf.Style.TITLEBAR + sf.Style.CLOSE) while window.is_open: for event in window.events: if type(event) is sf.CloseEvent: window.close() window.clear(sf.Color.WHITE) for drawable in self._draw_entities: window.draw(drawable) window.display()
def __init__(self): self.view = sf.View(sf.Rect((0, 0), (500, 500))) self.view.viewport = (sf.Rect((0.474, 0.2685), (0.26, 0.463))) self.settings = sf.ContextSettings() self.settings.antialiasing_level = 8 self.window = sf.RenderWindow(sf.VideoMode(1920, 1080), "IFS Flame Fractal Generator", sf.Style.DEFAULT, self.settings) self.window.framerate_limit = 60 self.general = ifs_general() self.cpu_ifs = ifs_cpu(self.general) self.gpu_ifs = ifs_gpu(self.general) self.gui = ui()
def __init__(self, wsize): """ Create a window. Parameters: wsize (int, int): x and y size of window """ width, height = wsize self.__window = sf.RenderWindow(sf.VideoMode(width, height), "Konrad Paluch - Labirynt", sf.Style.CLOSE) self.__window.vertical_synchronization = True self.__window.framerate_limit = 60
def toggle_fullscreen(self): if not self.fullscreen: self.window.close() self._window = window.RenderWindow( sf.VideoMode(const.SCREEN_W, const.SCREEN_H), self.name, sf.Style.NONE) self.window.framerate_limit = self.desired_fps self.window.mouse_cursor_visible = False self.window.vertical_synchronization = True self._fullscreen = True self._inputs = [] self.scale_view() else: self.window.close() self._window = window.RenderWindow( sf.VideoMode(self.W_WIDTH, self.W_HEIGHT), self.name, sf.Style.DEFAULT) self.window.framerate_limit = self.desired_fps self.window.mouse_cursor_visible = True self.window.vertical_synchronization = True self._fullscreen = False self._inputs = [] self.scale_view()
def __init__(self, controller, mode=sf.VideoMode(800, 800), bg=sf.Color.WHITE, algorithm=line_filling): self._state = self.PENCIL_STATE self._interface = FillApplicationInterface(controller) self._bg = bg self._mode = mode self._algorithm = algorithm self._draw_color = sf.Color.GREEN self._draw_area = sf.RenderTexture(mode.width, mode.height) self._dynamic_screen_objects = [] self._draw_area.clear(self._bg) self._draw_scope = {} self._draw_states = { self.PENCIL_STATE: self._pencil_handler, self.FILL_STATE: self._fill_handler, self.CIRCLE_STATE: self._circle_handler, self.RECTANGLE_STATE: self._rectangle_handler, self.POLYGONAL_STATE: self._polygonal_handler, self.ERASER_STATE: self._eraser_handler }
def show(impact_parameter, speed=0.1): signal.signal(signal.SIGUSR1, signal.SIG_IGN) # We don't care about pending signals signal.signal(signal.SIGUSR2, signal.SIG_IGN) # We just watch and enjoy signal.pthread_sigmask(signal.SIG_SETMASK, [signal.SIGUSR1, signal.SIGUSR2]) bg_path = "images/stock-photo.jpg" background_image = sf.Texture.from_file(bg_path) window = sf.RenderWindow(sf.VideoMode(1920, 1080), "A Swagabitch game") background_sprite = sf.Sprite(background_image) window.draw(background_sprite) window.display() window.framerate_limit = 60 # Not to spend 100% CPU time rocket = Simulator.Simulator("images/rocket_tiny.png", impact_parameter, speed) our_planet = Simulator.PhysicalBody("images/Earth128.png") while window.is_open: dt = 1e-2 # Not that accurate as in test(), but who cares window.clear() if sf.Keyboard.is_key_pressed(sf.Keyboard.ESCAPE): break for event in window.events: if not event: break # print(rocket) # print(our_planet) window.draw(background_sprite) rocket.draw(window) our_planet.draw(window) for i in range(GAME_SPEED): rocket.physics() rocket.move(dt) window.display() signal.signal(signal.SIGUSR1, signal.SIG_DFL) signal.signal(signal.SIGUSR2, signal.SIG_DFL)
def _configure( self, tasks_dir='data/imported/paths', #task directory maps_dir='data/imported/maps', #maps directory obstacle_punishment=5, #deafult reward and punishment values local_goal_reward=5, done_reward=10, greedy_distance_reward_weight=0.05, absolute_distance_reward_weight=0.1, vision_range=5, #20, #default vision range target_on_border_reward=5, absolute_distance_observation_weight=0.1, step_punishment=1.5, visualize=False): self.VISUALIZE = visualize self.task_set = TaskSet(tasks_dir, maps_dir) self.task_ids = list(self.task_set.keys()) self.cur_task_i = 0 self.vision_range = vision_range self.observation_space = gym.spaces.Box( low=0, high=1, shape=(2 * self.vision_range + 1, 2 * self.vision_range + 1)) self.obstacle_punishment = abs(obstacle_punishment) self.local_goal_reward = local_goal_reward self.done_reward = done_reward self.step_punishment = step_punishment self.greedy_distance_reward_weight = greedy_distance_reward_weight self.absolute_distance_reward_weight = absolute_distance_reward_weight self.target_on_border_reward = target_on_border_reward self.absolute_distance_observation_weight = absolute_distance_observation_weight if (self.VISUALIZE): self.map_window = sf.RenderWindow(sf.VideoMode(WINDOW_W, WINDOW_H), "MAP")
def __init__(self, width=50, height=40, title="Snake", color="Black", squareSize=15, frameRate=20): self.width = width self.height = height self.winWidth = width * squareSize self.winHeight = height * squareSize if (color.lower() == 'black'): self.bgColor = sf.Color.BLACK else: self.bgColor = sf.Color.WHITE self.window = sf.RenderWindow( sf.VideoMode(self.winWidth, self.winHeight), title) self.window.framerate_limit = frameRate self.squareSize = squareSize self.snake = None self.generateFood()
def mainloop(pis): size = sf.Vector2(1024, 600) vmode = sf.VideoMode(1024, 600) view = sf.View() view.size = size view.center = sf.Vector2(0, 0) window = sf.RenderWindow(vmode, "tokenring", sf.Style.FULLSCREEN) window.framerate_limit = 60 window.view = view clothes = [PiCloth(pi, 30) for p, pi in sorted(pis.items())] place_in_circle(clothes, size) selected_player = None observable_cloth = None world = None brush = sf.CircleShape(10) selected = set() while window.is_open: for event in window.events: if event == sf.Event.CLOSED: window.close() if event == sf.Event.MOUSE_BUTTON_PRESSED: v = sf.Vector2(event['x'], event['y']) - size / 2 target = get_cloth_under(clothes, v) if event['button'] == sfml.window.Button.LEFT and target: methods = ['add', 'remove'] getattr(selected, methods[target in selected])(target) if event['button'] == sfml.window.Button.RIGHT and target: observable_cloth = target t = time() maxtime = max(t - c.pi.ltt for c in clothes if c.pi.ltt > 0) mp = sf.Mouse.get_position(window) mp -= size / 2 selected_player = None for c in clothes: c.resolve_color(t, maxtime) if c.under(mp): selected_player = c if observable_cloth: observable_cloth.fill_color = sf.Color.BLUE world = observable_cloth.pi.world for selected_player in selected: selected_player.fill_color = sf.Color.YELLOW play_with_selected(selected_player) window.clear(sf.Color.BLACK) for c in clothes: window.draw(c) draw_world(world, window, brush) window.display()
from sfml import sf from pygame.time import Clock size = sf.Vector2(600, 400) timelist = [] speed = 5 width, height = size s = sf.RenderWindow(sf.VideoMode(width, height), "HIIII") font = sf.Font.from_file("../Ubuntu-L.ttf") #s.vertical_synchronization = True clock = Clock() sfclock = sf.Clock() def rect(window, colors, pos, outline_thickness=0): o = sf.RectangleShape() o.position = pos[0:2] o.size = pos[2:4] o.outline_thickness = outline_thickness try: o.outline_color = sf.Color(colors[1][0], colors[1][1], colors[1][2]) except: o.outline_color = sf.Color(0, 0, 0) o.fill_color = sf.Color(colors[0][0], colors[0][1], colors[0][2])
from __future__ import division from math import cos, sin, fabs, pi from random import randint from sfml import 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()
from sfml import sf from Board import Board ########### ###INTRO### ########### NORMAL_RESOLUTION = 600 RESOLUTION_X = 600 RESOLUTION_Y = 600 START_MOUSE_POSITION = -1 SIZE_BOARD = 9 window = sf.RenderWindow(sf.VideoMode(RESOLUTION_X, RESOLUTION_Y), "Kółko i krzyżyk") textureX = sf.Texture.from_file('Grafika/X.png') textureO = sf.Texture.from_file('Grafika/O.png') textureP = sf.Texture.from_file('Grafika/PLUS.png') arrayX = [] for i in range(SIZE_BOARD): sprite = sf.Sprite(textureX) arrayX.append(sprite) arrayO = [] for j in range(SIZE_BOARD): sprite = sf.Sprite(textureO) arrayO.append(sprite) arrayP = []
import argparse import cPickle sf = reload(sf) WINDOW_W = 400 WINDOW_H = 400 aparser = argparse.ArgumentParser() aparser.add_argument('map_fname', type=str, help='Path to .npz-file with map to generate tasks for') args = aparser.parse_args() cur_map = np.load(args.map_fname)['arr_0'] map_window = sf.RenderWindow(sf.VideoMode(WINDOW_W, WINDOW_H), "MAP") print(cur_map) map_squares = [[0] * cur_map.shape[1] for _ in range(cur_map.shape[0])] map_window.clear(sf_graph.Color.WHITE) map_window.display() for row in range(cur_map.shape[0]): for col in range(cur_map.shape[1]): map_squares[row][col] = sf_graph.RectangleShape((20, 20)) map_squares[row][col].outline_color = sf.Color.BLACK map_squares[row][col].outline_thickness = 1 # map_squares[row][col].size = sf_sys.Vector2(20, 20) if (cur_map[row][col]): map_squares[row][col].fill_color = sf_graph.Color.RED map_squares[row][col].position = (col * 20, row * 20) map_window.draw(map_squares[row][col]) map_window.display()
def setup(self, startWindow=None, playerName=None): self.params = GameParams() # To be filled by user input # Set up scorekeeping self.score = 0 self.scoreKeeper = ScoreKeeper() self.scoreKeeper.setFile('asteroidScore.txt') # Set up window width = 800 height = 600 font = sf.Font.from_file("rust.ttf") self.params.setFont(font) if startWindow is None: # startWindow is None unless this is a restart startWindow = sf.RenderWindow(sf.VideoMode(width, height), "Asteroids") startWindow.framerate_limit = 60 startWindow.clear(sf.Color.BLACK) #Display Welcome welcomeText = utils.drawText(startWindow, string="Asteroids", size=60, font=font, position='center') startWindow.display() # Wait for any input while (True): setup = False for event in startWindow.events: if type(event) is sf.CloseEvent: exit() elif (type(event) is sf.MouseButtonEvent or type(event) is sf.KeyEvent): setup = True if setup: break # Select Player Name if playerName is None: playerName = utils.textInput(startWindow, "Enter Name:", font, maxLength=10) self.params.setPlayerName(playerName.lower()) #Choose Difficulty difficulty = utils.selectOptions(startWindow, ["Easy", "Medium", "Hard"], [0, 1, 2], font) makeTimes = [20, 15, 12] timeModifiers = [0.98, 0.95, 0.92] self.params.setDifficulty(difficulty) self.timeToMakeAsteroid = makeTimes[difficulty] self.makeTimeModifier = timeModifiers[difficulty] self.lastAsteroidTime = time.time() - self.timeToMakeAsteroid self.timeToMakePowerup = 20 self.lastPowerupTime = time.time() - self.timeToMakePowerup self.powerupProbability = 1 / 600 # Set up Board self.board = Board(title="Asteroids", width=700, height=700) # Set up Ship self.ship = Ship(position=(self.board.getBoundary()[0] / 2, self.board.getBoundary()[1] / 2)) self.ship.setWrapping(True) self.ship.setBoundary(self.board.getBoundary()) startWindow.close()
def __init__(self, grid_step): self.grid_step = grid_step self.directions = 4 # creating a grid self.create_grid(self.grid_step) self.create_grid_elements() self.walls_list = [] self.deleted_walls = False # path line self.path = sf.VertexArray(sf.PrimitiveType.LINES_STRIP, 0) # path outline, just to make the line look thicker self.path_outline1 = sf.VertexArray(sf.PrimitiveType.LINES_STRIP, 0) self.path_outline2 = sf.VertexArray(sf.PrimitiveType.LINES_STRIP, 0) # GUI self.search_button = self.new_button( 'Search', (self.GRID_POS.x + self.grid_box.size.x + 75, self.GRID_POS.y + 25), sf.Color(50, 200, 50) ) self.reset_button = self.new_button( 'Reset', (self.GRID_POS.x + self.grid_box.size.x + 75, self.GRID_POS.y + 125), sf.Color(200, 50, 50) ) self.dezoom_button = self.new_button( ' -', (self.GRID_POS.x + self.grid_box.size.x + 72, self.GRID_POS.y + 225), sf.Color(160, 160, 160), size="small" ) self.zoom_button = self.new_button( ' +', (self.GRID_POS.x + self.grid_box.size.x + 72 + 105, self.GRID_POS.y + 225), sf.Color(160, 160, 160), size="small" ) self.directions_text = sf.Text('Directions :') self.directions_text.font = self.FONT self.directions_text.color = sf.Color.BLACK self.directions_text.character_size = 25 self.directions_text.origin = (0, -self.directions_text.character_size/2) self.directions_text.position = (self.GRID_POS.x + self.grid_box.size.x + 72, self.GRID_POS.y + 375) self.direction4_button = self.new_button( ' 4', (self.GRID_POS.x + self.grid_box.size.x + 72, self.GRID_POS.y + 425), sf.Color(160, 160, 160), size="small" ) self.direction8_button = self.new_button( ' 8', (self.GRID_POS.x + self.grid_box.size.x + 72 + 105, self.GRID_POS.y + 425), sf.Color(160, 160, 160), size="small" ) self.fps_text = sf.Text('fps:') self.fps_text.font = self.FONT self.fps_text.color = sf.Color.BLACK self.fps_text.character_size = 20 self.fps_text.origin = (0, -self.fps_text.character_size / 2) self.fps_text.position = (0, 0) self.fps_history = [] # used to compute average FPS self.message = sf.Text('') self.message.font = self.FONT self.message.color = sf.Color.BLACK self.message.character_size = 25 self.message.origin = (0, -self.message.character_size / 2) self.message.position = (350, 10) self.author = sf.Text('Modar NASSER (c) 2020') self.author.font = self.FONT self.author.color = sf.Color.BLACK self.author.character_size = 20 self.author.origin = (self.author.global_bounds.width, self.author.character_size/2) self.fps_clock = sf.Clock() # used to get real fps self.astar_clock = sf.Clock() # used to get how much time the agorithm takes self.current_state = self.START_POS_STATE self.window = sf.RenderWindow(sf.VideoMode(1422, 800), "A* algorithm simulator") self.window.framerate_limit = 100 self.icon = sf.Image.from_file(pyInstallerPath('assets/icon64.png')) self.window.set_icon(64, 64, sf.Image.from_file(pyInstallerPath('assets/icon64.png')).pixels.tobytes()) self.author.position = (self.window.size.x-5, self.window.size.y-5)
self.surface.clear(sf.Color.WHITE) self.surface.draw(self.background_sprite) for entity in self.entities: self.surface.draw(entity) self.surface.display() def on_draw(self, target, states): states.shader = self.shader target.draw(sf.Sprite(self.surface.texture), states) if __name__ == "__main__": # create the main window window = sf.RenderWindow(sf.VideoMode(800, 600), "pySFML - Shader") window.vertical_synchronization = True # create the effects effects = (Pixelate(), WaveBlur(), StormBlink(), Edge()) current = 0 # initialize them for effect in effects: effect.load() # create the message background try: text_background_texture = sf.Texture.from_file( "data/text-background.png")
def setup(self, startWindow=None, playerName=None): self.params = GameParams() # To be filled by user input # Set up scorekeeping self.score = 0 self.scoreKeeper = ScoreKeeper() self.scoreKeeper.setFile('breakoutScore.txt') # Set up window width = 800 height = 600 font = sf.Font.from_file("rust.ttf") self.params.setFont(font) if startWindow is None: # startWindow is None unless this is a restart startWindow = sf.RenderWindow(sf.VideoMode(width, height), "Breakout") startWindow.framerate_limit = 60 startWindow.clear(sf.Color.BLACK) #Display Welcome welcomeText = utils.drawText(startWindow, string="Breakout", size=60, font=font, position='center') startWindow.display() # Wait for any input while (True): setup = False for event in startWindow.events: if type(event) is sf.CloseEvent: exit() elif (type(event) is sf.MouseButtonEvent or type(event) is sf.KeyEvent): setup = True if setup: break # Select Player Name if playerName is None: playerName = utils.textInput(startWindow, "Enter Name:", font, maxLength=10) self.params.setPlayerName(playerName.lower()) #Choose Difficulty #difficulty = utils.selectOptions(startWindow, ["Easy", "Medium", "Hard"], [0, 1, 2], font) #self.params.setDifficulty(difficulty) # Set up Board self.board = Board(title="Breakout", width=1000, height=500) # Set up Paddle self.paddle = Paddle(boundary=self.board.getBoundary(), width=75, height=15) self.paddle.setMoveSpeed(10) # Gameplay parameters self.maxLayers = 5 self.level = 1 startWindow.close()
win.draw(newR) win.draw(r) def moveXModulo(vin, x, mod): xin = vin.x yin = vin.y newX = abs((xin + x) % mod) return sf.Vector2(newX, yin) vit = sf.Vector2(0, 0) window = sf.RenderWindow(sf.VideoMode(WIDTH, HEIGHT), 'Basic Window Tutorial', sf.Style.DEFAULT) window.framerate_limit = 60 window.key_repeat_enabled = False rect = sf.RectangleShape() rect.size = (50, 50) rect.position = (475, 25) rect.fill_color = sf.Color.GREEN while window.is_open: # fetch events (explained in next tutorial function) for event in window.events: if event == sf.Event.CLOSED: window.close() if event == sf.Event.KEY_PRESSED:
def main(song): window = sf.RenderWindow(sf.VideoMode(600, 600), "pySFML - Spacial Music") window.framerate_limit = 60 # load one font, one song and two textures try: font = sf.Font.from_file("data/sansation.ttf") music = sf.Music.from_file(song) texture = sf.Texture.from_file("data/speaker.gif") speaker = sf.Sprite(texture) speaker.position = -texture.size // 2 texture = sf.Texture.from_file("data/head_kid.png") hears = sf.Sprite(texture) hears.origin = texture.size // 2 except IOError: exit(1) # create a text that display instructions instructions = "Up/Down Move hears along Y axis\n" instructions += "Left/Right Move hears along X axis\n" instructions += "Plus/Minus Move hears along Z axis" instructions = sf.Text(instructions, font, 12) instructions.position = (70, 250) instructions.color = sf.Color.BLACK # make sure the song is monothread so it can be spacialized if music.channel_count != 1: print("Only sounds with one channel (mono sounds) can be spatialized.") print("This song ({0}) has {1} channels.".format( SONG, music.channels_count)) exit(1) # setup the music properties music.relative_to_listener = False music.min_distance = 200 music.attenuation = 1 # initialize some values before entering the main loop position = sf.Vector3(-250, -250, 0) sf.Listener.set_position(position) x, y, _ = position hears.position = (x, y) running = True # move the view to make coord (0, 0) appears on the center of the screen window.default_view.move(-300, -300) # start the music before entering the main loop music.loop = True music.play() # start the main loop while running: for event in window.events: if type(event) is sf.CloseEvent: running = False elif type(event) is sf.KeyEvent and event.pressed: if event.code is sf.Keyboard.UP: position.y -= 5 elif event.code is sf.Keyboard.DOWN: position.y += 5 elif event.code is sf.Keyboard.LEFT: position.x -= 5 elif event.code is sf.Keyboard.RIGHT: position.x += 5 elif event.code is sf.Keyboard.ADD: if position.z < 400: position.z += 5 elif event.code is sf.Keyboard.SUBTRACT: if position.z > -400: position.z -= 5 # update the listener and the hears position sf.Listener.set_position(position) x, y, z = position hears.position = (x, y) hears.ratio = (1, 1) + sf.Vector2(z, z) / 400. # clear screen, draw images and text and display them window.clear(sf.Color.WHITE) if position.z >= 0: window.draw(speaker) window.draw(hears) else: window.draw(hears) window.draw(speaker) window.draw(instructions) window.display() window.close()
import OpenGL from OpenGL.GL import * from OpenGL.GLU import * from sfml import sf # create the main window window = sf.RenderWindow(sf.VideoMode(800, 600), "pySFML - OpenGL", sf.Style.DEFAULT, sf.ContextSettings(32)) window.vertical_synchronization = True # load a font for drawing some text font = sf.Font.from_file("resources/sansation.ttf") # create a sprite for the background background_texture = sf.Texture.from_file("resources/background.jpg") background = sf.Sprite(background_texture) # load an OpenGL texture. # we could directly use a sf.Texture 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 from an image texture = 0 image = sf.Image.from_file("resources/texture.jpg") glGenTextures(1, texture) glBindTexture(GL_TEXTURE_2D, texture) gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, image.size.x, image.size.y, GL_RGBA, GL_UNSIGNED_BYTE, image.pixels.data) 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
import OpenGL from OpenGL.GL import * from OpenGL.GLU import * from sfml import sf # create the main window window = sf.RenderWindow(sf.VideoMode(800, 600), "pySFML - OpenGL", sf.Style.DEFAULT, sf.ContextSettings(32)) window.vertical_synchronization = True # load a font for drawing some text font = sf.Font.from_file("resources/sansation.ttf") # create a sprite for the background background_texture = sf.Texture.from_file("resources/background.jpg") background = sf.Sprite(background_texture) # load an OpenGL texture. # we could directly use a sf.Texture 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 from an image texture = 0 image = sf.Image.from_file("resources/texture.jpg") glGenTextures(1, texture) glBindTexture(GL_TEXTURE_2D, texture) gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, image.size.x, image.size.y, GL_RGBA, GL_UNSIGNED_BYTE, image.pixels.data) 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)