def __init__(self, screen, color, fps): self.fps = fps self.end = False self.screen = screen self.color = color self.info = Surface((1024, 50)) self.info.fill(color) self.ground = load('Resources\images\Sprites\Tiles\\0.png') self.pause_bg = load('Resources\images\\bg.png') self.pause = load('Resources\images\pause.png') self.pause.set_colorkey((179, 179, 179)) self.bomb_info = load('Resources\images\\bomb.png') self.life_info = load('Resources\images\life.png') self.power_info = load('Resources\images\power.png') self.main_menu = load('Resources\images\Buttons\Main menu.png') self.continue_btn = load('Resources\images\Buttons\Continue.png') self.pause_text = load('Resources\images\Buttons\Pause.png') self.bomb = load('Resources\images\\bomb.png') self.lvl = 1 self.scores = 0 self.start = 0 self.lives = 3 self.max_bombs = 1 self.strength = 1 set_visible(False) self.load_level() self.result = 0 self.play() set_visible(True) set_repeat()
def reset_stats(self, scoreboard): """ 将游戏状态重置 :return: """ self.score = 0 self.life -= 1 self.game_active = False self.ai_setting.interval = self.ai_setting.interval_base self.ai_setting.enemy_start = time() self.ai_setting.enemy_end = \ self.ai_setting.interval + self.ai_setting.enemy_start self.ai_setting.bullet_width = \ self.ai_setting.bullet_width_base self.ai_setting.ship_speed_factor = \ self.ai_setting.ship_speed_factor_base scoreboard.ai_setting.enemy_start = time() scoreboard.ai_setting.enemy_end = \ scoreboard.ai_setting.enemy_start + \ scoreboard.ai_setting.interval scoreboard.ai_setting.experience = \ scoreboard.ai_setting.experience_base scoreboard.prep_level() self.ai_setting.alien_speed_factor = \ self.ai_setting.alien_speed_base self.ai_setting.alien_score = self.ai_setting.alien_score_base mouse.set_visible(True)
def main(): print "#"*31 print "### Welcome to MindMixer ###" print "####### Version 0.1beta #######" print """Have a look at the sourcecode! Change stuff to suit your needs! The program will hopefully be self explaining. Hafe fun!""" print "#"*31 selftests() global N while 1: print "(Hint: while training, you can hit SPACE to abort)" print "Hit '"+KEYLEFT+"' if the",str(N)+". previous image is identical to the one shown" print "Hit '"+KEYRIGHT+"' if the",str(N)+". previous sound is identical to the one heard" while 1: print "Ready to train with N=%i?" %(N), if ask(): break else: print "Do you wish to train with N set to a different value? Choosing 'No' exits the program.", if ask(): n = int(raw_input("Ok, enter the desired value here: ")) while n < 1: print "N must be 1 or higher!" n = int(raw_input("Enter a value higher than 1: ")) N = n else: print "bye" sys.exit(1) display.init() display.set_mode(RESOLUTION, FULLSCREEN) font.init() mixer.init(44100) event.set_grab(True) mouse.set_visible(False) trials = gentrials() for trial in trials: if not trial.runtrial(): break display.quit() vis = 0.0 acu = 0.0 for trial in trials: if trial.result[0]: vis+=1 if trial.result[1]: acu+=1 vp = (vis/(MINTRIALS+N))*100 ap = (acu/(MINTRIALS+N))*100 message = "percentage in visual modality:%i\npercentage in acoustic modality:%i\n" %(int(vp),int(ap)) print message if vp >= UPPERTH and ap >= UPPERTH: N+=1 elif (vp < LOWERTH or ap < LOWERTH) and N > 1: N-=1
def handle(self, e): if e.type == KEYDOWN: pressed = key.get_pressed() shifted = pressed[K_LSHIFT] or pressed[K_RSHIFT] scroll = 10 if shifted else 1 if e.key == K_UP: self._scroll(1, -scroll) return True elif e.key == K_DOWN: self._scroll(1, scroll) return True elif e.key == K_LEFT: self._scroll(0, -scroll) return True elif e.key == K_RIGHT: self._scroll(0, scroll) return True elif e.unicode == '>': self._zscroll(-1) return True elif e.unicode == '<': self._zscroll(1) return True elif e.key == K_TAB: self._select(self.cursor) mouse.set_visible(False) return True elif (e.type == MOUSEBUTTONDOWN and self.background and self.background.get_rect().collidepoint(e.pos) and e.button == 1): self._select(self._absolutetile(mouse.get_pos())) return True elif (e.type == MOUSEBUTTONUP and self.background and self.background.get_rect().collidepoint(e.pos) and e.button == 1): self._dragging = False return True elif (e.type == MOUSEMOTION and self.background and self.background.get_rect().collidepoint(e.pos) and 1 in e.buttons): self._expandselection(self._absolutetile(mouse.get_pos())) self._dragging = True return False
def set(size, hotspot, xormasks, andmasks): """Sets new cursor image. Predefined cursors are tuples containing the 4 needed arguments, so you can type cursors.set(*cursors.arrow). Custom cursors must be first compiled by cursors.compile() to create the needed args. Public.""" if size is None: _mouse.set_visible(False) else: _mouse.set_visible(True) _mouse.set_cursor(size, hotspot, xormasks, andmasks)
def __init__(self, start=True, **kw): super().__init__(**kw) display.init() mouse.set_visible(False) self.size = self.canvas.array.shape[:2] self.screen = display.set_mode(self.size) self.screen.fill((0, 0, 0)) if start: self.start()
def handle(self, e): if e.type == MOUSEMOTION and e.rel != self._ignore: mouse.set_visible(True) self._ignore = None if self._playfield.handle(e): return True if 'pos' in e.dict: e.dict['pos'] = (e.pos[0] - self._fieldwidth, e.pos[1]) return self._info.handle(e)
def create_game(self): """Initializes the game.""" os.environ['SDL_VIDEO_CENTERED'] = '1' self.screen = display.set_mode(RESOLUTION, False, 32) self.scene = Scene(self.screen) self.events = EventManager(self.scene) self.clock = time.Clock() display.set_caption("%s %s" % (NAME, VERSION)) mouse.set_visible(False) if FULLSCREEN: toggle_fullscreen()
def _InitializeComponents(self, frequency, channels): # Initialize pygame. font.init() display.init() mixer.pre_init(frequency) mixer.init() mixer.set_num_channels(channels) mouse.set_visible(False)
def setVisible(self,visible): """Sets the visibility of the mouse to 1 or 0 NB when the mouse is not visible its absolute position is held at (0,0) to prevent it from going off the screen and getting lost! You can still use getRel() in that case. """ if usePygame: mouse.set_visible(visible) else: if self.win: #use default window if we don't have one w = self.win.winHandle else: w=pyglet.window.get_platform().get_default_display().get_windows()[0] w.set_mouse_visible(visible)
def __init__(self, level, map_tiles_filename, character_tiles_filename, fps=FRAMES_PER_SECOND): game.Game.__init__(self, fps) self.map_tiles = tileset.Tileset(map_tiles_filename, MAP_TILE_SIZE) self.character_tiles = tileset.Tileset(character_tiles_filename, CHARACTER_TILE_SIZE) if level < 1 or level > NUM_LEVELS: level = 1 self.current_level = level mixer.init() self.load_level(self.current_level) mouse.set_visible(False)
def set_exclusive_mouse(self, exclusive): if not exclusive == self._exclusive_mouse: self._exclusive_mouse = exclusive if self._exclusive_mouse: mouse.set_visible(False) pygame.event.set_grab(True) self._ex_mouse_x, self._ex_mouse_y = pygame.mouse.get_pos() else: # Show the cursor mouse.set_visible(True) pygame.event.set_grab(False) pygame.mouse.set_pos(self._ex_mouse_x, self._ex_mouse_y)
def setVisible(self, visible): """Sets the visibility of the mouse to 1 or 0 NB when the mouse is not visible its absolute position is held at (0, 0) to prevent it from going off the screen and getting lost! You can still use getRel() in that case. """ if self.win: # use default window if we don't have one self.win.setMouseVisible(visible) elif usePygame: mouse.set_visible(visible) else: # try communicating with window directly? plat = _default_display_ w = plat.get_windows()[0] w.set_mouse_visible(visible)
def _on_keyboard_down(self, keyboard, keycode, text, modifiers): """ with this is possible to control to show/hidden the faces """ if keycode[1] == 's' or keycode[1] == 'S': self.hide_faces() self.show_faces() self.navcolor = [1,1,1,1] Clock.unschedule(self._next_function) mouse.set_visible(True) if keycode[1] == 'h' or keycode[1] == 'H': self.hide_faces() self.navcolor = [1,1,1,0] Clock.schedule_once(self._next_function,settings.SECONDS_PER_IMAGE) mouse.set_visible(False) if keycode[1] == 'f' or keycode[1] == 'F': Window.toggle_fullscreen() return True
def __init__(self, parse, name=""): init() display.init() self.DIMS = (display.Info().current_w, display.Info().current_h) self.BG = Surface(self.DIMS) self.SCREEN = display.set_mode(self.DIMS, -2147483648) self.MANAGER = UIManager(self.DIMS) set_visible(True) update() Exit((0, 0), self.MANAGER) clear = Clear((0, 30), self.MANAGER) Spawn((0, 60), self.MANAGER, clear, self.DIMS, parse, name) Killer((0, 90), self.MANAGER, clear) Paint((0, 120), self.MANAGER) self.clock = Clock() while True: self.process_events()
def on_click(self, mouse_x, mouse_y): # Start new game. if self.play_button.clicked(mouse_x, mouse_y): self.settings.init_dynamic_settings() self.ship.move_to_center() self.bunkers.empty() self.bunkers.add( game_helper.create_bunkers(self.settings, self.screen, self.ship.rect.height)) self.alien_fleet.create() self.stats.reset() self.scoreboard.update() self.stats.game_active = True mouse.set_visible(False) # Display high score screen. elif self.score_button.clicked(mouse_x, mouse_y): self.high_score_screen.update() self.stats.show_start_screen = False
def game_pause(self): set_visible(True) set_repeat(0, 0) self.screen.blit(self.pause_bg, (0, 0)) is_paused = True start_pause = get_ticks() self.hero.ismoved = False n = 0 while is_paused: for event in get(): if event.type == QUIT: exit() elif event.type == KEYDOWN: if event.key == K_ESCAPE: n = 0 is_paused = False elif event.key == K_UP: n = 0 elif event.key == K_DOWN: n = 1 elif event.key == 13: is_paused = False elif event.type == MOUSEMOTION or event.type == MOUSEBUTTONDOWN and event.button == 1: [x, y] = event.pos if 405 <= x <= 620 and 360 <= y <= 408: n = 0 is_paused = event.type == MOUSEMOTION elif 380 <= x <= 650 and 440 <= y <= 486: n = 1 is_paused = event.type == MOUSEMOTION if not is_paused: if n == 1: self.end = True self.screen.blit(self.pause, (310, 240)) self.screen.blit(self.pause_text, (345, 255)) self.screen.blit(self.continue_btn, (405, 360)) self.screen.blit(self.main_menu, (380, 440)) self.screen.blit(self.bomb, (360 - n * 25, 365 + n * 80)) update() set_repeat(1, 1) set_visible(False) pause_time = get_ticks() - start_pause self.hero.update(self.screen, Group(), pause_time) self.start = self.start + pause_time
def _updatecursorsprite(self): self.cursorsprite.location = self.cursor self.cursorsprite.visible = not mouse.set_visible(-1) if self.cursorsprite.location: if not self.sprites.has(self.cursorsprite): self.sprites.add(self.cursorsprite) else: if self.sprites.has(self.cursorsprite): self.sprites.remove(self.cursorsprite)
def __init__(self, fps=FRAMES_PER_SECOND): game.Game.__init__(self, fps) mouse.set_visible(False) # Create the ship and place it in the center of the screen: center = shapes.Point(self.width / 2, self.height / 2) self.ship = shapes.Ship(center, SHIP_INITIAL_ROTATION, SHIP_COLOR) # Create bullet and upgrade lists: self.bullets = [] self.upgrades = [] # Create asteroids and background stars: self.asteroids = [] self.spawn_asteroids() self.stars = [] while len(self.stars) < (self.width * STAR_DENSITY): self.stars.append(shapes.Star(self.get_random_point())) # Initialize mixer and start looping background music: mixer.init() mixer.music.load(BACKGROUND_MUSIC) mixer.music.play(-1)
def update_mouse(self): if self.battle_master.is_victory_phase(): for enemy_unit in self.battle_master.stage_unit_renderer.stage_units[ 1:]: if enemy_unit.animation_set.mouse_collision(): self.player_interface_panel.display_bag_mouse() if constants.globals.clicked: self.player.get_loot(enemy_unit.unit, self.game_attributes.text_sprite) constants.globals.clicked = False # Return to avoid normal mouse showing up return if self.battle_master.is_battle_phase(): for enemy_unit in self.battle_master.stage_unit_renderer.stage_units[ 1:]: if enemy_unit.unit.animation_set.mouse_collision(): self.player_interface_panel.display_sword_mouse() if constants.globals.clicked and enemy_unit.unit.alive: self.player.next_action = ('attack', enemy_unit.unit) # Return to avoid normal mouse showing up return # Enable default mouse mouse.set_visible(True)
def _scroll(self, axis, amount): size = self.zoom.width if axis == 0 else self.zoom.height pos, tile = self._mouse() x0, y0 = pos while (tile is not None and ((amount < 0 and tile[axis] + self.offset[axis] > self.game.dimensions[axis] - self.dimensions[axis]/2) or (amount > 0 and tile[axis] + self.offset[axis] < self.dimensions[axis]/2))): pos, tile = self._mouse(tuple([pos[i] + (size * amount/abs(amount) if i == axis else 0) for i in range(2)])) amount -= amount/abs(amount) dest, remainder = self._clamp( self.offset[axis] + amount, (0, self.game.dimensions[axis] - self.dimensions[axis])) self.offset = tuple([dest if i == axis else self.offset[i] for i in range(2)]) while tile is not None and ((remainder < 0 and 0 < tile[axis]) or (remainder > 0 and tile[axis] < self.dimensions[axis]-1)): pos, tile = self._mouse(tuple([pos[i] + (size * remainder/abs(remainder) if i == axis else 0) for i in range(2)])) remainder -= remainder/abs(remainder) self.background = None mouse.set_visible(False) self._ignoremotion((pos[0] - x0, pos[1] - y0))
def set_cursor(self, cursor): """cursor can be either None, image name, Image, Sprite or HWCursor)""" if cursor is None: mouse.set_visible(False) self._sprite = None self._cursor = None elif isinstance(cursor, HWCursor): self._cursor = cursor self._sprite = None mouse.set_cursor(*cursor._data) mouse.set_visible(True) elif isinstance(cursor, Sprite): mouse.set_visible(False) self._sprite = cursor self._cursor = self.sprite else: s = Sprite(cursor) mouse.set_visible(False) self._sprite = s self._cursor = s
start_cols = SIZE[0]/100*1.625 # start position for cols step_rows = SIZE[0]/100*5.3125 # rows shift step_cols = SIZE[0]/100*4.6875 # columns shift pos = [start_rows_uneven, start_cols] rows = int(SIZE[1]/((SIZE[0]/100*3.125)*1.5))+1 # number of rows cols = int(SIZE[0]/((SIZE[0]/100*3.125)*1.5))+1 # number of columns # list x coords for lable words lable_x_positions = (('PRESS', int(SIZE[0] / 100 * 34.6875)), ('ESC', int(SIZE[0] / 100 * 40.625)), ('FOR', int(SIZE[0] / 100 * 40.625)), ('EXIT', int(SIZE[0] / 100 * 38.75))) lable_start_y = int(SIZE[0] / 100 * 9.375) mouse.set_visible(False) # set invisible for mouse cursor while 1: for e in event.get(): if e.type == KEYDOWN: if e.key == K_ESCAPE: sys.exit() screen.fill((40, 40, 40)) # draw lables for lable in lable_x_positions: screen.blit(ff.render(lable[0], 1, (55, 55, 55)), (lable[1], lable_start_y*(lable_x_positions.index(lable)+1))) # rotation if angle > 1.04 and angle < 1.05:
#sa = zeros((n_samples, 2)) #sound = sndarray.make_sound(sa) #sa = sndarray.samples(sound) #sound.play(-1) devs = init_multitouch(touch_callback) flags = FULLSCREEN | HWSURFACE | DOUBLEBUF mode = max(display.list_modes(0, flags)) display.set_mode(mode, flags) #display.set_mode((640, 480)) screen = display.get_surface() width, height = screen.get_size() txtfont = pygame.font.SysFont(None, 40) mouse.set_visible(False) fingers = [] start = None prevtime = None df = 0 curpos = (0, 0) curvel = (0, 0) from xbmc_client import DummyClient ws = DummyClient('ws://bh:9090/', protocols=['http-only', 'chat']) ws.connect() print 'Connected'
start_cols = SIZE[0] / 100 * 1.625 # start position for cols step_rows = SIZE[0] / 100 * 5.3125 # rows shift step_cols = SIZE[0] / 100 * 4.6875 # columns shift pos = [start_rows_uneven, start_cols] rows = int(SIZE[1] / ((SIZE[0] / 100 * 3.125) * 1.5)) + 1 # number of rows cols = int(SIZE[0] / ((SIZE[0] / 100 * 3.125) * 1.5)) + 1 # number of columns # list x coords for lable words lable_x_positions = (('PRESS', int(SIZE[0] / 100 * 34.6875)), ('ESC', int(SIZE[0] / 100 * 40.625)), ('FOR', int(SIZE[0] / 100 * 40.625)), ('EXIT', int(SIZE[0] / 100 * 38.75))) lable_start_y = int(SIZE[0] / 100 * 9.375) mouse.set_visible(False) # set invisible for mouse cursor while 1: for e in event.get(): if e.type == KEYDOWN: if e.key == K_ESCAPE: sys.exit() screen.fill((40, 40, 40)) # draw lables for lable in lable_x_positions: screen.blit(ff.render(lable[0], 1, (55, 55, 55)), (lable[1], lable_start_y * (lable_x_positions.index(lable) + 1)))
def __init__(self, cursor, visible=False): set_visible(visible) self.cursor = cursor self.absPos = (0,0) self.ignoreMove = False self._setDefaultButtonValues()
def Show(self): mouse.set_visible(False)
def show(self): set_visible(True)
def __init__(self): x, y = mouse.get_pos() mouse.set_visible(False) super().__init__(sword_image, x, y)
def main(): # initialize pygame pygame.init() # initialize screen info = display.Info() screenSize = (info.current_w, info.current_h) screen = display.set_mode(screenSize, pygame.FULLSCREEN) mouse.set_visible(False) # intialize clock clock = time.Clock() infoFont = font.Font(font.match_font('arial'), 12) # initialize game world world = World(screen) # start music mixer.music.load("resources/pad.ogg") mixer.music.set_volume(0.1) mixer.music.play(-1) # begin main game loop done = False while not done: # check for program exit signal for e in event.get(): if e.type == pygame.QUIT: done = True # check for input keys = key.get_pressed() if keys[pygame.K_ESCAPE]: done = True # update game world.update(clock.tick()) # render game world.draw() # draw fps fps = clock.get_fps() if DISPLAY_FPS: text = infoFont.render(str(int(round(fps))), True, (255, 255, 255)) position = (screen.get_width() / 2 - text.get_width() / 2, 32) screen.blit(text, position) # add particles until the processor can't handle it if fps > FRAME_RATE + 5: world.addParticle() # flip buffer display.flip() # clean up pygame.quit()
def setup(self): pygame.init() self.database.connect() self.config.read() self.data = self.core.get_data self.speed = self.config.parse["settings"]["speed"] set_caption(self.config.getName + " " + self.config.getVersion) self.screen = set_mode(self.config.getRect.size) self.core.load_assets() if self.data["icon"]: self.logs.info("Mengatur icon") set_icon(self.data["icon"]) set_visible(True) self.clock = Clock() #=== Background game ===# self.BACKGROUND = self.data["backgrounds"][random.choice( [x for x in self.data["backgrounds"]][1:])] self.BACKGROUND = scale(self.BACKGROUND, self.config.getRect.size) #=== Settings tanah texture ===# self.tanah = self.data["textures"]["tanah0"] self.tanah = scale(self.tanah, (1000, self.tanah.get_height())) self.tanah_diff = self.tanah.get_width() - self.BACKGROUND.get_width() self.tanah_position = [0, self.config.getRect.height * 0.95] #=== Settings grass texture ===# self.grass = self.data["textures"]["grass0"] self.grass = scale(self.grass, (1000, 10)) self.grass_diff = self.grass.get_width() - self.BACKGROUND.get_width() self.grass_position = [10, self.config.getRect.height * 0.94] #=== Settings rumput texture ===# rumput_image_list = [] for x in self.data["textures"]: if "rumput" in x: rumput_image_list.append(x) self.rumputGroup = Group() for x in range(random.randint(2, 4)): image = self.data["textures"]["rumput0"] self.rumputGroup.add( Rumput(image, [ random.randint(self.config.getRect.width, 3000), self.config.getRect.height * 0.80 ])) #=== Settings keris image ===# self.kerisGroup = Group() for x in range(random.randint(1, 3)): keris = Keris(self.data["anim"]["keris"], [ random.randint(self.config.getRect.width, self.config.getRect.width * 2), 10 ]) keris.rect.bottom += random.randint( 10, self.config.getRect.height - 130) self.kerisGroup.add(keris) #=== Settings bambu image ===# self.bambuGroup = Group() for x in range(random.randint(1, 3)): bambu = Bambu(self.data["other"]["bambu"], [ random.randint(self.config.getRect.width, self.config.getRect.width * 2), 10 ]) bambu.rect.bottom += self.config.getRect.height * 0.78 self.bambuGroup.add(bambu) #=== Settings player image ===# self.player = Player(self.data["anim"]["player1"], [60, self.config.getRect.height - 40]) #=== Settings score ===# self.score = Score(self.data) #=== Health bar ===# self.health = Health(self.data)
from pygame.image import load as iload from pygame.transform import smoothscale from pygame.time import Clock from pygame.event import get as eget from pygame.mouse import set_visible from os import listdir,access,F_OK from time import sleep from random import Random init() set_mode((0,0),FULLSCREEN|HWSURFACE|DOUBLEBUF) #set_mode((640,480),HWSURFACE) set_visible(False) s=get_surface() def fit(w,h,ww,hh): a=ww/float(w) w1=ww; h1=h*a if h1<=hh: return w1,h1 return w*(hh/float(h)),hh def center(w,h,ww,hh): return (ww-w)/2,(hh-h)/2 def getseed(d):
def go(): # START # Fairly obvious, initialize the pygame library pygame.init() # Create the world in which all physical things reside. It is our coordinate system and universe. world = World(vector((20.0, 20.0, 2000.0)), vector((-10.0, 0.0, 10.0))) # Create startup cameras and make the world visible to them eyecam = Camera() eyecam.registerObject(world) scopecam = Camera() scopecam.registerObject(world) # Setup the program window (just a special case of a View) screen = Screen(eyecam, vector((1000,800,0)), -1.0) screen.display = pygame.display.set_mode((1000, 800)) # Setup the display surfaces to be drawn to screen and list them main_dim = vector((1000,800,0.0)) scope_dim = vector((240,240,0.0)) mainview = View(eyecam, main_dim, zero_vector, 1.0) scopeview = Scope(scopecam, scope_dim, (main_dim - scope_dim) / 2.0, 4.0) views = [ mainview, scopeview ] # Hide the cursor mouse.set_visible(False) # Let's set up some useful variables now = pygame.time.get_ticks() # The current program time shot_fired = False # chase_bullet = False hide_scope = True lock_mouse = False power = 100.0 #mainview.reposition(eyecam) scopeview.setPower(power) timescale = 1.0 tot_mag = 0.0 tot_dur = 0.0 frames = 0 if lock_mouse: mouse.set_pos((scope_dim / 2.0).xy()) while 1: last_t = now now = pygame.time.get_ticks() t_length = float(now - last_t) if world.has_hit: shot_end = now #break if world.bullet.position.z() > world.target.position.z() + 1000.0: #world.bullet.position = vector((world.bullet.position.x(), world.bullet.position.y(), world.target.position.z() - 0.01)) shot_end = now break #pass for event in pygame.event.get(): if event.type == pygame.MOUSEBUTTONDOWN: if event.dict['button'] == 4: power += 1.0 if event.dict['button'] == 5: power -= 1.0 power = scopeview.setPower(power) print power if event.type == pygame.QUIT: sys.exit() sx, sy = (0.5 * mainview.dimensions).xy() if lock_mouse: mx, my = mouse.get_rel() mouse.set_pos(sx, sy) r = (1.0 / (10000 * power))* (vector((sx - mx, sy - my, 0))) scopecam.rotation += r eyecam.rotation += r else: mx, my = mouse.get_pos() r = (1.0 / (1000 * power))* (vector((sx - mx, sy - my, 0))) scopecam.rotation = r eyecam.rotation = r world.bullet.rotation = scopecam.rotation scopeview.reposition(scopeview.camera) mainview.reposition(mainview.camera) b1, b2, b3 = mouse.get_pressed() if b1 and not shot_fired: shot_fired = True shot_start = now world.bullet.velocity = rotate(vector((0.0,0.0,800.0)), (-world.bullet.rotation - scopeview.tweaks)) print 'Start Velocity: ' + str(world.bullet.velocity.magnitude()) #mainview.camera.rotation = zero_vector mainview.setPower(50.0) #scopeview.reposition(view.camera) #scopeview.overlay = [] # hide scope world.movers += [world.bullet] # Move everything. The world does most of the work once we tell it to, # we just need to handle the less tangible stuff. world.moveObjects(timescale * (t_length / 1000.0)) # Bullet chasing if shot_fired: #scopecam.rotation = world.bullet.rotation if hide_scope: scopeview.visible = False bp = world.bullet.position lbp = world.bullet.last_position diff = bp - lbp mag = diff.magnitude() magxz = sqrt(diff.x()**2 + diff.z()**2) frames += 1 tot_mag += mag tot_dur += t_length * timescale if chase_bullet and mag > 0.0: h = arctan2(diff.x(), diff.z()) e = arcsin(diff.y() / mag) eyecam.rotation = vector((h, -e, 0)) eyecam.position = bp & vector((1,1,1)) mainview.setPower(10.0) mainview.reposition(mainview.camera) #print eyecam.position #scopeview.reposition(eyecam) # Grab each view's camera image, then draw them to the program window in sequence for view in views: view.updateDisplay() view.draw(screen.display) # fps = 1000.0 / (t_length + (1 if t_length == 0 else 0)) screen.drawOverlay((fps,)) pygame.display.flip() for view in views: view.updateDisplay() view.draw(screen.display, (screen.dimensions - view.dimensions) / 2.0) pygame.display.flip() print "Flight time: " + str(tot_dur / 1000.0) + " s" print "Impact energy: " + str(.5 * world.bullet.mass * world.bullet.velocity.magnitude() ** 2) + " J" print 'End Position' print world.bullet.position print 'End Velocity: ' + str(world.bullet.velocity.magnitude()) print "Average frame time: " + str((tot_dur / 1000.0) / float(frames)) print "Average FPS: " + str(float(frames) / tot_dur * 1000) print "Average distance per frame: " + str(tot_mag / float(frames)) pygame.time.delay(1000) pygame.display.quit() pygame.quit()
""" Записываем новый рекорд в файл """ if score_in['record_score'] < score_in['current_score']: with open('record_score.txt', 'w', encoding='utf-8') as file_obj: file_obj.write(str(score_in['current_score'])) print(f"Новый рекорд {score_in['current_score']} записан в файл.") else: print("Новый рекорд не установлен - в файл ничего не записано.") # настраиваем экран environ['SDL_VIDEO_CENTERED'] = '1' # выводим окно программы в центре экрана window_surf = display.set_mode((SIZE_WINDOW, SIZE_WINDOW)) display.set_caption("Игра 'Полет в небе' © Житников Тарас") # дополнительные настройки mouse.set_visible(False) # отключаем указатель мыши game_clock = time.Clock() # будем ограничивать кадры в секундку # бесконечный цикл для быстрого перезапуска игр while True: # в начале игры считываем рекорд из файла score = { 'record_score': read_record_score(), 'current_score': 0, 'lives_player': MAX_LIVES_PLAYER, 'added_lives': 0, 'speed_game': 1 } # выводим приветственный экран welcome_screen("Игра «Полет в небе»", f"рекорд: {score['record_score']}", "Нажмите любую клавишу для начала игры.")
def hide(self): set_visible(False)
def go(): # START # Fairly obvious, initialize the pygame library pygame.init() # Create the world in which all physical things reside. It is our coordinate system and universe. world = World(vector((20.0, 20.0, 2000.0)), vector((-10.0, 0.0, 10.0))) # Create startup cameras and make the world visible to them eyecam = Camera() eyecam.registerObject(world) scopecam = Camera() scopecam.registerObject(world) # Setup the program window (just a special case of a View) screen = Screen(eyecam, vector((1000, 800, 0)), -1.0) screen.display = pygame.display.set_mode((1000, 800)) # Setup the display surfaces to be drawn to screen and list them main_dim = vector((1000, 800, 0.0)) scope_dim = vector((240, 240, 0.0)) mainview = View(eyecam, main_dim, zero_vector, 1.0) scopeview = Scope(scopecam, scope_dim, (main_dim - scope_dim) / 2.0, 4.0) views = [mainview, scopeview] # Hide the cursor mouse.set_visible(False) # Let's set up some useful variables now = pygame.time.get_ticks() # The current program time shot_fired = False # chase_bullet = False hide_scope = True lock_mouse = False power = 100.0 #mainview.reposition(eyecam) scopeview.setPower(power) timescale = 1.0 tot_mag = 0.0 tot_dur = 0.0 frames = 0 if lock_mouse: mouse.set_pos((scope_dim / 2.0).xy()) while 1: last_t = now now = pygame.time.get_ticks() t_length = float(now - last_t) if world.has_hit: shot_end = now #break if world.bullet.position.z() > world.target.position.z() + 1000.0: #world.bullet.position = vector((world.bullet.position.x(), world.bullet.position.y(), world.target.position.z() - 0.01)) shot_end = now break #pass for event in pygame.event.get(): if event.type == pygame.MOUSEBUTTONDOWN: if event.dict['button'] == 4: power += 1.0 if event.dict['button'] == 5: power -= 1.0 power = scopeview.setPower(power) print power if event.type == pygame.QUIT: sys.exit() sx, sy = (0.5 * mainview.dimensions).xy() if lock_mouse: mx, my = mouse.get_rel() mouse.set_pos(sx, sy) r = (1.0 / (10000 * power)) * (vector((sx - mx, sy - my, 0))) scopecam.rotation += r eyecam.rotation += r else: mx, my = mouse.get_pos() r = (1.0 / (1000 * power)) * (vector((sx - mx, sy - my, 0))) scopecam.rotation = r eyecam.rotation = r world.bullet.rotation = scopecam.rotation scopeview.reposition(scopeview.camera) mainview.reposition(mainview.camera) b1, b2, b3 = mouse.get_pressed() if b1 and not shot_fired: shot_fired = True shot_start = now world.bullet.velocity = rotate(vector( (0.0, 0.0, 800.0)), (-world.bullet.rotation - scopeview.tweaks)) print 'Start Velocity: ' + str(world.bullet.velocity.magnitude()) #mainview.camera.rotation = zero_vector mainview.setPower(50.0) #scopeview.reposition(view.camera) #scopeview.overlay = [] # hide scope world.movers += [world.bullet] # Move everything. The world does most of the work once we tell it to, # we just need to handle the less tangible stuff. world.moveObjects(timescale * (t_length / 1000.0)) # Bullet chasing if shot_fired: #scopecam.rotation = world.bullet.rotation if hide_scope: scopeview.visible = False bp = world.bullet.position lbp = world.bullet.last_position diff = bp - lbp mag = diff.magnitude() magxz = sqrt(diff.x()**2 + diff.z()**2) frames += 1 tot_mag += mag tot_dur += t_length * timescale if chase_bullet and mag > 0.0: h = arctan2(diff.x(), diff.z()) e = arcsin(diff.y() / mag) eyecam.rotation = vector((h, -e, 0)) eyecam.position = bp & vector((1, 1, 1)) mainview.setPower(10.0) mainview.reposition(mainview.camera) #print eyecam.position #scopeview.reposition(eyecam) # Grab each view's camera image, then draw them to the program window in sequence for view in views: view.updateDisplay() view.draw(screen.display) # fps = 1000.0 / (t_length + (1 if t_length == 0 else 0)) screen.drawOverlay((fps, )) pygame.display.flip() for view in views: view.updateDisplay() view.draw(screen.display, (screen.dimensions - view.dimensions) / 2.0) pygame.display.flip() print "Flight time: " + str(tot_dur / 1000.0) + " s" print "Impact energy: " + str( .5 * world.bullet.mass * world.bullet.velocity.magnitude()**2) + " J" print 'End Position' print world.bullet.position print 'End Velocity: ' + str(world.bullet.velocity.magnitude()) print "Average frame time: " + str((tot_dur / 1000.0) / float(frames)) print "Average FPS: " + str(float(frames) / tot_dur * 1000) print "Average distance per frame: " + str(tot_mag / float(frames)) pygame.time.delay(1000) pygame.display.quit() pygame.quit()