def __init__(self, win_width = 640, win_height = 480): pygame.init() self.screen = pygame.display.set_mode((win_width, win_height)) pygame.display.set_caption("Simulation of a rotating 3D Cube (tamilselvan)") self.clock = pygame.time.Clock() self.vertices = [ Point3D(-1,1,-1), Point3D(1,1,-1), Point3D(1,-1,-1), Point3D(-1,-1,-1), Point3D(-1,1,1), Point3D(1,1,1), Point3D(1,-1,1), Point3D(-1,-1,1) ] # Define the vertices that compose each of the 6 faces. These numbers are # indices to the vertices list defined above. self.faces = [(0,1,2,3),(1,5,6,2),(5,4,7,6),(4,0,3,7),(0,4,5,1),(3,2,6,7)] # Define colors for each face self.colors = [(255,0,255),(255,0,0),(0,255,0),(0,0,255),(0,255,255),(255,255,0)] self.angle = 0
def __init__(self): pygame.init() self.h=480 self.w=640 black= ( 0, 0, 0) white= ( 255, 255, 255) red = ( 255, 0, 0) self.window=pygame.display.set_mode((self.w,self.h)) self.surface = pygame.Surface([self.w,self.h]) self.surface.fill(white) self.window.blit(self.surface,(0,0)) pygame.display.set_caption("SWORDS") self.screen=pygame.display.get_surface() if self.screen == None: print 'NO DISPLAY IS SET' self.all_sprites_list = pygame.sprite.RenderPlain() self.player1 = Sword(red, 20, 15) self.player2 = Sword(red, 20, 15) self.player3 = Sword(red, 20, 15) self.player4 = Sword(red, 20, 15) self.player5 = Sword(red, 20, 15) self.all_sprites_list.add(self.player1) self.all_sprites_list .add(self.player2) self.all_sprites_list.add(self.player3) self.all_sprites_list.add(self.player4) self.all_sprites_list.add(self.player5) self.i=0 self.x=0 self.y=0 self.t=0 self.score=0
def __init__(self, solutionspace, algorithm, stopevent, options): algorithm.initialize(solutionspace, options, stopevent) def getx(p): (a,b) = p return a def gety(p): (a,b) = p return b (max_x, _) = max(solutionspace.solution, key = getx) (_, max_y) = max(solutionspace.solution, key = gety) self.range = max(max_x, max_y) self.size = 400 self.pointSize = 3 self.margin = 20 self.closeDelay = 3 self.visual = options.visual self.stopEvent = stopevent self.gen = algorithm.execute() self.algorithm = algorithm self.solution = solutionspace pygame.init() if options.visual: self.window = pygame.display.set_mode((self.size + 2 * self.margin, self.size + 2 * self.margin)) self.update()
def __init__(self): pg.mixer.pre_init(44100, -16, 4, 2048) pg.init() self.screen = pg.display.set_mode((WIDTH, HEIGHT)) pg.display.set_caption(TITLE) self.clock = pg.time.Clock() self.load_data()
def test(): pygame.init() size = width, height = 320, 240 speed = [2, 2] black = 0, 0, 0 screen = pygame.display.set_mode(size) ball = pygame.image.load("ball.gif") ballrect = ball.get_rect() while 1: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() ballrect = ballrect.move(speed) if ballrect.left < 0 or ballrect.right > width: speed[0] = -speed[0] if ballrect.top < 0 or ballrect.bottom > height: speed[1] = -speed[1] screen.fill(black) screen.blit(ball, ballrect) pygame.display.flip()
def main(): """ Main program function. """ # Initialize Pygame and set up the window pygame.init() size = [SCREEN_WIDTH, SCREEN_HEIGHT] screen = pygame.display.set_mode(size) pygame.display.set_caption("My Game") pygame.mouse.set_visible(False) # Create our objects and set the data done = False clock = pygame.time.Clock() # Create an instance of the Game class game = Game() # Main game loop while not done: # Process events (keystrokes, mouse clicks, etc) done = game.process_events() # Update object positions, check for collisions game.run_logic() # Draw the current frame game.display_frame(screen) # Pause for the next frame clock.tick(60) # Close window and exit pygame.quit()
def __init__(self,scales = [.3,.01,.01,.01,.01,.01]): pygame.init() pygame.joystick.init() self.controller = pygame.joystick.Joystick(0) self.controller.init() self.lStick = LeftStick(self.controller.get_axis(0), self.controller.get_axis(1)) self.rStick = RightStick(self.controller.get_axis(4), self.controller.get_axis(3)) # dpad directions ordered as up down left right dPadDirs = getDirs(self.controller) self.dPad = DPad(dPadDirs) #self.dPad = DPad(self.controller.get_hat(0)) self.trigger = Trigger(self.controller.get_axis(2)) self.inUse = [False,False,False,False] length = 6 self.offsets = np.zeros(length) self.uScale = np.ones(length) self.lScale = np.ones(length) self.driftLimit = .05 self.calibrate() self.scales = np.array(scales) time.sleep(1) self.calibrate()
def main(): pygame.init() width, height = 320, 240 size = width, height speed = [1, 1] black = 0, 0, 0 screen = pygame.display.set_mode(size) icon = pygame.image.load("ball icon.png") pygame.display.set_icon(icon) ball = pygame.image.load("ball.png").convert() ballrect = ball.get_rect() while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() screen.fill(black, ballrect) ballrect = ballrect.move(speed) if ballrect.left < 0 or ballrect.right > width: speed[0] = -speed[0] if ballrect.top < 0 or ballrect.bottom > height: speed[1] = -speed[1] for i in range(5000): time.sleep(0.000001) screen.fill(black, ballrect) screen.blit(ball, ballrect) pygame.display.flip()
def __init__(self, width=config.screen_width, height=config.screen_height): # initialization all pygame modules pygame.init() self.width, self.height = width, height self.screen = pygame.display.set_mode((self.width, self.height)) pygame.display.set_caption("Pacman") pygame.mouse.set_visible(0) #set repetition (set_repeat(after first keydown, after any other)) pygame.key.set_repeat(30,30) #text font self.font48 = pygame.font.SysFont(None, 48) self.font30 = pygame.font.SysFont(None, 30) ##sounds pygame.mixer.init() self.sounds = {'die': pygame.mixer.Sound(os.path.join(config.snd_dir, "die.ogg")), 'intro': pygame.mixer.Sound(os.path.join(config.snd_dir, "intro.ogg"))} ##intro music self.sounds['intro'].play() ##gameplay variables self.enemy_max_cols = 3 # equal to pacman.lives self.enemy_cols = 0 self.prev_life_score = 0 self.lives_cntr = 3 self.max_pellets = 181 #bool var for check enabled menu or not self.set_menu = False
def init_pygame(): pygame.init() size = (pygame.display.Info().current_w, pygame.display.Info().current_h) pygame.display.set_caption('Photo Booth Pics') #pygame.display.set_mode(size).fill(backg_fill) pygame.mouse.set_visible(False) #hide the mouse cursor return pygame.display.set_mode(size, pygame.FULLSCREEN)
def __init__(self, input_method, lcm_tag, joy_name): print('Initializing...') pygame.init() self.screen = pygame.display.set_mode((300, 70)) pygame.display.set_caption(lcm_tag) self.font = pygame.font.SysFont('Courier', 20) if input_method == 'keyboard': self.event_processor = KeyboardEventProcessor() print(bcolors.OKBLUE + '--- Keyboard Control Instruction --- ' + bcolors.ENDC) print('To increase the throttle/brake: press and hold the Up/Down' + ' Arrow') print('To decrease the throttle/brake: release the Up/Down Arrow') print( 'To keep the the current throttle/brake: press the Space Bar') print( 'To increase left/right steering: press the Left/Right Arrow') print(bcolors.OKBLUE + '------------------------------------ ' + bcolors.ENDC) else: self.event_processor = JoystickEventProcessor(joy_name) self.last_value = SteeringThrottleBrake(0, 0, 0) self.lc = lcm.LCM() self.lcm_tag = lcm_tag print('Ready')
def main(): pygame.init() globals.pygame = pygame # assign global pygame for other modules to reference globals.inputs = Inputs(pygame) # assign global inputs for other modules to reference update_display_mode() # now that the global display properties have been set up, update the display clock = pygame.time.Clock() # clock to tick / manage delta entities = [] # contains every object that will be drawn in the game entities.append(Entity()) # our testing entity will be the default entity loop = True # for controlling the game loop while(loop): clock.tick(60) # tick the clock with a target 60 fps globals.window.fill((255, 255, 255)) globals.inputs.update() # refresh inputs update(entities) # update all entities render(entities) # draw all entities if(globals.inputs.isKeyDown("space")): toggle_fullscreen() # space bar toggles fullscreen if(globals.inputs.isKeyDown("escape")): loop = False # escape key exits game if(globals.inputs.isQuitPressed()): loop = False # red 'x' button exits game pygame.display.flip() # flip the display, which finally shows our render pygame.quit() # unload pygame modules
def runGame(): # Initialize game, settings and screen object pygame.init() drSettings = Settings() screen = pygame.display.set_mode( (drSettings.screenWidth, drSettings.screenHeight)) pygame.display.set_caption("Drag Race") totalTime = 0 # Make the car car = Car(drSettings, screen) # Initialize the timer, gear text and speed hud = HeadUpDisplay(drSettings, screen, totalTime, car) # Store the game statistics stats = GameStats() # Start the main loop for the game while True: # Check for keypresses gf.checkEvents(car, stats) # Update the game active state if not car.onScreen: stats.gameActive = False if stats.gameActive: # Update the position of the car and the hud car.update() hud.update(stats.totalTime, car) stats.totalTime += drSettings.timeIncrement # Update the screen gf.updateScreen(drSettings, screen, car, hud)
def __init__(self, rom_file, display_screen=False,frame_skip=4,screen_height=84,screen_width=84,repeat_action_probability=0,color_averaging=True,random_seed=0,record_screen_path='screen_pics',record_sound_filename=None,minimal_action_set=True): self.ale = ALEInterface() if display_screen: if sys.platform == 'darwin': import pygame pygame.init() self.ale.setBool('sound', False) # Sound doesn't work on OSX elif sys.platform.startswith('linux'): self.ale.setBool('sound', True) self.ale.setBool('display_screen', True) self.ale.setInt('frame_skip', frame_skip) self.ale.setFloat('repeat_action_probability', repeat_action_probability) self.ale.setBool('color_averaging', color_averaging) if random_seed: self.ale.setInt('random_seed', random_seed) self.ale.loadROM(rom_file) if minimal_action_set: self.actions = self.ale.getMinimalActionSet() else: self.actions = self.ale.getLegalActionSet() self.dims = (screen_width,screen_height)
def __init__(self, win_width=640, win_height=480): """Initialization of pygame environment and hand joint coordinates.""" pygame.init() self.clock = pygame.time.Clock() self.screen = pygame.display.set_mode((win_width, win_height)) pygame.display.set_caption("3D Wireframe Hand Model Simulation") # Read in joint positions from csv file (argument from command line). self.joints = [] with open(sys.argv[1], 'rU') as f: csvf = csv.reader(f) for line in csvf: try: self.joints.append(Point3D(line[0], line[1], line[2])) except IndexError: raise InvalidInputFile("Each line must have following \ format: 'x, y, z'") if len(self.joints) % 21 != 0: raise InvalidInputFile("Total number of lines in input file must \ be a multiple of 21.") # Define the points that compose each of the fingers. self.index = (0, 1, 2, 3, 19) self.middle = (4, 5, 6, 7, 19) self.ring = (8, 9, 10, 11, 19) self.pinky = (12, 13, 14, 15, 19) self.thumb = (16, 17, 18, 19, 20) self.angleX = 0 self.angleY = 0 self.angleZ = 0 self.play = 0
def __init__(self, joystick_num=0): pygame.init() pygame.display.set_caption("Joystick Analyzer") # Set up the joystick pygame.joystick.init() self.my_joystick = None self.joystick_names = [] # Enumerate joysticks for i in range(0, pygame.joystick.get_count()): self.joystick_names.append(pygame.joystick.Joystick(i).get_name()) print self.joystick_names # By default, load the first available joystick. if len(self.joystick_names) > 0: self.my_joystick = pygame.joystick.Joystick(joystick_num) self.my_joystick.init() max_joy = max(self.my_joystick.get_numaxes(), self.my_joystick.get_numbuttons(), self.my_joystick.get_numhats()) self.screen = pygame.display.set_mode((max_joy * 30 + 10, 170)) self.font = pygame.font.SysFont("Courier", 20)
def __init__ (self, screen): pygame.mouse.set_visible(False) pygame.mouse.get_focused(True) pygame.init() music1='testBack.aud' music2='testBack2.aud' #play_file(music1) self.screen=screen self.size=screen.get_size() self.object_list=[] self.cur_fol=CursorFollower(self) self.wind=WindowObj(self) self.parent=screen self.myfont = pygame.font.SysFont("monospace", 15) create_window(self.wind,'mainMenu') self.order=Item(self,[200,100]) self.chaos=Item(self,[100,100]) self.order.image_name='Order' self.chaos.image_name='Chaos' self.order.interactive_name='order' self.chaos.interactive_name='chaos' #self.chaos.bondedTo=self.rufusRake self.create(self.order) self.create(self.chaos) self.create(self.cur_fol) self.create(self.wind) print("Damn you, world!") self.update()
def main(): pygame.init() mixer.init() screen = pygame.display.set_mode([480, 700]) if android: android.init() android.map_key(android.KEYCODE_BACK, pygame.K_ESCAPE) android.accelerometer_enable(True) game = Game(screen, "images") ret = game.startScreen() if ret == False: pygame.quit() sys.exit(1) while 1: game.init() for life in range(3): ball = game.createBall() game.balls.append(ball) ret = game.play() if ret == False: pygame.quit() sys.exit(1) ret = game.gameOver() if ret == False: pygame.quit() sys.exit(1)
def __init__(self, grid_size, tile_size, bg_img, door_coords, caption='Building Evacuation'): # Set the width and height of the screen [width, height] in pixels self.grid_size = grid_size self.tile_size = tile_size self.door_coords = door_coords self.x_range = int(self.grid_size[0] / self.tile_size) self.y_range = int(self.grid_size[1] / self.tile_size) # Setup pygame ui environment pygame.init() flags = pygame.DOUBLEBUF | pygame.RESIZABLE | pygame.HWSURFACE self.screen = pygame.display.set_mode(self.grid_size, flags) pygame.display.set_caption(caption) # limit events to ones that we actually use pygame.event.set_allowed([pygame.QUIT, pygame.MOUSEBUTTONDOWN, pygame.MOUSEBUTTONUP]) # Load the background image self.bg_img = pygame.image.load(bg_img).convert() self.bg_img_original = self.bg_img.copy() # anytime we zoom, we want to use the original self.bgx = -100 self.bgy = -600 # Used to manage how fast the screen updates self.clock = pygame.time.Clock() # zoom level, 1 is max out zoom, 3 is max in zoom self.zoom_level = 1 self.zoom_pos = [0, 0] # used for dragging image self.mouse_down = False self.click_pos = (0, 0)
def main(): width = 800; height = 600; title = "Swept AABB"; fps = 60; fpsClock = pygame.time.Clock(); pygame.init(); displaySurface = pygame.display.set_mode((width, height)); pygame.display.set_caption(title); player = Box(10, 300, 50, 50, 0, 0); moveSpeed = 10; wall = Box(300, 200, 100, 200, 0, 0); gameRunning = True; while (gameRunning): for event in pygame.event.get(): if (event.type == QUIT): gameRunning = False; getInput(player, moveSpeed); doCollision(player, wall); render(displaySurface, player, wall); pygame.display.update(); fpsClock.tick(fps); pygame.quit(); sys.exit();
def main(): # Initialise screen pygame.init() screen = pygame.display.set_mode((150, 50)) pygame.display.set_caption('Basic Pygame program') # Fill background background = pygame.Surface(screen.get_size()) background = background.convert() background.fill((250, 250, 250)) # Display some text font = pygame.font.Font(None, 36) text = font.render("Hello There", 1, (10, 10, 10)) textpos = text.get_rect() textpos.centerx = background.get_rect().centerx background.blit(text, textpos) # Blit everything to the screen screen.blit(background, (0, 0)) pygame.display.flip() # Event loop while 1: for event in pygame.event.get(): if event.type == QUIT: return screen.blit(background, (0, 0)) pygame.display.flip()
def __init__(self): pygame.init() self.screen = pygame.display.set_mode( (800,600) ) pygame.display.set_caption("Collisions") self.player = Player(keyboard={ 'left': pygame.K_LEFT, 'right': pygame.K_RIGHT, 'up': pygame.K_UP, 'down': pygame.K_DOWN, }) self.enemy = Player(keyboard={ 'left': pygame.K_a, 'right': pygame.K_d, 'up': pygame.K_w, 'down': pygame.K_s, }) self.enemy.set_center(self.screen) self.font = pygame.font.SysFont("", 32) self.text = ''
def main(): pygame.init() display = (800, 600) pygame.display.set_mode(display, DOUBLEBUF | OPENGL) gluPerspective(45, (display[0] / display[1]), 0.1, 50.0) glTranslatef(0.0, 0.0, -5) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_q or event.key == pygame.K_ESCAPE: pygame.quit() quit() if event.key == pygame.K_LEFT: glTranslatef(-0.5, 0, 0) if event.key == pygame.K_RIGHT: glTranslatef(0.5, 0, 0) if event.key == pygame.K_UP: glTranslatef(0, 1, 0) if event.key == pygame.K_DOWN: glTranslatef(0, -1, 0) if event.type == pygame.MOUSEBUTTONDOWN: if event.button == 1: glTranslatef(0, 0, 1.0) if event.button == 3: glTranslatef(0, 0, -1.0) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) Cube() pygame.display.flip() pygame.time.wait(10)
def test(): pygame.init() screen = pygame.display.set_mode((1280, 720)) width = 1280 height = 720 pygame.display.set_caption('Dirty Blitting') a = LoadingBar(screen, 'a') loop = True b = 0 counter = 0 while loop and b<100: a.update(1) time.sleep(.2) for event in pygame.event.get(): if event.type == QUIT: loop = False elif event.type == KEYDOWN and event.key == K_ESCAPE: loop = False for i in range(3): pygame.image.save(screen, "image\image{c}.jpg" .format (c = counter)) counter += 1 b+=1 pygame.quit()
def main(): pygame.init() pygame.display.set_mode((640, 480)) pygame.display.set_caption("1") pygame.key.set_repeat(50, 50) pygame.time.set_timer(REDRAWEVENT,16) pygame.time.set_timer(UPDATEEVENT, UPDATE_TIME) pygame.time.set_timer(SPAWNEVENT, 2500) p = player.HumanPlayer("0", (255, 0, 0), (0, 0)) loop = get_loop() loop.add_object(RedrawHandler()) loop.add_object(UpdateHandler()) loop.add_object(SpawnHandler(p)) loop.add_object(PrintHandler()) loop.add_object(QuitHandler()) loop.add_object(WASDHandler(p)) loop.add_object(CleanupHandler()) loop.add_object(p, "you") loop.add_object(ProjectileCreationHandler()) loop.add_object(MouseHandler()) while True: loop.tick()
def main(): pg.init() hrl.initializeOpenGL(1024,766) dpx = hrl.initializeDPX() done = False im1 = hrl.Texture('data/alien.png') im2 = hrl.Texture('data/cow.png') #im = hrl.Texture(flatGradient(1024,766),dpx=True) #im = hrl.Texture('data/linear_rg_gradient.bmp') while not done: circleTileDraw(im1,im2) #im.draw() #im1.draw((0,0),300,300) #im1.draw((300,550),200,200) #im2.draw((550,300),200,200) #im2.draw((300,50),200,200) #im2.draw((50,300),200,200) pg.display.flip() eventlist = pg.event.get() for event in eventlist: if event.type == QUIT \ or event.type == KEYDOWN and event.key == K_ESCAPE: done = True
def __init__(self, lev_width): self.lev_width = lev_width self.mainS = pygame.display.set_mode((SCREEN_W, SCREEN_H)) self.mouse_state = SAFE self.itemGroup = pygame.sprite.Group() self.borderRectList = list() self.iconGroup = pygame.sprite.Group() self.itemExistGroup = pygame.sprite.Group() self.cam = scrollerC.Camera(scrollerC.complex_camera, \ lev_width, SCREEN_H - PANEL_H) self.straw_man = dummy.Dummy((HALF_W, HALF_W)) # DUMMY FOR CAMERA self.right_arrow = arrow.Arrow((SCREEN_W - 40 , 5), RIGHT,\ self.straw_man, self.lev_width, self.mainS) self.left_arrow = arrow.Arrow((0, 5), LEFT,\ self.straw_man, self.lev_width, self.mainS) self.curPos = (0, 0) self.clock = pygame.time.Clock() self.create_panels() self.create_icons() pygame.init()
def __init__(self, screensize = (400,400), fullscreen = False, title = 'PygameApp Window'): """ Argument to initializer is the desired screen size and/or desire for full screen """ # save copies of the creation arguments self.screensize = screensize self.fullscreen = fullscreen self.title = title # create a pygame group for tracking sprites self.spritegroup = pygame.sprite.LayeredDirty() self.elapsedms = 0 # keep track of the elapsed time pygame.init() # every pygame app must do this self.clock = pygame.time.Clock() # make a clock object to manage a frame rate # open a window different ways, depending on fullscreen setting if self.fullscreen: # find out what the current display capabilities are self.displayinfo = pygame.display.Info() self.screensize = (self.displayinfo.current_w, self.displayinfo.current_h) self.display = pygame.display.set_mode(self.screensize, FULLSCREEN) else: self.display = pygame.display.set_mode(self.screensize) # create a window pygame.display.set_caption(self.title) self.setbackgroundcolor(pygame.Color('black'))
def __init__(self, description, open_dialog, *args, **kwargs): tk.Frame.__init__(self, *args, width=WIDTH, height=HEIGHT, **kwargs) self.description = description self.render_list = [] self.objects_list = [] self.walls_list = [] self.back = (100, 100, 100) self.start_pos = None self.cursor = DemoCursor(False, False) self.open_dialog = open_dialog self.root = args[0] self.root.geometry("+100+100") self.objs_win = None self.walls_win = None self.embed = tk.Frame(root, width=640, height=480) self.embed.grid(row=0, column=2) self.root.update() os.environ['SDL_WINDOWID'] = str(self.embed.winfo_id()) if platform == 'windows': os.environ['SDL_VIDEODRIVER'] = 'windib' pygame.init() self.screen = pygame.display.set_mode((640, 480)) # pygame.display.flip() self.show_obj = tk.IntVar() self.show_walls = tk.IntVar() self.add_menu() self.root.bind('<Motion>', self.on_mouse_move) self.root.bind('<Button-1>', self.on_mouse_button)
def picture(): sock = cStringIO.StringIO() camera = highgui.cvCreateCameraCapture(0) def get_image(): #Creamos camara im = highgui.cvQueryFrame(camera) im = opencv.cvGetMat(im) return opencv.adaptors.Ipl2PIL(im) fps = 30.0 #Frames per second pygame.init() window = pygame.display.set_mode((640,480)) #Tamaño pygame.display.set_caption("Twitter") #Titulo screen = pygame.display.get_surface() #Mostramos camara while True: events = pygame.event.get() im = get_image() pg_img = pygame.image.frombuffer(im.tostring(), im.size, im.mode) screen.blit(pg_img, (0,0)) pygame.display.flip() #Flipeamos la imagen pygame.time.delay(int(1000 * 1.0/fps)) #Actualizamos frames for event in events: if event.type == KEYDOWN: if event.key == K_SPACE: #Tomamos foto con barra espaciadora pygame.image.save(pg_img, filename) img = filename xml = upload_from_computer(img) process(xml) #Enviamos a imgur sys.exit(0) #No encontre la forma de cerrar la ventana de la camara, con esto se cierra todo el programa if event.key == K_ESCAPE: #Cerramos la camara al presionar ESC sys.exit(0)
def main( update_rects=True, use_static=False, use_layered_dirty=False, screen_dims=[640, 480], use_alpha=False, flags=0, ): """Show lots of sprites moving around Optional keyword arguments: update_rects - use the RenderUpdate sprite group class (default True) use_static - include non-moving images (default False) use_layered_dirty - Use the FastRenderGroup sprite group (default False) screen_dims - Pygame window dimensions (default [640, 480]) use_alpha - use alpha blending (default False) flags - additional display mode flags (default no additional flags) """ if use_layered_dirty: update_rects = True pg.init() # needed to initialise time module for get_ticks() pg.display.init() # if "-fast" in sys.argv: screen = pg.display.set_mode(screen_dims, flags, vsync="-vsync" in sys.argv) # this is mainly for GP2X, so it can quit. pg.joystick.init() num_joysticks = pg.joystick.get_count() if num_joysticks > 0: stick = pg.joystick.Joystick(0) stick.init() # now we will receive events for the joystick screen.fill([0, 0, 0]) pg.display.flip() sprite_surface = pg.image.load(os.path.join(data_dir, "asprite.bmp")) sprite_surface2 = pg.image.load(os.path.join(data_dir, "static.png")) if use_rle: sprite_surface.set_colorkey([0xFF, 0xFF, 0xFF], pg.SRCCOLORKEY | pg.RLEACCEL) sprite_surface2.set_colorkey([0xFF, 0xFF, 0xFF], pg.SRCCOLORKEY | pg.RLEACCEL) else: sprite_surface.set_colorkey([0xFF, 0xFF, 0xFF], pg.SRCCOLORKEY) sprite_surface2.set_colorkey([0xFF, 0xFF, 0xFF], pg.SRCCOLORKEY) if use_alpha: sprite_surface = sprite_surface.convert_alpha() sprite_surface2 = sprite_surface2.convert_alpha() else: sprite_surface = sprite_surface.convert() sprite_surface2 = sprite_surface2.convert() Thingy.images = [sprite_surface] if use_static: Static.images = [sprite_surface2] if len(sys.argv) > 1: try: numsprites = int(sys.argv[-1]) except Exception: numsprites = 100 else: numsprites = 100 sprites = None if use_layered_dirty: ## sprites = pg.sprite.FastRenderGroup() sprites = pg.sprite.LayeredDirty() else: if update_rects: sprites = pg.sprite.RenderUpdates() else: sprites = pg.sprite.Group() for i in range(0, numsprites): if use_static and i % 2 == 0: sprites.add(Static()) sprites.add(Thingy()) frames = 0 start = time() background = pg.Surface(screen.get_size()) background = background.convert() background.fill([0, 0, 0]) going = True while going: if not update_rects: screen.fill([0, 0, 0]) ## for sprite in sprites: ## sprite.move() if update_rects: sprites.clear(screen, background) sprites.update() rects = sprites.draw(screen) if update_rects: pg.display.update(rects) else: pg.display.flip() for event in pg.event.get(): if event.type in [pg.QUIT, pg.KEYDOWN, pg.QUIT, pg.JOYBUTTONDOWN]: going = False frames += 1 end = time() print(f"FPS: {frames / (end - start):f}") pg.quit()
import pygame pygame.init() # 초기화 (반드시 필요) # 화면 크기 설정 screen_width = 480 # 가로 크기 screen_height = 640 screen = pygame.display.set_mode((screen_width, screen_height)) # 화면 타이틀 설정 pygame.display.set_caption("sangbeom game") # 게임 이름 # 배경 이미지 불러오기 background = pygame.image.load( "C:\\Users\아무나 사용\\Desktop\\pygame_basic\\background.png") # 캐릭터 불러오기 character = pygame.image.load( "C:\\Users\아무나 사용\\Desktop\\pygame_basic\\character.png") character_size = character.get_rect().size # 이미지의 크기를 구해옴 character_width = character_size[0] # 캐릭터의 가로 크기 character_height = character_size[1] # 캐릭터의 세로 크기 character_x_pos = (screen_width / 2) - (character_width / 2 ) # 화면 가로의 절반 크기에 해당하는 곳에 위치 character_y_pos = screen_height - character_height # 화면 세로 크기 가장 아래에 해당하는 곳에 위치 # 이동할 좌표
from tkinter import ttk import Inference_Realtime import matplotlib matplotlib.use("TkAgg") from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk from matplotlib.animation import FuncAnimation from mpl_toolkits.mplot3d import Axes3D from matplotlib import style import matplotlib.pyplot as plt from random import randint import time from matplotlib.figure import Figure import pygame import numpy as np pygame.init() pygame.joystick.init() joystick = pygame.joystick.Joystick(0) joystick.init() master = tk.Tk() master.geometry("1000x1000+900+50") per_frame = tk.Frame(master) per_frame.pack( side=tk.LEFT, padx=30, )
import sys import pygame # Pygame Init init_status = pygame.init() plansza = pygame.display.set_mode((500, 500)) while True: for event in pygame.event.get(): if event.type == pygame.KEYDOWN: print(f"ID przycisku to {event.key}") if event.key == pygame.K_ESCAPE: pygame.quit() sys.exit()
''' I have added some audio files. They will not work in repl as it does not support audio. The line numbers with audio are: lines 9, 10, 42, 565. Please un hashtag them if you are not using repl. Thank you. ''' import pygame #importing the pygame module import random pygame.init() #initialising the game #bulletsound = pygame.mixer.Sound('bulletsound.wav') #music = pygame.mixer.music.load('song.wav') screenwidth = 800 screenheight = 600 win = pygame.display.set_mode((screenwidth,screenheight)) #creating the box that the game will be in pygame.display.set_caption("Game") icon = pygame.image.load('icon.png') s1 = pygame.image.load('starfighter.png') s2 = pygame.image.load('tiefighter.png') s3 = pygame.image.load('rocketup.png') s4 = pygame.image.load('general.png') runall = True #variable that runs the game normalmode = False starwars1 = False starwars2 = False starwars3 = False displayinstruction = 0
#Entete de classes.py import pygame as pg from constantes import * import yahtzee import de pg.init() #Mise en place de la fenetre ecran = pg.display.set_mode(fen) pg.display.set_caption(nomEcran_accueil) #Images #Background background = pg.image.load(image_background).convert() background = pg.transform.scale(background, fen) #Background 2 background2 = pg.Surface(fen) background2.fill((226, 226, 224)) #Bouton Jouer bouton_jouer = pg.image.load(image_jouer).convert_alpha() bouton_jouer = pg.transform.scale(bouton_jouer, (LHbouton_jouer)) #Bouton Crédit bouton_credit = pg.image.load(image_credit).convert_alpha() bouton_credit = pg.transform.scale(bouton_credit, (LHbouton_credit)) #Bouton Retour
def main(): # permet d'utiliser ces variables en dehors du main() global PLAYWIDTH, ROWS, bras, INFOSPACE PLAYWIDTH = 500 # taile en pixel de notre fenêtre carrée INFOSPACE = 100 # taille de la baniere dinfo en pixel pygame.init() # démmare pygame pygame.key.set_repeat( 10 ) # permet de garder un touche enfoncé, avec 10 ms entre chaque entrée win = pygame.display.set_mode( (PLAYWIDTH, PLAYWIDTH + INFOSPACE)) # définition de la fenêtre bras = Arm() # instanciation bras flag = True # drapeau qui fait rouler le jeu piped_mode = True #bool pour utilisation du pipeline clock = pygame.time.Clock() # permet de gérer le temps des cycles textSpot = init_textSpot( ) #initialise les positions d'ancrages pour la baniere d<info RUNNING, PAUSE = 0, 1 #definition des etats state = RUNNING #on commence avec le jeu actif while flag: #Pour chaque événement pygame (clic, clavier,boutons) for event in pygame.event.get(): # si on a appuyé sur la croix de la fenêtre if event.type == pygame.QUIT: pygame.quit() #on quitte (met fin au programme) # ici on enregistre toutes les touches qui on été pressée pendant une itération du jeu if event.type == pygame.KEYDOWN: #si on appuie sur sur s on stop le jeu (pause) if event.key == pygame.K_s: state = PAUSE printOnce = 1 pygame.key.set_repeat(0) #si on appuie sur p on play le jeu (running) elif event.key == pygame.K_p: print("back in game") state = RUNNING pygame.key.set_repeat(10) #si on appuie sur q on quitte le jeu (+ efficace que bouton) elif event.key == pygame.K_q: pygame.quit() #Si le jeu roule if state == RUNNING: pygame.time.delay( 50) # on donne un délai de 20 ms entre chaque itération clock.tick(60) # regule le fps max #si on utilise le pipeline pour les commandes if piped_mode: line = sys.stdin.readline( ) #on lis une ligne du pipeline (libère la ligne du pipe) #Si la ligne ne contient rien on passe à la prochaine itération if not line: continue #sinon on sépare les segments de la ligne line_split = line.split() angles = list(map( float, line_split)) # extrait les angles de la ligne print("angles", angles) bras.doPose(angles) #on commande le bras avec les angles #Sinon on est en mode manuel avec le clavier else: bras.moveSegments() #on met l'interface graphique à jour redrawWindow(win, textSpot) elif state == PAUSE: if printOnce == 1: print("Game in pause") printOnce = 0
def on_init(self): pg.init() pg.display.set_caption("Pipes") self._disp = pg.display.set_mode( self.size, pg.HWSURFACE | pg.DOUBLEBUF | pg.NOFRAME) self.smallFont = pg.font.Font("fonts/Montserrat-Regular.ttf", 15) self.mediumFont = pg.font.Font("fonts/Montserrat-Regular.ttf", 25) self.largeFont = pg.font.Font("fonts/Montserrat-Regular.ttf", 40) self.close_btn = Button( x=1336, y=0, width=30, height=30, text="X", text_color=color.RED, text_accent_color=color.BLACK, bg_color=color.BLACK, bg_accent_color=color.RED, click_fn=self.stop, ) self.add_btn = Button( x=0, y=738, width=30, height=30, text="+", text_color=color.GREEN, text_accent_color=color.BLACK, bg_color=color.BLACK, bg_accent_color=color.GREEN, click_fn=self.add, ) self.obstruction_btn = Button( x=30, y=738, width=200, height=30, text="Obstruction", text_color=color.ORANGE, text_accent_color=color.BLACK, bg_color=color.BLACK, bg_accent_color=color.ORANGE, click_fn=self.obstruct, ) self.change_dir_btn = Button( x=230, y=738, width=260, height=30, text="Change direction", text_color=color.BLUE, text_accent_color=color.BLACK, bg_color=color.BLACK, bg_accent_color=color.BLUE, click_fn=self.change_dir, ) self.create_conduct_btn = Button( x=490, y=738, width=260, height=30, text="Create conduct", text_color=color.PURPLE, text_accent_color=color.BLACK, bg_color=color.BLACK, bg_accent_color=color.PURPLE, click_fn=self.conduct, ) self.create_tank_btn = Button( x=750, y=738, width=160, height=30, text="Add tank", text_color=color.YELLOW, text_accent_color=color.BLACK, bg_color=color.BLACK, bg_accent_color=color.YELLOW, click_fn=self.tank, ) self._running = True
def game(genome, config): net = neat.nn.FeedForwardNetwork.create(genome, config) pygame.init() FPSCLOCK = pygame.time.Clock() DISPLAY = pygame.display.set_mode((SCREENWIDTH, SCREENHEIGHT)) pygame.display.set_caption('Flappy Bird') global SCORE bird = Bird(DISPLAY) pipe1 = Pipe(DISPLAY, SCREENWIDTH+100) pipe2 = Pipe(DISPLAY, SCREENWIDTH+100+(SCREENWIDTH/2)) pipeGroup = pygame.sprite.Group() pipeGroup.add(pipe1.upperBlock) pipeGroup.add(pipe2.upperBlock) pipeGroup.add(pipe1.lowerBlock) pipeGroup.add(pipe2.lowerBlock) # birdGroup = pygame.sprite.Group() # birdGroup.add(bird1) moved = False time = 0 while True: DISPLAY.blit(BACKGROUND,(0,0)) if (pipe1.x < pipe2.x and pipe1.behindBird==0) or (pipe2.x < pipe1.x and pipe2.behindBird==1): input = (bird.y,pipe1.x, pipe1.upperY, pipe1.lowerY) centerY = (pipe1.upperY + pipe1.lowerY)/2 elif (pipe1.x < pipe2.x and pipe1.behindBird==1) or (pipe2.x < pipe1.x and pipe2.behindBird==0): input = (bird.y,pipe2.x, pipe2.upperY, pipe2.lowerY) centerY = (pipe2.upperY + pipe2.lowerY)/2 # print(input) vertDist = (((bird.y - centerY)**2)*100)/(512*512) time += 1 fitness = SCORE - vertDist + (time/10.0) t = pygame.sprite.spritecollideany(bird,pipeGroup) if t!=None or (bird.y== 512 - bird.height) or (bird.y == 0): # print("GAME OVER") # print("FINAL SCORE IS %d"%fitness) return(fitness) output = net.activate(input) for event in pygame.event.get(): if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE): pygame.quit() sys.exit() if output[0]>=0.5: bird.move("UP") moved = True if moved == False: bird.move(None) else: moved = False pipe1Pos = pipe1.move() if pipe1Pos[0] <= int(SCREENWIDTH * 0.2) - int(bird.rect.width/2): if pipe1.behindBird == 0: pipe1.behindBird = 1 SCORE += 10 print("SCORE IS %d"%(SCORE+vertDist)) pipe2Pos = pipe2.move() if pipe2Pos[0] <= int(SCREENWIDTH * 0.2) - int(bird.rect.width/2): if pipe2.behindBird == 0: pipe2.behindBird = 1 SCORE += 10 print("SCORE IS %d"%(SCORE+vertDist)) pygame.display.update() FPSCLOCK.tick(FPS)
def run(self): pg.init() self.screen = pg.display.set_mode(SCREEN_RES) pg.display.set_caption('Sudoku solver') display = Display_board(self.screen) val = 0 blink = False alpha = 1 a_change = True blink_color = GREEN candidates = [] get_cord(INITIAL_CORDS) set_highlight(INITIAL_CORDS, INITIAL_CORDS, INITIAL_CORDS, INITIAL_LOCK) board = create_board().board while 1: for event in pg.event.get(): if event.type == pg.QUIT or (event.type == pg.KEYDOWN and event.key == pg.K_ESCAPE): exit() if event.type == pg.MOUSEBUTTONDOWN and input_lock != 1: pos = pg.mouse.get_pos() get_cord(pos) # Checks if selection is on the board if pos[0] < TOP_LX or pos[1] < TOP_LY or pos[0] > int(BOT_RX) or pos[1] > int(BOT_RY): blink = False else: blink = True if event.type == pg.KEYDOWN and input_lock != 1: if event.key == pg.K_1: val = 1 if event.key == pg.K_2: val = 2 if event.key == pg.K_3: val = 3 if event.key == pg.K_4: val = 4 if event.key == pg.K_5: val = 5 if event.key == pg.K_6: val = 6 if event.key == pg.K_7: val = 7 if event.key == pg.K_8: val = 8 if event.key == pg.K_9: val = 9 if event.key == pg.K_BACKSPACE: board[int(box_index_x)][int(box_index_y)] = 0 elif event.type == pg.KEYDOWN and input_lock == 1: if event.key == pg.K_BACKSPACE: val = 0 set_highlight(INITIAL_CORDS, INITIAL_CORDS, INITIAL_CORDS, INITIAL_LOCK) blink_color = GREEN board[int(box_index_x)][int(box_index_y)] = 0 if val != 0: # display.draw_val(val, box_index_x, box_index_y) board_index = board[int(box_index_x)][int(box_index_y)] if valid(board, int(box_index_x), int(box_index_y), val) and board[int(box_index_x)][int(box_index_y)] != 0: if type(board_index) = int: board[int(box_index_x)][int(box_index_y)] = val board[int(box_index_x)][int(box_index_y)].append(val) elif valid(board, int(box_index_x), int(box_index_y), val): board[int(box_index_x)][int(box_index_y)] = val else: board[int(box_index_x)][int(box_index_y)] = val # Draws the screen pg.draw.rect(self.screen, BLACK, (0, 0, self.screen.get_width(), self.screen.get_height())) self.screen.fill(BEIGE) # Draws the board display.draw(board) # Check if cell is selected if blink: cell = display.find_cell(box_index_x, box_index_y) blink = display.blink(alpha, a_change) alpha = blink[0] a_change = blink[1] myRect = pg.Rect(cell) rectSurf = pg.Surface(myRect.size, pg.SRCALPHA) rectSurf.fill(blink_color) rectSurf.set_alpha(alpha) self.screen.blit(rectSurf, (myRect.x, myRect.y)) # Check if incorrect input if input_lock == 1 and val != 0: display.update(board, row_index, col_index, blk_index) blink_color = RED val = 0 # display.draw_box() pg.display.update()
def main(self): pygame.init() # ikona pygame.display.set_icon(pygame.image.load('utilities\icon.png')) # tytul okna pygame.display.set_caption('PPassage') # obiekt odpowiedzialny za stan gry i poziom trudnosci objState = GameStates() while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() # tytul gry na glownym ekranie WelcomeScreen.showTitle(self) # przyciski if objState.STATE == 'WelcomeMenu' and self.WELCOMEMENU: if button(self, 'Start', self.FONTSIZE, self.BUTTONDISTANCEX, self.BUTTONDOWNY - (3*self.BUTTONHEIGHT + 3*50), self.BUTTONWIDTH, self.BUTTONHEIGHT): WelcomeScreen.buttonAction(self, 'Start', objState) if button(self, 'Difficulty', self.FONTSIZE, self.BUTTONDISTANCEX, self.BUTTONDOWNY - (2*self.BUTTONHEIGHT + 2*50), self.BUTTONWIDTH, self.BUTTONHEIGHT): WelcomeScreen.buttonAction(self, 'Difficulty', objState) if button(self, 'High Scores', self.FONTSIZE, self.BUTTONDISTANCEX, self.BUTTONDOWNY - (self.BUTTONHEIGHT + 50), self.BUTTONWIDTH, self.BUTTONHEIGHT): WelcomeScreen.buttonAction(self, 'HighScores', objState) if button(self, 'Quit', self.FONTSIZE, self.BUTTONDISTANCEX, self.BUTTONDOWNY, self.BUTTONWIDTH, self.BUTTONHEIGHT): WelcomeScreen.buttonAction(self, 'Quit', objState) elif objState.STATE == 'DiffMenu' and self.DIFFMENU: # napis 'Difficulty' font = pygame.font.Font(self.FONTNAME, self.FONTSIZE+10) textSurf = font.render('Difficulty', True, WHITE) textRect = textSurf.get_rect() textRect.center = ( self.HALFWIDTH, self.HALFHEIGHT - self.BUTTONHEIGHT - 100 ) self.displaySurface.blit(textSurf, textRect) if button(self, 'Easy', self.FONTSIZE, (self.WIDTH - self.BUTTONWIDTH)/2, self.HALFHEIGHT - self.BUTTONHEIGHT - 50, self.BUTTONWIDTH, self.BUTTONHEIGHT): WelcomeScreen.buttonAction(self, 'Easy', objState) if button(self, 'Medium', self.FONTSIZE, (self.WIDTH - self.BUTTONWIDTH)/2, self.HALFHEIGHT, self.BUTTONWIDTH, self.BUTTONHEIGHT): WelcomeScreen.buttonAction(self, 'Medium', objState) if button(self, 'Hard', self.FONTSIZE, (self.WIDTH - self.BUTTONWIDTH)/2, self.HALFHEIGHT + self.BUTTONHEIGHT + 50, self.BUTTONWIDTH, self.BUTTONHEIGHT): WelcomeScreen.buttonAction(self, 'Hard', objState) if button(self, 'Back to menu', self.FONTSIZE, self.BUTTONDISTANCEX, self.BUTTONDOWNY, self.BUTTONWIDTH, self.BUTTONHEIGHT): WelcomeScreen.buttonAction(self, 'BackMenu', objState) # napis 'Mode' font = pygame.font.Font(self.FONTNAME, self.FONTSIZE+2) textSurf = font.render('Mode', True, WHITE) textRect = ( (self.HALFWIDTH + self.HALFWIDTH/2 + 12 + 20), (self.HALFHEIGHT - 75) ) self.displaySurface.blit(textSurf, textRect) if checkButton(self, 'Classic', self.FONTSIZE, self.HALFWIDTH + self.HALFWIDTH/2, self.HALFHEIGHT ): WelcomeScreen.buttonAction(self, 'Classic', objState) if checkButton(self, 'Continuous', self.FONTSIZE, self.HALFWIDTH + self.HALFWIDTH/2, self.HALFHEIGHT + 50): WelcomeScreen.buttonAction(self, 'Continuous', objState) mode = objState.getMode() if mode == 'Classic': WelcomeScreen.drawCheckBox(self, self.HALFWIDTH + self.HALFWIDTH/2, self.HALFHEIGHT ) elif mode == 'Continuous': WelcomeScreen.drawCheckBox(self, self.HALFWIDTH + self.HALFWIDTH/2, self.HALFHEIGHT + 50) diff = objState.getDifficulty() if diff == 'Easy': WelcomeScreen.drawselectedButton(self, 'Easy', self.FONTSIZE+2, (self.WIDTH - self.BUTTONWIDTH)/2, self.HALFHEIGHT - self.BUTTONHEIGHT - 50, self.BUTTONWIDTH, self.BUTTONHEIGHT) elif diff == 'Medium': WelcomeScreen.drawselectedButton(self, 'Medium', self.FONTSIZE+2, (self.WIDTH - self.BUTTONWIDTH)/2, self.HALFHEIGHT, self.BUTTONWIDTH, self.BUTTONHEIGHT) elif diff == 'Hard': WelcomeScreen.drawselectedButton(self, 'Hard', self.FONTSIZE+2, (self.WIDTH - self.BUTTONWIDTH)/2, self.HALFHEIGHT + self.BUTTONHEIGHT + 50, self.BUTTONWIDTH, self.BUTTONHEIGHT) else: print('Wrong DIFFICULTY name') elif objState.STATE == 'ScoreMenu' and self.SCOREMENU: # wyswietla osiagniete wyniki showHighScore(self) if button(self, 'Back to menu', self.FONTSIZE, self.BUTTONDISTANCEX, self.BUTTONDOWNY, self.BUTTONWIDTH, self.BUTTONHEIGHT): WelcomeScreen.buttonAction(self, 'BackMenu', objState) pygame.display.update()
def main(): pygame.init() screen = pygame.display.set_mode((640, 480)) clock = pygame.time.Clock() x_curser1 = 160 y_curser1 = 240 x_curser2 = 480 y_curser2 = 240 mode = '' count = 0 radius = 10 screen.fill((0, 0, 0)) color_curser1 = (0, 255, 0) color_curser2 = (0, 255, 0) pygame.draw.circle(screen, color_curser1, (x_curser1, y_curser1), radius) pygame.draw.circle(screen, color_curser2, (x_curser2, y_curser2), radius) arm = armtakeoff() arm.arm() arm.takeoff() while True: screen.fill((0, 0, 0)) x_curser1 = 160 y_curser1 = 240 x_curser2 = 480 y_curser2 = 240 pressed = pygame.key.get_pressed() alt_held = pressed[pygame.K_LALT] or pressed[pygame.K_RALT] ctrl_held = pressed[pygame.K_LCTRL] or pressed[pygame.K_RCTRL] for event in pygame.event.get(): # determin if X was clicked, or Ctrl+W or Alt+F4 was used if event.type == pygame.QUIT: return if event.type == pygame.KEYDOWN: if event.key == pygame.K_w and ctrl_held: return if event.key == pygame.K_F4 and alt_held: return if event.key == pygame.K_ESCAPE: return # determine if a letter key was pressed if event.key == pygame.K_w: mode = 'up' elif event.key == pygame.K_s: mode = 'down' elif event.key == pygame.K_d: mode = 'right' elif event.key == pygame.K_a: mode = 'left' elif event.key == pygame.K_SPACE: mode = 'jump' elif event.key == pygame.K_q: mode = 'yaw' elif event.key == pygame.K_e: mode = 'yawri8' elif event.key == pygame.K_LCTRL: mode = 'low' elif event.key == pygame.K_h: mode = 'hold' color_curser1 = (255, 0, 0) color_curser2 = (255, 0, 0) color_curser3 = (0, 0, 255) color_curser4 = (0, 0, 255) pygame.draw.circle(screen, color_curser1, (x_curser1, y_curser1), radius) pygame.draw.circle(screen, color_curser2, (x_curser2, y_curser2), radius) x_curser1, y_curser1, x_curser2, y_curser2 = curserControl( screen, x_curser1, y_curser1, x_curser2, y_curser2, mode, count, color_curser1, color_curser1, radius) pygame.draw.circle(screen, color_curser3, (x_curser1, y_curser1), radius) pygame.draw.circle(screen, color_curser4, (x_curser2, y_curser2), radius) pygame.display.flip() clock.tick(60)
def main(): pygame.init() pygame.display.set_mode((0, 0), pygame.RESIZABLE) game = ExamGame() game.run()
def play(self): pygame.init() pygame.font.init() font = pygame.font.SysFont('Arial', 18) textsurface = font.render('', False, (0, 0, 0)) screen = pygame.display.set_mode((800, 800)) pygame.display.set_caption('Lau kata kati') background = pygame.image.load('assets/board.png').convert() white = pygame.image.load('assets/white.png') black = pygame.image.load('assets/black.png') clock = pygame.time.Clock() self.create_pawns() while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() if self.next_move == 'white': if event.type == pygame.MOUSEBUTTONDOWN and not self.done: self.done = True xMouse = event.pos[0] yMouse = event.pos[1] #print(xMouse, yMouse) # clicked_white = [p for p in white_pawns if p.rect.collidepoint(xMouse, yMouse)] # clicked_black = [p for p in black_pawns if p.rect.collidepoint(xMouse, yMouse)] index = None for p in self.white_pawns: if p.rect.collidepoint(xMouse, yMouse): self.clicked_white.append(p) index = self.white_pawns.index(p) if len(self.clicked_white) == 1: print('BIAŁY ZŁAPANY') clicked_pawn = self.clicked_white[0] self.color = 0 textsurface = font.render('', False, (0, 0, 0)) else: self.done = False textsurface = font.render('Pionek wybrany niepoprawnie!', False, (0, 0, 0)) elif event.type == pygame.MOUSEBUTTONDOWN and self.done: self.done = False xMouse2 = event.pos[0] yMouse2 = event.pos[1] # clicked_pawn.x = xMouse2 # clicked_pawn.y = yMouse2 if self.move(xMouse, yMouse, xMouse2, yMouse2): if self.color == 0: self.white_pawns[index].x = xMouse2 self.white_pawns[index].y = yMouse2 self.white_pawns[index].rect.center = (xMouse2, yMouse2) elif self.color == 1: self.black_pawns[index].x = xMouse2 self.black_pawns[index].y = yMouse2 self.black_pawns[index].rect.center = (xMouse2, yMouse2) textsurface = font.render('', False, (0, 0, 0)) else: textsurface = font.render('Niepoprawny ruch!', False, (0, 0, 0)) #for whitepawn in self.white_pawns: #print(whitepawn.x, whitepawn.y) #print() #for blackpawn in self.black_pawns: #print(blackpawn.x, blackpawn.y) # clicked_pawn.rect.center = (clicked_pawn.x, clicked_pawn.y) self.clicked_white = [] self.clicked_black = [] elif self.next_move == 'black': miN = 100 eval = self.minmax(3, 'black', self.board, -math.inf, math.inf) for element in self.evaluated_boards: #print('ELEMENT: ', element[0]) if element[1] == eval: self.board = element[0] self.evaluated_boards = [] break # for element in self.evaluated_boards: # if element[1] < miN: # miN = element[1] # # print('MIN: ', miN) # # for x in self.evaluated_boards: # if x[1] == miN: # self.board = x[0] # self.evaluated_boards = [] # break self.color = 1 self.next_move = 'white' # for p in self.black_pawns: # if p.rect.collidepoint(xMouse, yMouse): # self.clicked_black.append(p) # index = self.black_pawns.index(p) # if len(self.clicked_black) == 1: # print('CZARNY HEHE ZŁAPANY') # clicked_pawn = self.clicked_black[0] # self.color = 1 # textsurface = font.render('', False, (0, 0, 0)) # else: # self.done = False # textsurface = font.render('Pionek wybrany niepoprawnie!', False, (0, 0, 0)) # for pawn in white_pawns: # print(pawn.x, pawn.y) # if pawn.rect.collidepoint(xMouse, yMouse): # pawn.x = xMouse # pawn.y = yMouse # pawn.rect.center = (pawn.x, pawn.y) screen.blit(background, (0, 0)) screen.blit(textsurface, (0, 0)) # for pawn in black_pawns: # screen.blit(pawn.image, (pawn.x-32.5, pawn.y-32.5)) # # for pawn in white_pawns: # screen.blit(pawn.image, (pawn.x-32.5, pawn.y-32.5)) for x in range(len(self.board)): if self.board[x] == 'white': screen.blit(white, (self.fields_pos[x][0] - 32.5, self.fields_pos[x][1] - 32.5)) elif self.board[x] == 'black': screen.blit(black, (self.fields_pos[x][0] - 32.5, self.fields_pos[x][1] - 32.5)) # if pawn == 'white': # print(x) # screen.blit(white, (fields_pos[x][0]-32.5, fields_pos[x][1]-32.5)) # elif pawn == 'black': # print(x) # screen.blit(black, (fields_pos[x][0] - 32.5, fields_pos[x][1] - 32.5)) print(self.board) pygame.display.update() clock.tick(60) time.sleep(0.5)
def main(): global state global grid global found_end blue_gradient = [0, 0, 123] pygame.init() pygame.font.init() screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) # serch stuff start_node = [] target_node = [] # Grid for row in range(ROW): for column in range(COLUMN): grid.append([row, column, 0]) # Clock clock = pygame.time.Clock() # Draw initial, thigs that dont change screen.fill(BLACK) font = pygame.font.SysFont('Comic Sans Ms', 30) # Reset button pygame.draw.rect(screen, BLUE, [850, 100, 100, 50]) txt_reset = font.render('Reset', False, WHITE) screen.blit(txt_reset, (850, 100)) # Start search button pygame.draw.rect(screen, BLUE, [850, 200, 100, 50]) txt_reset = font.render('Start', False, WHITE) screen.blit(txt_reset, (850, 200)) # Search stuff frontier = collections.deque() came_from = dict() # Game running loop running = True mouse_down = False biggest_diff = 0 while running: # Handle events for event in pygame.event.get(): # Quitting the game if event.type == QUIT: running = False elif event.type == KEYDOWN: if event.key == K_ESCAPE: running = False # Mouse handling elif event.type == MOUSEBUTTONDOWN: mouse_down = True pos = pygame.mouse.get_pos() # Reset button check if pos[0] >= 850 and pos[0] <= 950 and pos[1] >= 100 and pos[ 1] <= 150: Reset_Grid(frontier, came_from) continue # Reset button check if pos[0] >= 850 and pos[0] <= 950 and pos[1] >= 200 and pos[ 1] <= 250 and state == States.SET_BLOCK: state = States.START_SEARCH add_all_nodes() continue # Grid cells check row = int(pos[1] // (CELL_WIDTH + MARGIN)) column = int(pos[0] // (CELL_HEIGHT + MARGIN)) if row >= ROW or column >= COLUMN or node[2] != 0: continue node = grid[column + (row * ROW)] set_mode = 0 if state == States.SET_START: set_mode = 1 state = States.SET_END start_node = [row, column, 1] frontier.append([start_node[0], start_node[1]]) came_from[str([start_node[0], start_node[1]])] = None # neighbours.append(pos_start) elif state == States.SET_END: if grid[column + (row * ROW)][2] != 0: continue set_mode = 2 state = States.SET_BLOCK target_node = [row, column, 2] elif state == States.SET_BLOCK: set_mode = 3 node[2] = set_mode elif event.type == MOUSEBUTTONUP: mouse_down = False elif event.type == MOUSEMOTION and state == States.SET_BLOCK and mouse_down: # Calculate the indexes, and leve if out of bounds pos = pygame.mouse.get_pos() row = int(pos[1] // (CELL_WIDTH + MARGIN)) column = int(pos[0] // (CELL_HEIGHT + MARGIN)) if row >= ROW or column >= COLUMN: continue node = grid[column + (row * ROW)] if node[2] == 0: node[2] = 3 #the algo if state == States.START_SEARCH: if len(frontier) != 0: current = frontier.popleft() if grid[current[1] + (current[0] * ROW)][2] == 2: found_end = True if grid[current[1] + (current[0] * ROW)][2] == 4: grid[current[1] + (current[0] * ROW)][2] = 5 for next in neighbours(current): # if [next[0], next[1], 2] == target_node: if str(next) not in came_from: frontier.append(next) came_from[str(next)] = current if grid[next[1] + (next[0] * ROW)][2] == 0: grid[next[1] + (next[0] * ROW)][2] = 4 else: show_result(start_node, target_node, came_from) # Screen drawing for row in range(ROW): for column in range(COLUMN): color = WHITE node = grid[column + (row * ROW)] if node[2] == 1: color = RED if node[2] == 2: color = GREEN if node[2] == 3: color = GREY if node[2] == 4: color = (12, 245, 20) if node[2] == 5: diff = (start_node[0] - node[0]) + (start_node[1] - node[1]) if abs(diff) > biggest_diff: biggest_diff = abs(diff) print(biggest_diff) step_colour = blue_gradient step_colour[0] = abs( int(diff * (255 / (ROW - 1 + ROW - 1 - 1)))) color = step_colour if node[2] == 6: color = BLACK pygame.draw.rect(screen, color, [(MARGIN + CELL_WIDTH) * column + MARGIN, (MARGIN + CELL_HEIGHT) * row + MARGIN, CELL_WIDTH, CELL_HEIGHT]) clock.tick(120) pygame.display.update() quit()
def run_game(): global bullets_die,turn,computer_health,reserve pygame.init() ai_settings =Settings() screen = pygame.display.set_mode((ai_settings.screen_width, ai_settings.screen_height)) pygame.display.set_caption('Alien Invasion') ship = Ship(ai_settings,screen) bullets = Group() aliens = Group() # print(alien.rect.y) # aliens.add(alien) bg_color = (20,250,200) while True: # print(alien.rect.y) tre = randint(-100,1005) for event in pygame.event.get(): #for event in pygame.event.get(): if event.type == pygame.MOUSEBUTTONDOWN: mouse_x,mouse_y = pygame.mouse.get_pos() ship.senter = mouse_x if event.type == pygame.KEYDOWN: if event.key == pygame.K_1: first = randint(0,220) second = randint(0,220) three = randint(0,220) ai_settings.bg_color = (first,second,three) if event.key == pygame.K_n: run(ship,turn) if event.key == pygame.K_b: sys.exit() if event.key == pygame.K_RIGHT: ship.movin_right = True turn = 0 if event.key == pygame.K_SPACE: # if len(bullets) < ai_settings.bullet_allowed: new_bullet = Bullet(ai_settings,screen,ship) bullets.add(new_bullet) if event.key == pygame.K_LEFT: ship.movin_left = True turn = 1 elif event.type == pygame.KEYUP: if event.key == pygame.K_RIGHT: ship.movin_right = False if event.key == pygame.K_LEFT: ship.movin_left = False ship.update() for bullet in bullets.copy(): if bullet.rect.y <= 0 and bullet.tre == 0: bullet.turn = 1 bullet.tre = 1 aliens.add(bullet) # new_pos(Bullet,bullets,ai_settings,screen) screen.fill(ai_settings.bg_color) for bullet in bullets.sprites(): bullet.draw_bullet() first = randint(0,200) second = randint(0,200) three = randint(0,200) ai_settings.bullet_color = (first,second,three) if pygame.sprite.spritecollideany(bullet,aliens): bullet.turn = 1 aliens.add(bullet) # new_pos(Bullet,bullets,ai_settings,screen) ship.blitme() bullets.update() #chek_fleet_edges(ai_settings,aliens) #aliens.update() pygame.display.flip()
def main(): # 初始化pygame pygame.init() fpsClock = pygame.time.Clock() # 创建pygame显示层 playSurface = pygame.display.set_mode((640,480)) pygame.display.set_caption('Raspberry Snake') # 初始化变量 snakePosition = [100,100] snakeSegments = [[100,100],[80,100],[60,100]] raspberryPosition = [300,300] raspberrySpawned = 1 direction = 'right' changeDirection = direction while True: # 检测例如按键等pygame事件 for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() elif event.type == KEYDOWN: # 判断键盘事件 if event.key == K_RIGHT or event.key == ord('d'): changeDirection = 'right' if event.key == K_LEFT or event.key == ord('a'): changeDirection = 'left' if event.key == K_UP or event.key == ord('w'): changeDirection = 'up' if event.key == K_DOWN or event.key == ord('s'): changeDirection = 'down' if event.key == K_ESCAPE: pygame.event.post(pygame.event.Event(QUIT)) # 判断是否输入了反方向 if changeDirection == 'right' and not direction == 'left': direction = changeDirection if changeDirection == 'left' and not direction == 'right': direction = changeDirection if changeDirection == 'up' and not direction == 'down': direction = changeDirection if changeDirection == 'down' and not direction == 'up': direction = changeDirection # 根据方向移动蛇头的坐标 if direction == 'right': snakePosition[0] += 20 if direction == 'left': snakePosition[0] -= 20 if direction == 'up': snakePosition[1] -= 20 if direction == 'down': snakePosition[1] += 20 # 增加蛇的长度 snakeSegments.insert(0,list(snakePosition)) # 判断是否吃掉了树莓 if snakePosition[0] == raspberryPosition[0] and snakePosition[1] == raspberryPosition[1]: raspberrySpawned = 0 else: snakeSegments.pop() # 如果吃掉树莓,则重新生成树莓 if raspberrySpawned == 0: x = random.randrange(1,32) y = random.randrange(1,24) raspberryPosition = [int(x*20),int(y*20)] raspberrySpawned = 1 # 绘制pygame显示层 playSurface.fill(blackColour) for position in snakeSegments: pygame.draw.rect(playSurface,whiteColour,Rect(position[0],position[1],20,20)) pygame.draw.rect(playSurface,redColour,Rect(raspberryPosition[0], raspberryPosition[1],20,20)) # 刷新pygame显示层 pygame.display.flip() # 判断是否死亡 if snakePosition[0] > 620 or snakePosition[0] < 0: gameOver(playSurface) if snakePosition[1] > 460 or snakePosition[1] < 0: for snakeBody in snakeSegments[1:]: if snakePosition[0] == snakeBody[0] and snakePosition[1] == snakeBody[1]: gameOver(playSurface) # 控制游戏速度 fpsClock.tick(5)
def main(): global FPSCLOCK, DISPLAYSURF, BASICFONT, RESET_SURF, RESET_RECT, NEW_SURF, NEW_RECT, SOLVE_SURF, SOLVE_RECT pygame.init() FPSCLOCK = pygame.time.Clock() DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT)) pygame.display.set_caption('Slide Puzzle') BASICFONT = pygame.font.Font('freesansbold.ttf', BASICFONTSIZE) # Store the option buttons and their rectangles in OPTIONS. RESET_SURF, RESET_RECT = makeText('Reset', TEXTCOLOR, TILECOLOR, WINDOWWIDTH - 120, WINDOWHEIGHT - 90) NEW_SURF, NEW_RECT = makeText('New Game', TEXTCOLOR, TILECOLOR, WINDOWWIDTH - 120, WINDOWHEIGHT - 60) SOLVE_SURF, SOLVE_RECT = makeText('Solve', TEXTCOLOR, TILECOLOR, WINDOWWIDTH - 120, WINDOWHEIGHT - 30) mainBoard, solutionSeq = generateNewPuzzle(80) SOLVEDBOARD = getStartingBoard( ) # a solved board is the same as the board in a start state. allMoves = [] # list of moves made from the solved configuration while True: # main game loop slideTo = None # the direction, if any, a tile should slide msg = '' # contains the message to show in the upper left corner. if mainBoard == SOLVEDBOARD: msg = 'Solved!' drawBoard(mainBoard, msg) checkForQuit() for event in pygame.event.get(): # event handling loop if event.type == MOUSEBUTTONUP: spotx, spoty = getSpotClicked(mainBoard, event.pos[0], event.pos[1]) if (spotx, spoty) == (None, None): # check if the user clicked on an option button if RESET_RECT.collidepoint(event.pos): resetAnimation(mainBoard, allMoves) # clicked on Reset button allMoves = [] elif NEW_RECT.collidepoint(event.pos): mainBoard, solutionSeq = generateNewPuzzle( 80) # clicked on New Game button allMoves = [] elif SOLVE_RECT.collidepoint(event.pos): resetAnimation(mainBoard, solutionSeq + allMoves) # clicked on Solve button allMoves = [] else: # check if the clicked tile was next to the blank spot blankx, blanky = getBlankPosition(mainBoard) if spotx == blankx + 1 and spoty == blanky: slideTo = LEFT elif spotx == blankx - 1 and spoty == blanky: slideTo = RIGHT elif spotx == blankx and spoty == blanky + 1: slideTo = UP elif spotx == blankx and spoty == blanky - 1: slideTo = DOWN elif event.type == KEYUP: # check if the user pressed a key to slide a tile if event.key in (K_LEFT, K_a) and isValidMove(mainBoard, LEFT): slideTo = LEFT elif event.key in (K_RIGHT, K_d) and isValidMove( mainBoard, RIGHT): slideTo = RIGHT elif event.key in (K_UP, K_w) and isValidMove(mainBoard, UP): slideTo = UP elif event.key in (K_DOWN, K_s) and isValidMove( mainBoard, DOWN): slideTo = DOWN if slideTo: slideAnimation(mainBoard, slideTo, 'Click tile or press arrow keys to slide.', 8) # show slide on screen makeMove(mainBoard, slideTo) allMoves.append(slideTo) # record the slide pygame.display.update() FPSCLOCK.tick(FPS)
""" pipeHeight = GAME_SPRITES['pipe'][0].get_height() offset = SCREENHEIGHT / 3 y2 = offset + random.randrange(0, int(SCREENHEIGHT - GAME_SPRITES['base'].get_height() - 1.2 * offset)) pipeX = SCREENWIDTH + 10 y1 = pipeHeight - y2 + offset pipe = [ {'x': pipeX, 'y': -y1}, # upper Pipe {'x': pipeX, 'y': y2} # lower Pipe ] return pipe if __name__ == "__main__": # This will be the main point from where our game will start pygame.init() # Initialize all pygame's modules FPSCLOCK = pygame.time.Clock() pygame.display.set_caption('Flappy Bird by MJ') GAME_SPRITES['numbers'] = ( pygame.image.load('gallery/sprites/0.png').convert_alpha(), pygame.image.load('gallery/sprites/1.png').convert_alpha(), pygame.image.load('gallery/sprites/2.png').convert_alpha(), pygame.image.load('gallery/sprites/3.png').convert_alpha(), pygame.image.load('gallery/sprites/4.png').convert_alpha(), pygame.image.load('gallery/sprites/5.png').convert_alpha(), pygame.image.load('gallery/sprites/6.png').convert_alpha(), pygame.image.load('gallery/sprites/7.png').convert_alpha(), pygame.image.load('gallery/sprites/8.png').convert_alpha(), pygame.image.load('gallery/sprites/9.png').convert_alpha(), )
def main(test=False): """ Main program. :param test: Indicate function is being tested :type test: bool :return: None """ # ------------------------------------------------------------------------- # Init pygame # ------------------------------------------------------------------------- pygame.init() os.environ['SDL_VIDEO_CENTERED'] = '1' # Write help message on console for m in HELP: print(m) # Create window global surface surface = pygame.display.set_mode((W_SIZE, H_SIZE)) pygame.display.set_caption('Example - Timer Clock') # Main timer and game clock clock = pygame.time.Clock() global timer timer = [0.0] dt = 1.0 / FPS timer_font = pygameMenu.font.get_font(pygameMenu.font.FONT_NEVIS, 100) # ------------------------------------------------------------------------- # Create menus # ------------------------------------------------------------------------- # Timer timer_menu = pygameMenu.Menu(surface, dopause=False, font=pygameMenu.font.FONT_NEVIS, menu_alpha=85, menu_color=(0, 0, 0), # Background color menu_color_title=(0, 0, 0), menu_height=int(H_SIZE * 0.65), menu_width=600, # If this menu closes (ESC) back to main onclose=pygameMenu.events.RESET, option_shadow=True, rect_width=4, title='Timer Menu', title_offsety=5, # Adds 5px to title vertical position window_height=H_SIZE, window_width=W_SIZE ) # Add options timer_menu.add_option('Reset timer', reset_timer) # Adds a selector (element that can handle functions) timer_menu.add_selector('Change bgcolor', # Values of selector, call to change_color_bg [('Random', (-1, -1, -1)), ('Default', (128, 0, 128)), ('Black', (0, 0, 0)), ('Blue', COLOR_BLUE)], # Optional parameter that sets default item of selector default=1, # Action when changing element with left/right onchange=change_color_bg, # Action when pressing return on an element onreturn=change_color_bg, # Optional parameters to change_color_bg function write_on_console=True ) timer_menu.add_option('Update game object', TestCallClassMethod().update_game_settings) timer_menu.add_option('Return to Menu', pygameMenu.events.BACK) timer_menu.add_option('Close Menu', pygameMenu.events.CLOSE) # Help menu help_menu = pygameMenu.TextMenu(surface, dopause=False, font=pygameMenu.font.FONT_FRANCHISE, menu_color=(30, 50, 107), # Background color menu_color_title=(120, 45, 30), # Pressing ESC button does nothing onclose=pygameMenu.events.DISABLE_CLOSE, option_shadow=True, option_shadow_position=pygameMenu.locals.POSITION_SOUTHEAST, text_align=pygameMenu.locals.ALIGN_CENTER, title='Help', window_height=H_SIZE, window_width=W_SIZE ) help_menu.add_option('Return to Menu', pygameMenu.events.BACK) for m in HELP: help_menu.add_line(m) # About menu about_menu = pygameMenu.TextMenu(surface, dopause=False, draw_text_region_x=5, # 5% margin font=pygameMenu.font.FONT_NEVIS, font_size_title=30, font_title=pygameMenu.font.FONT_8BIT, menu_color_title=COLOR_BLUE, mouse_visible=False, # Disable menu close (ESC button) onclose=pygameMenu.events.DISABLE_CLOSE, option_shadow=True, text_fontsize=20, title='About', window_height=H_SIZE, window_width=W_SIZE ) about_menu.add_option('Return to Menu', pygameMenu.events.BACK) for m in ABOUT: about_menu.add_line(m) about_menu.add_line(pygameMenu.locals.TEXT_NEWLINE) # Main menu, pauses execution of the application main_menu = pygameMenu.Menu(surface, bgfun=mainmenu_background, enabled=False, font=pygameMenu.font.FONT_NEVIS, menu_alpha=90, fps=FPS, onclose=pygameMenu.events.CLOSE, title='Main Menu', title_offsety=5, window_height=H_SIZE, window_width=W_SIZE ) main_menu.add_option(timer_menu.get_title(), timer_menu) # Add timer submenu main_menu.add_option(help_menu.get_title(), help_menu) # Add help submenu main_menu.add_option(about_menu.get_title(), about_menu) # Add about submenu main_menu.add_option('Exit', pygameMenu.events.EXIT) # Add exit function # ------------------------------------------------------------------------- # Main loop # ------------------------------------------------------------------------- while True: # Tick clock clock.tick(FPS) timer[0] += dt # Paint background surface.fill(COLOR_BACKGROUND) # Application events events = pygame.event.get() for event in events: if event.type == pygame.QUIT: exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: main_menu.enable() # Draw timer time_string = str(datetime.timedelta(seconds=int(timer[0]))) time_blit = timer_font.render(time_string, 1, COLOR_WHITE) time_blit_size = time_blit.get_size() surface.blit(time_blit, ( W_SIZE / 2 - time_blit_size[0] / 2, H_SIZE / 2 - time_blit_size[1] / 2)) # Execute main from principal menu if is enabled main_menu.mainloop(events, disable_loop=test) # Flip surface pygame.display.flip() # At first loop returns if test: break
def main(): conf = KarIO.ClassifConf() ### prepare a csv file to save the results ########## result_file = open( os.path.join("shapeCateg-" + conf.user + "-" + conf.slide + "-" + conf.metaphases_list[0] + "-" + conf.counterstain + '.csv'), 'w') result = csv.writer(result_file, delimiter=';', lineterminator='\n') row = [] ########### pygame.init() screen = pygame.display.set_mode(conf.screensize) metaphaseList = conf.metaphases_list print metaphaseList[0] conf.set_particlespath(0) print conf.path conf.set_particles(conf.path) print "conf.particlesList", conf.particlesList pygame.display.set_caption("Karyotyper") pygame.mouse.set_visible(True) background = pygame.Surface(screen.get_size()) background = background.convert() background.fill((0, 100, 0)) screen.blit(background, (0, 0)) pygame.display.flip() imagesList = [] for i in conf.particlesList: im = load_image(os.path.join(conf.path, i)) imagesList.append(im) print len(imagesList) i1 = load_image( "/home/claire/Applications/ImagesTest/jp/Jpp48/13/DAPI/particles/part15.png", -1) i2 = load_image( "/home/claire/Applications/ImagesTest/jp/Jpp48/13/DAPI/particles/part12.png", -1) chrList = [] n = 0 li = 20 col = 0 for c in imagesList: chrList.append(Ichrom(c, conf.particlesList[n], (col, li))) print conf.particlesList[n] n = n + 1 col = col + 20 #li= #chr0= Ichrom(ima) chr1 = Ichrom(i1, "part15", (0, 0)) #chr1 = Krom(i1,(0,0)) chr2 = Ichrom(i2, "part12", (30, 30)) #chr2=Krom(i2,(30,30)) print "---------classif---------------" print conf.catlist[0] print type(conf.boxpos[0]) categList = [] categ1 = Classifier(conf.boxpos[0], conf.boxsize, conf.catlist[0]) categList.append(categ1) categ2 = Classifier(conf.boxpos[1], conf.boxsize, conf.catlist[1]) categList.append(categ2) categ3 = Classifier(conf.boxpos[2], conf.boxsize, conf.catlist[2]) categList.append(categ3) categ4 = Classifier(conf.boxpos[3], conf.boxsize, conf.catlist[3]) categList.append(categ4) allsprites = pygame.sprite.RenderPlain(chrList) allcategories = pygame.sprite.RenderPlain(categList) clock = pygame.time.Clock() config = CfgP.RawConfigParser() #spritelist=(chr1,chr2) spritelist = chrList rotationmode = 0 while 1: clock.tick(60) for event in pygame.event.get(): if event.type == QUIT: return elif event.type == KEYDOWN and event.key == K_ESCAPE: #spritelist=(chr1,chr2) #building a config file #saveCfgFile(config,spritelist) for s in spritelist: ##cfg file""" print "saving config" cref = s.ref ctype = s.type config.add_section(cref) config.set(cref, 'shape type', ctype) ## csv file ## row.append((s.ref, s.type)) result.writerows(row) row.pop() #### config.write(open('shape.cfg', 'w')) print "config saved" ###save the csv file #### result_file.close() del result del result_file return elif event.type == KEYDOWN and event.key == K_r: rotationmode = rotationmode + 1 if rotationmode == 1: print "rotation ON" if rotationmode == 2: print "rotation OFF" rotationmode = 0 if event.type == pygame.MOUSEBUTTONDOWN: #need to be modified to handle a list of chromosomes # chr1.rollover(rotationmode) # chr2.rollover(rotationmode) for k in chrList: k.rollover(rotationmode) allsprites.update(allcategories, background) allcategories.update() ## ##Search which chromosome is moved ##into which category and classify ##that chromosome in that category # collision=pygame.sprite.groupcollide(allcategories,allsprites,False,False,None) # for classified in collision.keys(): # print classified screen.blit(background, (0, 0)) allsprites.draw(screen) allcategories.draw(screen) pygame.display.flip()
def main(): """ This is our main program. """ pygame.init() # Set the height and width of the screen size = [SCREEN_WIDTH, SCREEN_HEIGHT] screen = pygame.display.set_mode(size) pygame.display.set_caption("Bouncing Balls") # Loop until the user clicks the close button. done = False # Used to manage how fast the screen updates clock = pygame.time.Clock() ball_list = [] ball = make_ball() ball_list.append(ball) # -------- Main Program Loop ----------- while not done: # --- Event Processing for event in pygame.event.get(): if event.type == pygame.QUIT: done = True elif event.type == pygame.KEYDOWN: # Space bar! Spawn a new ball. if event.key == pygame.K_SPACE: ball = make_ball() ball_list.append(ball) # --- Logic for ball in ball_list: # Move the ball's center ball.x += ball.change_x ball.y += ball.change_y # Bounce the ball if needed if ball.y > SCREEN_HEIGHT - BALL_SIZE or ball.y < BALL_SIZE: ball.change_y *= -1 if ball.x > SCREEN_WIDTH - BALL_SIZE or ball.x <= BALL_SIZE: ball.change_x *= -1 # --- Drawing # Set the screen background screen.fill(BLACK) # Draw the balls for ball in ball_list: pygame.draw.circle(screen, WHITE, [ball.x, ball.y], BALL_SIZE) # --- Wrap-up # Limit to 60 frames per second clock.tick(60) # Go ahead and update the screen with what we've drawn. pygame.display.flip() # Close everything down pygame.quit()
elif movement[0] < 0: rect.left = tile.right collision_types['left'] = True rect.y += movement[1] hit_list = collision_test(rect,tiles) for tile in hit_list: if movement[1] > 0: rect.bottom = tile.top collision_types['bottom'] = True elif movement[1] < 0: rect.top = tile.bottom collision_types['top'] = True return rect, collision_types clock = pygame.time.Clock() pygame.init() # initiates pygame pygame.display.set_caption('Pygame Platformer') WINDOW_SIZE = (600,400) screen = pygame.display.set_mode(WINDOW_SIZE,0,32) # initiate the window display = pygame.Surface((300,200)) # used as the surface for rendering, which is scaled moving_right = False moving_left = False vertical_momentum = 0 air_timer = 0 true_scroll = [0,0] game_map = load_map('map') <<<<<<< HEAD grass_img = pygame.image.load('images/grass.png') dirt_img = pygame.image.load('images/dirt.png') player_img = pygame.image.load('images/player.png').convert()