def start(): global boidflock seed(time.time()) graphics.init(width=640, height=480) graphics.bg_colour(graphics.BLACK) #splatter a flock in the space randomly def generate_boid(): x = randrange(0, 640) #random left-right y = randrange(0, 480) #random up-down position = pygame.math.Vector2(x, y) #splat a boid, add to flock list velocity = pygame.math.Vector2((random() * 2) - 1, (random() * 2) - 1) velocity.scale_to_length(50) boidflock.add(boids.Boid(position, velocity)) for _ in range(50): generate_boid() for b in boidflock: b.image = pygame.Surface((1, 1)) b.image.fill(graphics.WHITE) boidflock.draw(graphics.screen) graphics.draw()
def start(argv): graphics.assetDirectory('assets') sprite = graphics.Sprite("sprite.png", Vector2D(100.0,100.0), frames=9) button = GUI.Button("button.png", Vector2D(200.0,100.0)) def drawFunc(): sprite.draw() button.draw() graphics.drawText("Works!", Vector2D(80.0,550.0), Color(0,0,255)) graphics.init(800, 600, drawFunc) inputf.init() GUI.init() def movementMicrothread(): while True: if inputf.keyboard[inputf.key.UP]: sprite.position.y += 10 * logic.delta() if inputf.mouse.left: sprite.position.x += 10 * logic.delta() #else: # sprite.position.x -= 10 * logic.delta() if inputf.mouse.inRect(sprite): sprite.position.y -= 10 * logic.delta() microthreads.schedule() microthreads.microthread(movementMicrothread) logic.start()
def main(): global ents, sc, run run = True graphics.init(con.SCR_WIDTH, con.SCR_HEIGHT) sc = score.Score() try: pygame.mixer.pre_init(44100, -16, 2, 4096) pygame.mixer.init() except: print "You don't have audio support." con.audio_support = False if con.audio_support: audio.load_audio() pygame.mixer.music.load(os.path.join('audio', 'jl_music2.ogg')) pygame.mixer.music.set_volume(.9) while run: game_start() game_loop() game_end() pygame.quit()
def init(): global font, smallfont, bigfont, mediumfont, consolefont graphics.init() consolefont = load_font(None, 20) smallfont = font = load_font(None, 25) mediumfont = load_font(None, 32) font = bigfont = load_font(None, 50)
def create_window(size): graphics.init() fullscreen = features.get('ui.fullscreen') if fullscreen: size = graphics.get_screen_size() graphics.create_window(size, fullscreen=fullscreen) if features.get('ui.offscreen'): graphics.set_offscreen_window(size)
def main(): pygame.init() pygame.mixer.init() sound.setvolume(0) pygame.font.init() graphics.setmode() graphics.init() if settings.playback: state0, record = cPickle.load(open(data.filepath("record.pkl"), "rb")) state.loadobj(state0) scene.push(scenes.game if settings.skipmenu else scenes.menu) elif settings.restart: state.init() scene.push(scenes.game if settings.skipmenu else scenes.menu) else: scene.push(scenes.menu) if state.load(): scene.push(scenes.game) clock = pygame.time.Clock() if settings.playback: for rstate, dt, events, kpress, mpos in record: clock.tick(settings.fps) s = scene.top() random.setstate(rstate) if settings.vidcap: vidcap._mpos = mpos s.think(dt, events, kpress, mpos) s.draw(mpos) pygame.display.flip() return if settings.getrecord: record = [] state0 = cPickle.loads(cPickle.dumps(state.saveobj())) while scene.top(): dt = min(0.001 * clock.tick(settings.fps), 0.5) if settings.fixfps: dt = 1.0 / settings.fps s = scene.top() while dt > 0: tdt = min(dt, 0.1) events = map(EventProxy, pygame.event.get()) kpress = pygame.key.get_pressed() mpos = pygame.mouse.get_pos() if settings.getrecord: record.append((random.getstate(), tdt, events, kpress, mpos)) s.think(tdt, events, kpress, mpos) dt -= tdt s.draw(mpos) pygame.display.flip() graphics.quit() if settings.getrecord: cPickle.dump([state0, record], open(data.filepath("record.pkl"), "wb"))
def run(): try: parser.init() stage.init() graphics.init() theme.init() gameloop.start() except KeyboardInterrupt: exit()
def init_screen(): global screen, surface, overview_surface if osutil.is_desktop: # on Android android.pyx takes care of init graphics.init() graphics.create_window((1280, 800)) screen = graphics.get_window() surface = screen
def init(): graphics.init() ui.consolefont = load_font(None, 20) ui.smallfont = font = load_font(None, 25) ui.mediumfont = load_font(None, 32) ui.font = ui.bigfont = load_font(None, 50) if features.get('stream.enable'): from . import stream stream.init()
def run(): try: # Init the editor graphics.init() theme.init() # Start the editor gameloop.start() except KeyboardInterrupt: exit()
def run(width=300, height=300): def redrawAllWrapper(canvas, data): canvas.delete(ALL) canvas.create_rectangle(0, 0, data.width, data.height, fill='black', width=0) graphics.redrawAll(canvas, data) canvas.update() def mousePressedWrapper(event, canvas, data): graphics.mousePressed(event, data) redrawAllWrapper(canvas, data) def keyPressedWrapper(event, canvas, data): graphics.keyPressed(event, data) redrawAllWrapper(canvas, data) def motionWrapper(event, canvas, data): graphics.motion(event, data) redrawAllWrapper(canvas, data) def timerFiredWrapper(canvas, data): graphics.timerFired(data) redrawAllWrapper(canvas, data) # pause, then call timerFired again canvas.after(data.timerDelay, timerFiredWrapper, canvas, data) # Set up data and call init class Struct(object): pass data = Struct() data.width = width data.height = height data.timerDelay = 100 # milliseconds root = Tk() graphics.init(data) # create the root and the canvas canvas = Canvas(root, width=data.width, height=data.height) canvas.configure(bd=0, highlightthickness=0) canvas.pack() # set up events root.bind("<Button-1>", lambda event: mousePressedWrapper(event, canvas, data)) root.bind("<Key>", lambda event: keyPressedWrapper(event, canvas, data)) root.bind('<Motion>', lambda event: motionWrapper(event, canvas, data)) timerFiredWrapper(canvas, data) # and launch the app root.mainloop() # blocks until window is closed print("bye!")
def main(): global surface,FPSCLOCK pygame.init() surface = pygame.display.set_mode((WINDOWWIDTH,WINDOWHEIGHT)) FPSCLOCK = pygame.time.Clock() graphics.init(surface) board = [] for i in range(BOARDROWS): board.append([BLANK]*BOARDCOLS) assert len(board) == BOARDROWS for i in range(BOARDROWS): assert len(board[i]) == BOARDCOLS board[0][0] = TYPE_O board[0][1] = TYPE_O board[1][0] = TYPE_O board[1][1] = TYPE_O board[5][5] = TYPE_I board[6][5] = TYPE_I board[7][5] = TYPE_I board[8][5] = TYPE_I game.start() while (True): if game.checkGameEnd(): print 'the game has ended!!' FPSCLOCK.tick(FPS) continue for event in pygame.event.get(QUIT): terminate() for y in range(BOARDROWS): for x in range(BOARDCOLS): print game.board[y][x], print '' print 'number of pieces: ',len(game.getPieces()) #graphics.drawBoard(board) graphics.reset() for piece in game.getPieces(): # print 'drawing a piece!!!' print piece graphics.drawPiece(piece) graphics.drawStatus(1000,20) pygame.display.update() game.update() FPSCLOCK.tick(FPS)
def main(): global FPSCLOCK, DISPLAYSURF, running,SOUND_CLEARLINE pygame.init() FPSCLOCK = pygame.time.Clock() graphics.init() pygame.mixer.init(44100, -16, 2, 2048) pygame.display.set_caption(GAME_NAME) pygame.mixer.music.load('../music/theme.mp3') # load music theme SOUND_CLEARLINE = pygame.mixer.Sound(file='../music/clearline.wav') # TODO: need to lead line eating sound running = False # show main menu or sth start() run() # by now, the game is over terminate()
def run(): try: # Init the game parser.init() # Check for editor if (parser.args.editor): os.system("/usr/share/make-snake/snake-editor/__main__.py") sys.exit(0) graphics.init() theme.init() stage.init() game.reset() # Start the game gameloop.start() except KeyboardInterrupt: exit()
def main(): cap = cv2.VideoCapture(0) assert cap.isOpened(), 'failed to open capture' _, img = cap.read() height, width = img.shape[:2] pygame.init() pygame.display.set_mode((width, height), DOUBLEBUF | OPENGL) graphics.init() with np.load('calib.npz') as data: cmat, dist = data['mat'], data['dist'] flag = False rvec = np.zeros(3) tvec = np.zeros(3) while True: _, img = cap.read() flag, img, rvec, tvec = track(img, cmat, dist, rvec, tvec, flag) color = 255 if flag else 100 # img = axis(img, rvec, tvec, cmat, dist, color) graphics.clear() graphics.imshow(img) if flag: graphics.drawteapot(rvec, tvec, cmat, width, height) pygame.display.flip() pygame.time.wait(17) for event in pygame.event.get(): if event.type == pygame.QUIT: cap.release() pygame.quit() quit()
# Constants viewport_size = 600 # This is the height of the viewport spread = 20 #used to be 20, but i like at 80 active_hollusion = None lastframe = None #Setup import graphics import math import time import PyGif Posn = graphics.Posn Rgb = graphics.Rgb draw_solid_polygon = graphics.draw_solid_polygon graphics.init(viewport_size) vp = graphics.open_viewport("ViewPort", 4/3*viewport_size, viewport_size) lp = graphics.open_pixmap("LeftPort", 4/3*viewport_size, viewport_size) rp = graphics.open_pixmap("RightPort", 4/3*viewport_size, viewport_size) def clear_all(): global active_hollusion global vp, lp, rp if(active_hollusion != None): active_hollusion("kill") active_hollusion = None graphics.clear_viewport(vp) graphics.clear_viewport(lp) graphics.clear_viewport(rp) class Frame:
Rocks=[] #Init player data, in validation loop due to init player = [Name, Position, Fuel, Civ, Rocks] pythonplanet = int(input("Which Planet would you like to make to be the PythonPlanet?\nPlease enter a planet that exists in your import file: ")) #will raise IndexError if invalid print() graphics = input("Disclaimer: No graphics will be processed if using above 10 planets!\nPlease indicate if you would like to see graphics or not (Y/N): ") #IndexError is raised in the resulting function print() try: #initialize gfx.init(file, presetplanet, planets, player, graphics) #gfx.init loads the file regardless of gfx #try raise except this except IndexError and FileNotFoundError: raise ValueError if pythonplanet in range(len(planets)): gfx.setPythonPlanet(pythonplanet, planets) else: raise ValueError break #if reached here, kill validation loop - it is complete except ValueError: print("Hey! Some of those value(s) were incorrect, please enter them again!") print() continue
def main(): parser = argparse.ArgumentParser(description='Display a randomized Carcassonne map') parser.add_argument('files', metavar='FILE', nargs='*', help='Tile description file (JSON format)') parser.add_argument('-d', '--debug', dest='debug_mode', action='store_true', help='Display non-game tiles, etc.') parser.add_argument('-n', metavar='N', type=int, dest='max_tiles', default = 0, help='Number of tiles to display (Default: The whole tileset)') parser.add_argument('-z', '--zoom-factor', metavar='Z', type=float, dest='zoom_factor', default = 1.0, help='Initial zoom factor (Default: 1.0)') parser.add_argument('--draw-all', dest='draw_all', action='store_true', help='Draw all tiles') parser.add_argument('-f', '--full-screen', dest='full_screen', action='store_true', help='Full screen') parser.add_argument('-s', '--screenshot', dest='take_screenshot', action='store_true', help='Take a screenshot of the final display') parser.add_argument('--dump', dest='dump_to_img', action='store_true', help='Dump the final grid to an image') parser.add_argument('--river-policy', type=str, dest='river_policy', choices=[policy.name for policy in RiverPlacement], action='append', default=[], help='Placement policies for the river tileset. Can be used multiple times') parser.add_argument('--river-period', metavar='P', type=int, dest='river_period', default=1, help='Period of repetition of the river tileset. Set to zero for a single use of the river tileset') parser.add_argument('--seed', metavar='INT', type=int, dest='seed', default = 0, help='A seed for the random generator (Default: Use a system generated seed)') args = parser.parse_args() # Set random seed rng_seed = args.seed if rng_seed == 0: rng_seed = secrets.randbits(64) print('Random seed: {}'.format(rng_seed)) random.seed(rng_seed) # Load tileset (JSON files) tileset = list(itertools.chain.from_iterable(parse_tileset_description_file(json_file) for json_file in args.files)) if len(tileset) == 0: error('No tiles loaded') # River tiles placement policy and period river_placement_policies = parse_river_placement_policies([RiverPlacement[policy] for policy in args.river_policy]) river_tileset_period = args.river_period if args.river_period >= 0 else 0 if args.debug_mode and any('river' in tile.tags for tile in tileset): print('river_placement_policies: {}'.format([policy.name for policy in river_placement_policies])) print('river_tileset_period: {}'.format(river_tileset_period)) try: # Load tile images, and draw missing ones graphics.init() tile_size = load_or_draw_tile_images(tileset, args.draw_all) carcassonne_city_tileset, tileset = TileSubset.carcassonne_city().partition_iter(tileset) city_start_flag = len(carcassonne_city_tileset) > 0 river_tileset, regular_tileset = TileSubset.river().partition(tileset) del tileset # Non-game tiles riverside_tile = Tile.from_uniform_color((217, 236, 255), tile_size, 'riverside') forbidden_tile = Tile.from_uniform_color((100, 20, 20), tile_size, 'forbidden') segment_length_tiles = { 0: forbidden_tile, 1: Tile.from_uniform_color((10, 60, 10), tile_size, 'one_side'), 2: Tile.from_uniform_color((40, 120, 40), tile_size, 'two_sides'), 3: Tile.from_uniform_color((70, 180, 70), tile_size, 'three_sides') } # Open display (w, h) = (0, 0) if args.full_screen else (1280, 720) display = graphics.GridDisplay(w, h, tile_size) print('Press ESCAPE in the graphics window to quit', flush = True) # Place random tiles. The map must grow! candidate_tiles = CandidateTiles( on_update = lambda pos_tile: display.set_tile(segment_length_tiles[pos_tile.get_segment_length()].img, pos_tile.pos.x, pos_tile.pos.y) if args.debug_mode else None, on_delete = None) z = args.zoom_factor border = place_carcassonne_city(carcassonne_city_tileset, candidate_tiles, display, z, Vect(-2, -1)) if city_start_flag else Boundary() total_nb_tiles_placed = 0 total_nb_tiles_not_placed = 0 first_tileset_flag = not city_start_flag all_done_flag = False for tileset in iterate_tilesets(river_tileset, regular_tileset, river_tileset_period, infinite = (args.max_tiles > 0)): for tiles_to_place in shuffle_tileset(tileset, first_tileset_flag, river_placement_policies): local_nb_tiles_placed = 0 while len(tiles_to_place) > 0: tiles_not_placed = [] for tile in tiles_to_place: if args.max_tiles > 0 and total_nb_tiles_placed >= args.max_tiles: all_done_flag = True break if len(border) == 0: # The first tile of the map is placed at the center placed_tile = PlacedTile(tile, Vect(0, 0), r = 0) else: forced_segment = 'R' if 'river' in tile.tags and 'source' not in tile.tags else None max_candidates = 1 candidate_placements = find_candidate_placements(tile, border, candidate_tiles, max_candidates, forced_segment) placed_tile = select_tile_placement(candidate_placements) if len(candidate_placements) > 0 else None if placed_tile: update_border_and_candidate_tiles(placed_tile, border, candidate_tiles) placed_tile.draw(display) total_nb_tiles_placed += 1 local_nb_tiles_placed += 1 # z = 0.995 * z # display.update(z, 100) else: tiles_not_placed.append(tile) if all_done_flag: break if len(tiles_not_placed) == len(tiles_to_place): # making no progress, stop there total_nb_tiles_not_placed += len(tiles_not_placed) for tile in tiles_not_placed: warn('Could not place tile: {}'.format(tile)) break assert len(tiles_not_placed) < len(tiles_to_place) tiles_to_place = tiles_not_placed # Done with the current tiles subset if DEBUG_PRINTOUT or args.debug_mode: print('total_nb_tiles_placed: {} (+{})'.format(total_nb_tiles_placed, local_nb_tiles_placed)) if all_done_flag: break # Done with the current tileset if all_done_flag: break first_tileset_flag = False display.update(z) # Completely done! display.update(z) print('Done!') print('total_nb_tiles_not_placed: {}'.format(total_nb_tiles_not_placed)) print('total_nb_tiles_placed: {}'.format(total_nb_tiles_placed)) sys.stdout.flush() # Wait until the user quits while True: display.check_event_queue(200) except graphics.MustQuit: pass finally: if args.debug_mode and 'display' in locals(): print(display.get_debug_info()) if (args.take_screenshot or args.debug_mode) and 'display' in locals(): display.take_screenshot(SCREENSHOT_PATH) print('Screenshot saved in {}'.format(SCREENSHOT_PATH)) if args.dump_to_img and 'display' in locals(): display.dump_to_img(DUMP_PATH, args.zoom_factor) print('Dump grid to {}'.format(DUMP_PATH)) graphics.quit() return 0
import pygame import graphics import entity import events pygame.init() graphics.init((400, 400)) george = entity.George() graphics.add(george) graphics.background = graphics.load("stars.png") def quit(e): global run if (e.type == pygame.KEYUP): if (e.key == pygame.K_F4 and e.mod & pygame.KMOD_ALT): run = False elif (e.type == pygame.QUIT): run = False events.register(pygame.QUIT, quit) events.register(pygame.KEYUP, quit) events.register(pygame.KEYDOWN, george.key_handler) events.register(pygame.KEYUP, george.key_handler) clock = pygame.time.Clock()
def __init__(self, surf): graphics.surf = surf graphics.init(amount)
def init_game(): graphics.init() gfx_thread.start()
import graphics import unit from random import * graphics.init() pygame.mixer.init() def startScreen(): global plane, banner, cloud1, cloud2, cloud3, cloud4, run, clock, play, instance instance = -1 graphics.background = graphics.load("images/sky.jpg") cloud1 = unit.Cloud(randrange(0, 1400, 10), randint(0, 600)) graphics.register(cloud1) cloud2 = unit.Cloud(randrange(0, 1400, 10), randint(0, 600)) graphics.register(cloud2) banner = unit.Banner(530, 120) graphics.register(banner) play = unit.Play(560, 200) graphics.register(play) plane = unit.Plane(800, 100) graphics.register(plane) cloud3 = unit.Cloud(randrange(0, 1400, 10), randint(0, 600)) graphics.register(cloud3) cloud4 = unit.Cloud(randrange(0, 1400, 10), randint(0, 600))
import pygame, graphics, palette, cursor, toolbar, text, components, wire graphics.init() text.init() class UserInterface: def __init__(self): self.board = Board(self) self.clickables = [] self.cursor = cursor.Cursor() self.toolbar = toolbar.Toolbar() self.toolbar.add_tool(components.display.DisplayTool(self.board)) self.toolbar.add_tool(components.button.ButtonTool(self.board)) self.clickables.append(self.toolbar) infotext = text.render('FlowSID v0.0.1') info = pygame.sprite.Sprite() info.image = pygame.Surface(infotext.rect.inflate(3, 3).size) info.rect = info.image.get_rect() info.image.fill(palette.color(0x10)) pygame.draw.rect(info.image, palette.color(0x20), info.rect, 1) infotext.rect.move_ip(2, 2) info.image.blit(infotext.image, infotext.rect) colors = tuple(palette.color(x) for x in (0x10,0x20,0x30,0x20)) def update_info(frame): info.rect.bottomright = graphics.screen.get_size() for x in range(info.rect.width - 2): color = colors[(x - 16*len(colors)*frame/255)/2%len(colors)] info.image.fill(color, pygame.Rect(x + 1, 1, 1, 1))