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 initProg(self): """ Initialize OpenGL create the cube and sky cube and initialize the positions and orientations for the cubes. """ # enable Z-buffer read and write glEnable(GL_DEPTH_TEST) glDepthMask(GL_TRUE) cuby = CubeMaker() self.cube = cuby.createCube(True, False) self.skyboxverts = cuby.createCube(False, False) self.skyboxverts *= 2000.0 if (self.debug1): print("\n\tType for sky box: ", type(self.skyboxverts), ".") self.printCube(self.skyboxverts) print("\n\tType for cube: ", type(self.cube), ".") self.printCube(self.cube) # Create a clock for timing events. self.clock = sf.Clock() self.image = CreateImage() self.textureID = self.image.doubleImage(self.boximages, 0) if (self.debug1): for x in range(len(self.textureID)): print("\n\tTexture ", x, " with ID ", self.textureID[x], " from file ", self.boximages[x]) self.skyboxID = self.image.createSkyBoxTex(self.skyfiles, len(self.textureID)) glDepthRange(0.1, 200.0)
def loop(self): clock = sf.Clock() while self.hwnd.is_open: dt = clock.restart() self._think(dt.seconds) self.hwnd.clear(sf.Color(18, 176, 255)) self._render() self.hwnd.display()
def SFTaxiTest(polies, verts): sfTaxiShader = SFTaxiShader([poly.centroid for poly in polies]) window = Window() mouseCursor = MouseCursor(window) sfObjects = SFObjects(polies, verts) clickPos = None clock = sf.Clock() while window.is_open: tDelta = clock.restart().seconds sfObjects.setScale(window.view.size.x / window.size.x) window.clear() #window.draw(sfTaxiShader) sfTaxiShader.quad.align(window) sfObjects.quadCorners = sfTaxiShader.quad.corners() sfObjects.updateRays(sfTaxiShader.corners()) window.draw(sfObjects) window.draw(mouseCursor) window.display() checkNavKeys(window, tDelta, mouseCursor.pos) for event in window.events: if type(event) is sf.CloseEvent: window.close() elif type(event) is sf.MouseButtonEvent and event.pressed: if event.button == sf.Mouse.LEFT: sfObjects.clickedAt(mouseCursor.pos) else: checkForNavEvents(window, event, mouseCursor.pos) elif type(event) is sf.KeyEvent and event.pressed: if event.code == sf.Keyboard.ESCAPE: window.close() elif event.code == sf.Keyboard.P: sfObjects.clickedAt = selectPoly elif event.code == sf.Keyboard.I: sfObjects.clickedAt = selectIntersect else: checkForNavEvents(window, event, mouseCursor.pos) else: checkForNavEvents(window, event, mouseCursor.pos)
glEnable(GL_DEPTH_TEST) glDepthMask(GL_TRUE) glClearDepth(1.) # setup a perspective projection glMatrixMode(GL_PROJECTION) glLoadIdentity() gluPerspective(90., 1., 1., 500.) # bind our texture glEnable(GL_TEXTURE_2D) glBindTexture(GL_TEXTURE_2D, texture) glColor4f(1., 1., 1., 1.) # create a clock for measuring the time elapsed clock = sf.Clock() # start game loop while window.is_open: # process events for event in window.events: # close window : exit if event == sf.CloseEvent: window.close() # escape key : exit if event == sf.KeyEvent and event.code == sf.Keyboard.ESCAPE: window.close()
def __init__(self): self.name = "idle" self.timer = sf.Clock() self.duration: Optional[float] = None
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)
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:
def __init__(self, videomode, title): self.window = sf.RenderWindow(videomode, title) self._running = True self._clock = sf.Clock() GameWindow.current = self
def __init__(self): self.timer = sf.Clock() self.my_turn = False self.last_turn = False self.time_limit = 45
class Game: """ The class that stores the window, draws and updates it """ __windowsize = (1060, 960) __window = Window(__windowsize) __clock = sf.Clock() __map = Map(__windowsize) __GuiManager = GUI.guimanager.GUIManager(__window.get_render_window(), __map) def __init__(self): self.__load_widgets() def is_running(self): return self.__window.is_open() def get_window(self): return self.__window def update(self): dtime = self.__clock.restart().seconds self.__window.update(self.__GuiManager) self.__GuiManager.update(dtime) def render(self): """ Draw all objects in window. """ sizex, sizey = self.__map.get_size() tilex, tiley = self.__map.get_tiles_size() self.wall.set_size(tilex, tiley) self.way.set_size(tilex, tiley) self.start.set_size(tilex, tiley) self.end.set_size(tilex, tiley) self.indirect.set_size(tilex, tiley) self.userindirect.set_size(tilex, tiley) map = self.__map.get_map() wind = self.__window.get_render_window() # clear the window wind.clear(sf.Color(0, 0, 0)) # draw content if tilex != 0 or tiley != 0: for i in range(sizex): for j in range(sizey): if map[i][j] == 0: self.wall.set_position(i * tilex, j * tiley) self.wall.draw(wind) elif map[i][j] == 1: self.way.set_position(i * tilex, j * tiley) self.way.draw(wind) elif map[i][j] == 2: self.start.set_position(i * tilex, j * tiley) self.start.draw(wind) elif map[i][j] == 3: self.end.set_position(i * tilex, j * tiley) self.end.draw(wind) elif map[i][j] == 4: self.indirect.set_position(i * tilex, j * tiley) self.indirect.draw(wind) elif map[i][j] == 5: self.userindirect.set_position(i * tilex, j * tiley) self.userindirect.draw(wind) self.__GuiManager.draw(wind) # display window wind.display() def __load_widgets(self): """ Load widgets. """ self.wall = GUI.image.Image("wall") self.way = GUI.image.Image("way") self.start = GUI.image.Image("start") self.end = GUI.image.Image("end") self.indirect = GUI.image.Image("indirect") self.userindirect = GUI.image.Image("userindirect") edit_box_x = GUI.editbox.EditBox(sizex=96, sizey=28, text="30") edit_box_x.set_position(960, 16) edit_box_y = GUI.editbox.EditBox(sizex=96, sizey=28, text="30") edit_box_y.set_position(960, 60) button_showgrid = GUI.button.Button(text="Show Grid") button_showgrid.set_position(960, 100) button_showgrid.bind_left_callback(lambda: self.__map.generate_grid( edit_box_x.get_text(), edit_box_y.get_text())) button_generate = GUI.button.Button(text="Generate") button_generate.set_position(960, 150) button_generate.bind_left_callback(lambda: self.__map.generate()) button_solve = GUI.button.Button(text="Solve") button_solve.set_position(960, 200) button_solve.bind_left_callback(lambda: self.__map.solve_maze()) button_clear_solve = GUI.button.Button(text="Clear Solve") button_clear_solve.set_position(960, 250) button_clear_solve.bind_left_callback(lambda: self.__map.clear_solve()) button_clear_solve.set_character_size(18) button_clear_points = GUI.button.Button(text="Clear points") button_clear_points.set_position(960, 300) button_clear_points.bind_left_callback( lambda: self.__map.clear_points()) button_clear_points.set_character_size(18) self.__GuiManager.add_widget(edit_box_x) self.__GuiManager.add_widget(edit_box_y) self.__GuiManager.add_widget(button_showgrid) self.__GuiManager.add_widget(button_generate) self.__GuiManager.add_widget(button_solve) self.__GuiManager.add_widget(button_clear_solve) self.__GuiManager.add_widget(button_clear_points) self.__GuiManager.add_widget(ES)
def __init__(self, animation: Anim): self.anim = animation self.active_frame = self.anim.frames[0] self.index = 0 self.playing = True self.clock = sf.Clock()
def __init__(self, tilelayer, x: int, y: int, gid: int): super().__init__() self._map = tilelayer.map self._tileset: Optional[MapTileset] = None self._gid = gid self._id = gid self._transformations = TileTransformation.get_transformations( self._gid) for tr in self._transformations: self._gid -= tr for tileset in self._map.tilesets: if tileset.first_gid <= self._gid <= tileset.last_gid: self._id = self._gid - tileset.first_gid self._tileset = tileset break self._x = x * self._tileset.tile_width self._y = y * self._tileset.tile_height self._tx = (self._id % self._tileset.columns) * self._tileset.tile_width self._ty = (self._id // self._tileset.columns) * self._tileset.tile_height self._sprite: sf.VertexArray = sf.VertexArray(sf.PrimitiveType.QUADS) self._sprite.resize(4) self._sprite[0].position = self.position self._sprite[1].position = self.position + sf.Vector2( self._tileset.tile_width, 0) self._sprite[2].position = self.position + sf.Vector2( self._tileset.tile_width, self._tileset.tile_height) self._sprite[3].position = self.position + sf.Vector2( 0, self._tileset.tile_height) tex_coords = self._calculate_tex_coo(self._tx, self._ty) self._sprite[0].tex_coords = tex_coords[0] self._sprite[1].tex_coords = tex_coords[1] self._sprite[2].tex_coords = tex_coords[2] self._sprite[3].tex_coords = tex_coords[3] self._frames = [] self._anim_data = [] self._anim_index = 0 if self.id in self._tileset.animations: self._anim_data = self.tileset.animations[self.id] for frame in self._anim_data: vert = sf.VertexArray(sf.PrimitiveType.QUADS) vert.resize(4) tx = (frame['id'] % self._tileset.columns) * self._tileset.tile_width ty = (frame['id'] // self._tileset.columns) * self._tileset.tile_height vert[0].position = self.position vert[1].position = self.position + sf.Vector2( self._tileset.tile_width, 0) vert[2].position = self.position + sf.Vector2( self._tileset.tile_width, self._tileset.tile_height) vert[3].position = self.position + sf.Vector2( 0, self._tileset.tile_height) tex_coords = self._calculate_tex_coo(tx, ty) vert[0].tex_coords = tex_coords[0] vert[1].tex_coords = tex_coords[1] vert[2].tex_coords = tex_coords[2] vert[3].tex_coords = tex_coords[3] self._frames.append(vert) self._clock = sf.Clock()
def SFTaxiTest(B, polies, isClosed): sfBorders = [SFBorder_debug(b) for b in B] if len(B) < 100 else [] verts = [] xa, ya = zip(*G.P) pMin = Vec2(min(xa), min(ya)) pMax = Vec2(max(xa), max(ya)) window = Window() sz = ((pMax - pMin) * 1.125).y window.view.size = sz, sz * window.size.y / window.size.x HomeView.size = window.view.size window.view.center = (pMax + pMin) / 2.0 HomeView.center = window.view.center circ = SFCircle(sf.Color.BLACK) ca = nearest3(regionAt(window.map_pixel_to_coords(window.size / 2.0))) sfTaxiShader = SFTaxiShader(G.P) mouseCursor = MouseCursor(window) sfObjects = SFObjects(polies, isClosed) clickPos = None clock = sf.Clock() while window.is_open: tDelta = clock.restart().seconds scale = window.view.size.x / window.size.x circ.setScale(2.5 * scale) window.clear() window.draw(sfTaxiShader) corners = sfTaxiShader.quad.corners() for p in verts: circ.circle.position = p window.draw(circ.circle) for b in sfBorders: b.updateRays(corners) window.draw(b) window.draw(sfObjects) window.draw(mouseCursor) window.display() checkNavKeys(window, tDelta, mouseCursor.pos) for event in window.events: if type(event) is sf.CloseEvent: window.close() elif type(event) is sf.MouseButtonEvent and event.pressed: if event.button == sf.Mouse.LEFT: sfObjects.clickedAt(mouseCursor.pos) else: checkForNavEvents(window, event, mouseCursor.pos) elif type(event) is sf.KeyEvent and event.pressed: if event.code == sf.Keyboard.ESCAPE: window.close() elif event.code == sf.Keyboard.G: drawShader = not drawShader elif event.code == sf.Keyboard.V: G.drawVerts = not G.drawVerts elif event.code == sf.Keyboard.P: sfObjects.clickedAt = selectPoly elif event.code == sf.Keyboard.I: sfObjects.clickedAt = selectIntersect else: checkForNavEvents(window, event, mouseCursor.pos) else: checkForNavEvents(window, event, mouseCursor.pos)
def __init__(self, title: str = "NasNas game", w_width: int = 960, w_height: int = 540, v_width: float = 960, v_height: float = 540, fps: Optional[int] = 60): """ Initializes the engine and creates: - a window - a main scene - a camera named game_camera Args: title (str): title of the game window w_width (int): window width w_height (int): window height v_width (int): game view width v_height (int): game view height fps (int): desired fps """ GameObject.game = self self.W_WIDTH, self.W_HEIGHT = w_width, w_height self.V_WIDTH, self.V_HEIGHT = v_width, v_height # Game name, displayed in window title self.name = title self.desired_fps = fps self._window = window.RenderWindow(sf.VideoMode(w_width, w_height), self.name) if self.desired_fps: self._window.framerate_limit = self.desired_fps self._level = None self._fullscreen = False # inputs from keyboard are stored in this list self._inputs: List[int] = [] # list of all cameras/view used in the game self._cameras: List[camera.Camera] = [] # list of all scenes used in the game, usually 1 is enough self._scenes: List[scenes.Scene] = [] # list of all playing transitions self._transitions: List[transitions.Transition] = [] # list of all menus self._menus: List[ui.Menu] = [] # Scene is where everything is drawn on self.scene = self.create_scene(w_width, w_height) # game camera, usually looks at the main scene (world map, scrolling level ...) self.game_camera = self.create_camera( "game", 0, Rect((0, 0), (v_width, v_height))) # clock and dt used for FPS calculation self.clock = sf.Clock() self.dt = 1.0 self.debug = False self.debug_texts = [] # list of DebugText self.scale_view()