def drawWindow(): window.blit(_background, (0, 0)) # pygame.draw.rect(window, (105, 105, 105), (0, 0, 450, 560)) # playlist # pygame.draw.rect(window, (105, 105, 105), (460, 0, 1280 - 450 - 10, 560)) # songlist #pygame.draw.rect(window, (105, 105, 105), (0, 570, 1280, 720 - 10 - 570)) # controls if client.offline: window.blit(_nonet, (1152, 22)) else: window.blit(_net, (1152, 22)) window.blit(_songname.img, (20, 640)) if State.currentSong != '': name = cutText(State.currentSong, _songname.w) else: name = '' text1 = font.render(f"{name}", 1, colors['black']) window.blit(text1, (45, 665)) text2 = font.render('Volume', 1, colors['white']) window.blit(text2, (148, 612)) if not State.allsongs: font1 = pygame.font.SysFont('berlinsansfb', 40) text3 = font1.render( State.playlists[State.playlistIndex].button.textname, 1, colors['white']) w, h = font1.size( State.playlists[State.playlistIndex].button.textname) window.blit(text3, (920 - int(w / 2), 15)) songView.draw(window) playlistView.draw(window) if State.allsongs: for i in range(0, len(State.songbuttons)): if songView.list[i]: State.songbuttons[i].update(i - songView.value) State.songbuttons[i].draw(window) else: for i in range(0, len(State.playlists[State.playlistIndex].songs)): if songView.list[i]: State.playlists[State.playlistIndex].songs[i].update( i - songView.value) State.playlists[State.playlistIndex].songs[i].draw(window) for i in range(0, len(State.playlists)): if playlistView.list[i]: State.playlists[i].button.update(i - playlistView.value) State.playlists[i].button.draw(window) repeatButton.draw(window) if State.repeat > 0: pixels = pygame.PixelArray(_repeat.img) pixels.replace((20, 255, 25, 255), (60, 185, 185, 220), 0.405) del pixels if State.repeat == 1: font1 = pygame.font.SysFont('berlinsansfb', 22) text3 = font1.render('1', 1, colors['white']) window.blit(text3, (1245, 678)) else: font1 = pygame.font.SysFont('berlinsansfb', 25) text3 = font1.render('∞', 1, colors['white']) window.blit(text3, (1237, 676)) else: repeatButton.img.img = _repeatcopy.img.copy() if State.shuffle > 0: pixels = pygame.PixelArray(_shuffle.img) pixels.replace((20, 255, 25, 255), (60, 185, 185, 220), 0.405) del pixels else: shuffleButton.img.img = _shufflecopy.img.copy() removeButton.draw(window) addButton.draw(window) renamelistButton.draw(window) if not State.paused: pauseButton.draw(window) else: playButton.draw(window) allsongsButton.draw(window) nextButton.draw(window) previousButton.draw(window) shuffleButton.draw(window) newplaylistButton.draw(window) deleteButton.draw(window) volume.draw(window) time.draw(window) pygame.display.update()
pygame.draw.line(windowSurface, BLUE, (60, 120), (120, 120), 4) # draw a blue circle onto the surface pygame.draw.circle(windowSurface, BLUE, (300, 50), 20, 0) pygame.gfxdraw.circle(windowSurface, 300, 50, 25, BLUE) pygame.gfxdraw.aacircle(windowSurface, 300, 50, 28, BLUE) # draw a red ellipse onto the surface pygame.draw.ellipse(windowSurface, RED, (300, 250, 40, 80), 1) pygame.gfxdraw.aaellipse(windowSurface, 300, 250, 60, 100, RED) # draw the text's background rectangle onto the surface pygame.draw.rect(windowSurface, RED, (textRect.left - 20, textRect.top - 20, textRect.width + 40, textRect.height + 40)) # get a pixel array of the surface pixArray = pygame.PixelArray(windowSurface) pixArray[480][380] = BLACK del pixArray # draw the text onto the surface windowSurface.blit(text, textRect) # draw the window onto the screen pygame.display.update() # run the game loop while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit()
import pygame pygame.init() white = (255, 255, 255) black = (0, 0, 0,) red = (255, 0, 0) green = (0, 255 ,0) blue =(0,0,255) gameDisplay = pygame.display.set_mode((800, 600)) gameDisplay.fill(black) pixAr = pygame.PixelArray(gameDisplay) pixAr[10][20]= green pygame.draw.line(gameDisplay, blue, (100,200), (300, 450), 5) pygame.draw.rect(gameDisplay, red, (400, 400, 50, 20)) pygame.draw.circle(gameDisplay, white, (150, 150), 75) pygame.draw.polygon(gameDisplay, green, ((25,75),(76, 125), (250, 375),(400, 25),(60, 540))) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() pygame.display.update()
def dibujarTiro(supPant, supPaisajeUrbano, ángulo, velocidad, númJugador, viento, gravedad, gor1, gor2): # xinicio e yinicio corresponden a la esquina superior izquierda del gorila. ángulo = ángulo / 180.0 * math.pi velInicX = math.cos(ángulo) * velocidad velInicY = math.sin(ángulo) * velocidad anchoGor, alturaGor = GOR_ABAJO_SUP.get_size() rectGor1 = pygame.Rect(gor1[0], gor1[1], anchoGor, alturaGor) rectGor2 = pygame.Rect(gor2[0], gor2[1], anchoGor, alturaGor) if númJugador == 1: imgGor = BRAZO_IZQ_ARRIBA else: imgGor = BRAZO_DER_ARRIBA """El gorila del jugador 1 sobre la izquierda usa su brazo izquierdo para arrojar bananas. El gorila del jugador 2 sobre la derecha usa su brazo derecho.""" if númJugador == 1: xinicio = gor1[0] yinicio = gor1[1] elif númJugador == 2: xinicio = gor2[0] yinicio = gor2[1] dibujarGorila(supPant, xinicio, yinicio, imgGor) pygame.display.update() time.sleep(0.3) dibujarGorila(supPant, xinicio, yinicio, AMBOS_BRAZOS_ABAJO) pygame.display.update() """Dibujar el gorila arrojando la banana.""" formaBanana = ARRIBA if númJugador == 2: xinicio += GOR_ABAJO_SUP.get_size()[0] yinicio -= obtenerRectBanana( 0, 0, formaBanana).height + BAN_ARRIBA_SUP.get_size()[1] impacto = False bananaEnJuego = True t = 1.0 impactoSol = False while not impacto and bananaEnJuego: x = xinicio + (velInicX * t) + (0.5 * (viento / 5) * t**2) y = yinicio + ((-1 * (velInicY * t)) + (0.5 * gravedad * t**2)) """Esta es básicamente la ecuación que describe el arco de la trayectoria de la banana.""" if x >= ANCHO_PNT - 10 or x <= 3 or y >= ALTURA_PNT: bananaEnJuego = False rectBanana = obtenerRectBanana(x, y, formaBanana) if formaBanana == ARRIBA: supBanana = BAN_ARRIBA_SUP rectBanana.left -= 2 rectBanana.top += 2 elif formaBanana == ABAJO: supBanana = BAN_ABAJO_SUP rectBanana.left -= 2 rectBanana.top += 2 elif formaBanana == IZQ: supBanana = BAN_IZQ_SUP elif formaBanana == DER: supBanana = BAN_DER_SUP formaBanana = siguienteFormaBanana(formaBanana) arregloPíxFuente = pygame.PixelArray(supPaisajeUrbano) if bananaEnJuego and y > 0: if solRect.collidepoint(x, y): # la banana ha golpeado al sol, entonces dibujamos la cara "sorprendida". impactoSol = True # dibujar el sol con la cara adecuada dibujarSol(supPant, sorprendido=impactoSol) if rectBanana.colliderect(rectGor1): # la banana ha golpeado al jugador 1 """Notar que dibujamos la explosión sobre la pantalla (en supPant) y en la superficie independiente del paisaje (on supPaisajeUrbano). Esto es para que las bananas no golpeen al sol o algún texto y accidentalmente piensen que han chocado contra algo. También queremos que el objeto superficie supPaisajeUrbano lleve registro de qué parte de los edificios sigue en pie.""" hacerExplosión(supPant, supPaisajeUrbano, rectBanana.centerx, rectBanana.centery, tamañoExplosión=int(TAMAÑO_EXPLOSIÓN_GOR * 2 / 3), velocidad=0.005) hacerExplosión(supPant, supPaisajeUrbano, rectBanana.centerx, rectBanana.centery, tamañoExplosión=TAMAÑO_EXPLOSIÓN_GOR, velocidad=0.005) dibujarSol(supPant) return 'gorila1' elif rectBanana.colliderect(rectGor2): # la banana ha golpeado al jugador 2 hacerExplosión(supPant, supPaisajeUrbano, rectBanana.centerx, rectBanana.centery, tamañoExplosión=int(TAMAÑO_EXPLOSIÓN_GOR * 2 / 3), velocidad=0.005) hacerExplosión(supPant, supPaisajeUrbano, rectBanana.centerx, rectBanana.centery, tamañoExplosión=TAMAÑO_EXPLOSIÓN_GOR, velocidad=0.005) supPant.fill(COLOR_CIELO, rectBanana) # borrar banana dibujarSol(supPant) return 'gorila2' elif chocaContraSinColor(arregloPíxFuente, supPant, rectBanana, COLOR_CIELO): # la banana ha golpeado un edificio hacerExplosión(supPant, supPaisajeUrbano, rectBanana.centerx, rectBanana.centery) supPant.fill(COLOR_CIELO, rectBanana) # borrar banana dibujarSol(supPant) return 'edificio' del arregloPíxFuente """Pygame no nos permite hacer "blit" sobre una superficie mientras exista un arreglo de píxeles de ella, de modo que la borramos.""" supPant.blit(supBanana, (rectBanana.topleft)) pygame.display.update() time.sleep(0.02) supPant.fill(COLOR_CIELO, rectBanana) # borrar banana t += 0.1 # avanzar en el dibujo. dibujarSol(supPant) return 'errado'
pygame.draw.line(window_surface, blue, (120, 60), (60, 120)) pygame.draw.line(window_surface, blue, (60, 120), (120, 120), 4) # draw a blue circle onto the surface pygame.draw.circle(window_surface, blue, (300, 50), 20, 0) # Draw a red ellipse onto the surface. pygame.draw.ellipse(window_surface, red, (300, 250, 40, 80), 1) # draw the text's background rectangle onto the surface pygame.draw.rect(window_surface, red, (textRect.left - 20, textRect.top - 20, textRect.width + 40, textRect.height + 40)) # get a pixel array of the surface pix_array = pygame.PixelArray(window_surface) for line in range(500): pix_array[line][380] = red del pix_array # draw the text onto the surface window_surface.blit(text, textRect) # draw the window onto the screen pygame.display.update() # Run the game loop while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit()
def __init__(self): self.creditText = ["1994 Channel 7, Destiny: Virtual", "Released Under GPL V3.0 in 2013 by Jeremy D Stanton of IronSeed.net", "2013 y-salnikov - Converted IronSeed to FreePascal and GNU/Linux", "2016 Nuke Bloodaxe - Code Tidying", "2020 Nuke Bloodaxe - Complete Python Refactor/Rewrite", "All rights reserved."] self.versionText = ["Ironseed", g.version] # Ridiculous version string required... self.introText1 = ["A","Destiny: Virtual", "Designed Game"] self.introText2 = ["Mars", "3784 A.D."] self.introText3 = ["Escaping the iron fist of a fanatical", "theocracy, the members of the Ironseed", "Movement launch into space and are set", "adrift after suffering a computer", "malfunction"] self.introText4 = ["Ship IRONSEED to Relay Point:", "Link Established.", "Receiving Encode Variants.", "Wiping Source Encodes.", "Terminating Transmission.", 'Control Protocol Transfered to Human Encode "PRIME".'] # Que Transformers theme... self.introText5 = ["As captain, you awaken along with the", "crew some thousand years later and are", "confronted by an alien horde..."] self.introText6 = ["Orders: Approach and Destroy.", "Jamming all Emissions.", "Targeting...", "Locked and Loading...", "Closing for Fire..."] self.introText7 = ["Enemy Closing Rapidly...", "Shields Imploding...", "Destruction Imminent.", "Attempting Crash Landing."] self.introText8 = ["They threaten to devour all life in", "their path...your only hope of defeating", "the Scavengers is to reunite the Kendar,", "an ancient alliance among the free", "worlds."] self.starField = pygame.image.load(os.path.join('Graphics_Assets', 'cloud.png')) self.channel7Logo = pygame.image.load(os.path.join('Graphics_Assets', 'channel7.png')) self.mars = pygame.image.load(os.path.join('Graphics_Assets', 'world.png')) self.charCom = pygame.image.load(os.path.join('Graphics_Assets', 'charcom.png')) self.redLight = pygame.image.load(os.path.join('Graphics_Assets', 'CrewCom_RED.png')) self.battle = pygame.image.load(os.path.join('Graphics_Assets', 'battle1.png')) self.alienShip = pygame.image.load(os.path.join('Graphics_Assets', 'alien.png')) self.ship = pygame.image.load(os.path.join('Graphics_Assets', 'ship1.png')) self.intro5 = pygame.image.load(os.path.join('Graphics_Assets', 'intro5.png')) self.ironseed = pygame.image.load(os.path.join('Graphics_Assets', 'main3.png')) # Prime intro stage checker self.introStage = 0 self.introFinished = False self.musicState = False # Prepare counters self.count = 1 self.length = 0 self.encodeStep = 0 self.scavengerStep = 0 self.crashLandingStep = 0 self.centredX = 0.0 self.centeredY = 0.0 # Prepare Ironseed Intro stopwatch. self.stopwatch = h.StopWatch() # Prepare surface used for fading out. self.fade = pygame.Surface((g.width,g.height)) self.fade.fill(g.BLACK) self.fade.set_alpha(10) # Prepare Channel 7 Logo for blitting. self.C7Scaled = pygame.transform.scale(self.channel7Logo, (g.width, g.height)) self.C7LogoBlit = pygame.PixelArray(self.C7Scaled.convert()) self.C7LogoCreate = pygame.Surface((g.width, g.height), 0) self.C7LogoCreate.set_colorkey(g.BLACK) # Prepare starfield for blitting. self.starFieldScaled = pygame.transform.scale(self.starField, (g.width, g.height)) #self.starFieldBlit = pygame.PixelArray(self.scaled.convert()) # Prepare Mars for Blitting. self.marsScaled = pygame.transform.scale(self.mars, (g.width, g.height)) #self.marsBlit = pygame.PixelArray(self.scaled.convert()) # Prepare Character communication screen for blitting. self.charComScaled = pygame.transform.scale(self.charCom, (g.width, g.height)) self.charComScaled.set_colorkey(g.BLACK) # Gradient as a list of tuples. self.redBar = h.colourGradient(int(g.width/16)*2, g.RED) # Full length Encode Bar. self.fullBar = h.createBar(self.redBar, int((g.width/320)*37), int((g.height/200)*2)+1) # Red tank light, including flipped version. self.redLightScaled = pygame.transform.scale(self.redLight, (int((g.width/320)*13), int((g.height/200)*16))) self.redLightScaledFlipped = pygame.transform.flip(self.redLightScaled, True, False) # Background star with lens flare. self.battleScaled = pygame.transform.scale(self.battle, (g.width, g.height)) self.battleScaled.set_colorkey(g.BLACK) # Prepare ship for blitting, this will be transformed later. self.shipScaled = pygame.transform.scale(self.ship, (g.width, g.height)) self.shipScaled.set_colorkey(g.BLACK) # Buffer for image manipulation. self.bufferSurfaceImage = pygame.Surface((g.width,g.height)) self.bufferSurfaceImage.set_colorkey(g.BLACK) # TODO: Set correct scale ratio. # Prepare Alien battleship deck self.alienShipScaled = pygame.transform.scale(self.alienShip, (g.width, g.height)) self.alienShipScaled.set_colorkey(g.BLACK) # Prepare Ironseed deck image; I really should have the EGO jars # bubbling in distress here. self.ironseedScaled = pygame.transform.scale(self.ironseed, (g.width, g.height)) self.ironseedScaled.set_colorkey(g.BLACK) # Create blue status bar for additive overlay. self.blueBar = h.colourLine(int((g.width/320)*106), g.BLUE) self.fullBlueBar = h.createBar(self.blueBar, int((g.width/320)*106), int((g.height/200)*10)+1)
update = 0 while True: if update: pygame.display.update() update = 0 for event in pygame.event.get(): if event.type == QUIT: # zatvorenie aplikacie pygame.quit() sys.exit() if (event.type == KEYUP) and (event.key == 113): pygame.quit() sys.exit() if (event.type == MOUSEBUTTONDOWN): posx, posy = event.pos canvas = pygame.PixelArray(win) canvas[posx][posy] = (255, 255, 128) del canvas update = 1 if (event.type == MOUSEMOTION): posx, posy = event.pos pozicia = BasicFont.render(" X=%d Y=%d " % (posx, posy), True, (255, 255, 255), (0, 80, 0)) poziciaRect = pozicia.get_rect() poziciaRect.move_ip(20, 20) win.blit(pozicia, poziciaRect) update = 1
screen_status_h = 96 app_display_width = display_width * screen_scale app_display_height = display_height * screen_scale + screen_status_h app_display_pixels_count = app_display_width * app_display_height app_display_size = (app_display_width, app_display_height) app_screen = pygame.display.set_mode(app_display_size) device_screen_pixels_count = display_width * screen_scale * display_height * screen_scale pygame.display.set_caption("CHIP8 Emulator") pxarray = pygame.PixelArray(app_screen) clock = pygame.time.Clock() pygame.key.set_repeat(2000, 2000) REGISTERS_NUM = 0x10 CLS_BG = (0, 0, 0) COL_FG = (255, 255, 255) KEY_MAP = {
def draw_pixels(self): pixels = pygame.PixelArray(self.surface) for i in range(220, 250): # [pos x][pos y] pixels[400 + (220 - i)][i] = GREEN del pixels
HWSURFACE | DOUBLEBUF | RESIZABLE) screen.blit(pygame.transform.scale(pic, event.dict['size']), (0, 0)) pygame.display.flip() for i in range(1, Width - 2): for j in range(1, Height - 2): HitVec = False TheHood = [ Map[i - 1][j], Map[i + 1][j], Map[i + 1][j - 1], Map[i][j + 1] ] for x in TheHood: if x == Map[i][j] % 3 + 1: HitVec = True if HitVec: Switch = randint(0, 3) if Switch == 0: Map[i - 1][j] = Map[i][j] elif Switch == 1: Map[i + 1][j] = Map[i][j] elif Switch == 2: Map[i][j - 1] = Map[i][j] elif Switch == 3: Map[i][j + 1] = Map[i][j] pixObj = pygame.PixelArray(DisplaySurf) pixObj[i][j] = MyColors[Map[i][j] - 1] del pixObj pygame.display.update()
def handle_events(self, events): for event in events: if event.type == pygame.QUIT: pygame.event.post(pygame.event.Event(QUIT)) if event.type == pygame.KEYDOWN and event.key == pygame.K_p: self.paused = not self.paused if self.paused: continue if event.type == KEYDOWN and event.key == K_ESCAPE: self.manager.go_to(TitleScene()) if event.type == pygame.KEYDOWN and event.key == pygame.K_z: if Animation("sword") not in self.animations: params = {'sprite': self.sword_texture, 'phase': 0} self.animations.append(Animation("sword", params)) if event.type == pygame.KEYDOWN and event.key == pygame.K_x: pygame.event.post(pygame.event.Event(actionEvent)) if event.type == pygame.KEYDOWN or event.type == pygame.KEYUP: self.player.update_speed() if event.type == pathfindingEvent: for char in self.npcs: if type(char) is Stalker: char.update_path(self.grid, char.gridPos, self.player.gridPos) if event.type == updateGridEvent: self.grid.update_grid(self.collidables + self.character_collision_boxes) if event.type == animationEvent: # Update all active animations for s in self.animations: if s.name == "sword": #Sword animation self.player.directionLock = True if s.phase >= 12: self.swordsprite.image = pygame.Surface((0, 0)) self.animations.remove(s) self.player.directionLock = False self.player.set_sprite_direction() self.player.update_sprite() self.sword_icon = pygame.transform.flip(self.sword_icon, True, False) continue if s.phase < 7: if s.phase == 3: pygame.event.post(pygame.event.Event(swordSwingEvent)) if s.phase < 2: self.swordsprite.image = s.sprite.subsurface(pygame.Rect(0, 0, 25, 28)) else: self.swordsprite.image = s.sprite.subsurface(pygame.Rect(25 * (s.phase-2), 0, 25, 28)) self.swordsprite.image = pygame.transform.rotate(pygame.transform.flip(self.swordsprite.image, True, False), (360 - self.player.direction) % 360 ) self.swordsprite.rect.topleft = self.player.rect.midtop if s.phase == 0: self.sword_icon = pygame.transform.flip(self.sword_icon, True, False) if 45 > (self.player.direction % 360) or (self.player.direction % 360) >= 315: self.swordsprite.rect.left -= 16 elif 45 <= (self.player.direction % 360) < 135: self.swordsprite.rect.left -= 5 self.swordsprite.rect.top += 5 elif 135 <= (self.player.direction % 360) < 225: self.swordsprite.rect.top += 12 self.swordsprite.rect.left -= 6 elif 225 <= (self.player.direction % 360) < 315: self.swordsprite.rect.left -= 16 self.swordsprite.rect.top += 5 pass s.phase += 1 #Animations needed: #Sword swing x #Death #Door opening #Chest opening if s.name == "health": if s.phase >= 13: self.animations.remove(s) pygame.event.post(pygame.event.Event(healthEvent)) continue s.sprite.image = SimpleRectSprite(pygame.Rect(s.sprite.rect), self.heartTexture.subsurface(pygame.Rect((s.phase) * 8, 0, 8, 8)), True).image s.phase += 1 for char in self.entities: if char.moving: char.walking_phase = char.walking_phase + 0.5 char.update_sprite() if char.stunned: if not char.red_blink: pixels = pygame.PixelArray(char.image) pixels.replace(BLACK, RED, 0.9) char.image = pixels.surface char.red_blink = True else: char.red_blink = False char.update_sprite() elif char.red_blink: char.red_blink = False char.update_sprite() if event.type == swordSwingEvent: boxes = self.make_surrounding_blocks(self.player.collision_rect) blocks = pygame.sprite.Group() blocks.add(boxes[self.player.direction/45]) #blocks.add(boxes[((self.player.direction/45) + 1) % 8]) for sprite in pygame.sprite.groupcollide(self.npcs, blocks, False, True): sprite.hit() if event.type == unstunEvent: for entity in self.entities: if entity.stunned: entity.stunned = False if entity.health <= 0: entity.kill() entity = None if event.type == healthEvent: if self.player.health > self.player.maxHealth: self.player.health = self.player.maxHealth - 1 self.player.displayHealth = self.player.maxHealth if self.player.health <= 0: self.manager.go_to(GameOverScene()) if self.player.displayHealth != self.player.health: params = {'sprite': self.heartList[self.player.displayHealth-1], 'jumpdistance': 8, 'phase': 0, } self.animations.append(Animation("health", params)) self.player.displayHealth -= 1 if event.type == actionEvent: # When the player presses the action key surrounding_blocks = self.make_surrounding_blocks(self.player.collision_rect) blocks = pygame.sprite.Group() blocks.add(surrounding_blocks[self.player.direction / 45], Block(self.player.collision_rect, BLACK)) for door in pygame.sprite.groupcollide(self.doors, blocks, False, False): if not door.locked: if not door.is_open: door.toggle() self.grid.update_grid(self.collidables + self.character_collision_boxes) elif self.player.keys > 0: self.player.keys -= 1 door.unlock()
class Gui_Client(object): __highlight_triggers = False __image_pool = {} __mouse_cursor = None __mouse_pos = (0, 0) # ------------------------------------------------------------------------------ def __init__(self): self.graphic_ini = self.__read_text_file(GRAPHIC_INI_FILEPATH) self.highlight_triggers_on() # ------------------------------------------------------------------------------ def init(self, moo2_dir): self.moo2_dir = moo2_dir self.__load_lbx_archives() self.__load_fonts() self.__load_palettes() self.__load_graphic(self.graphic_ini[:1]) self.__load_ships_lbx() pygame.init() pygame.display.set_mode((640, 480), 0, 24) self.DISPLAY = pygame.display.get_surface() screen = Gui_Screen.Gui_Screen() screen.init(self) # ------------------------------------------------------------------------------ def get_display(self): """Returns Pygame Display Surface object Will be removed in the near future """ return pygame.display.get_surface() # ------------------------------------------------------------------------------ def highlight_triggers_on(self): """Enables the triggers highlightling""" self.b_highlight_triggers = True # ------------------------------------------------------------------------------ def highlight_triggers_off(self): """Disables the triggers highlightling""" self.b_highlight_triggers = False # ------------------------------------------------------------------------------ def flip(self, src=None): """Flips the display buffer content and redraws the mouse cursor""" if self.mouse_cursor: bg_area = pygame.Rect(self.mouse_pos, self.mouse_cursor_size) cursor_bg = pygame.Surface(self.mouse_cursor_size) cursor_bg.blit(self.DISPLAY, (0, 0), bg_area) self.DISPLAY.blit(self.mouse_cursor, self.mouse_pos) pygame.display.flip() self.DISPLAY.blit(cursor_bg, self.mouse_pos) else: pygame.display.flip() # ------------------------------------------------------------------------------ def update(self, rects=None): """Pushes given portions of graphic buffer to display""" pygame.display.update(rects) # ------------------------------------------------------------------------------ def __read_text_file(self, filename): """Returns the content of the given text file as a list of strings""" fh = open(filename, 'rt') content = fh.read().strip().split("\n") fh.close() return content # ------------------------------------------------------------------------------ def __load_lbx_archives(self): """Loads LBX archives listed in lbx.md5 file. The files are checked for a given MD5 sum. returns True if all loaded files match their expected checksum, otherwise returns False """ print("Loading LBX archive index") self.lbx = {} lbx_md5 = self.__read_text_file(LBX_MD5_FILEPATH) check = True for line in lbx_md5: md5, filename = line.strip().split(" ") self.lbx[filename] = Moo2_LBX.Archive( "%s/%s" % (self.moo2_dir, filename), md5) if self.lbx[filename].check_md5(): print(" %s %s ... OK" % (md5, filename)) else: print(" %s %s ... error" % (md5, filename)) print(" MD5 sum does not match, actual MD5 sum is %s" % self.lbx[filename].md5_hexdigest()) check = False print("") if check: print(" Done") else: print(" Done with LBX loading errors: (MD5 checksum mismatch)") #print(" >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>") #print(" Warning!") #print("") #print(" Some LBX files don't match the expected MD5 checksum") #print(" The OpenMOO2 supports only original LBX files from MOO2 version 1.31") #print("") #print(" <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<") return check # ------------------------------------------------------------------------------ def __load_fonts(self): """Loads up the game fonts""" self.fonts = { 'font1': self.lbx['FONTS.LBX'].read_font(0), 'font2': self.lbx['FONTS.LBX'].read_font(1), 'font3': self.lbx['FONTS.LBX'].read_font(2), 'font4': self.lbx['FONTS.LBX'].read_font(3), 'font5': self.lbx['FONTS.LBX'].read_font(4), 'font6': self.lbx['FONTS.LBX'].read_font(5) } # ------------------------------------------------------------------------------ def get_font(self, font_id): """Returns a graphical font identified by font_id""" return self.fonts[font_id] # ------------------------------------------------------------------------------ def __load_palettes(self): """Loads a color palettes""" self.raw_palettes = { 'FONTS_01': self.lbx['FONTS.LBX'].read_palette(1), 'FONTS_02': self.lbx['FONTS.LBX'].read_palette(2), 'FONTS_03': self.lbx['FONTS.LBX'].read_palette(3), 'FONTS_04': self.lbx['FONTS.LBX'].read_palette(4), 'FONTS_05': self.lbx['FONTS.LBX'].read_palette(5), 'FONTS_06': self.lbx['FONTS.LBX'].read_palette(6), 'FONTS_07': self.lbx['FONTS.LBX'].read_palette(7), 'FONTS_08': self.lbx['FONTS.LBX'].read_palette(8), 'FONTS_09': self.lbx['FONTS.LBX'].read_palette(9), 'FONTS_10': self.lbx['FONTS.LBX'].read_palette(10), 'FONTS_11': self.lbx['FONTS.LBX'].read_palette(11), 'FONTS_12': self.lbx['FONTS.LBX'].read_palette(12), 'FONTS_13': self.lbx['FONTS.LBX'].read_palette(13), 'IFONTS_1': self.lbx['IFONTS.LBX'].read_palette(1), 'IFONTS_2': self.lbx['IFONTS.LBX'].read_palette(2), 'IFONTS_3': self.lbx['IFONTS.LBX'].read_palette(3), 'IFONTS_4': self.lbx['IFONTS.LBX'].read_palette(4) } self.palettes = { 'APP_PICS': copy.deepcopy(self.raw_palettes['FONTS_02']), 'BUFFER0': copy.deepcopy(self.raw_palettes['FONTS_02']), 'COLBLDG': copy.deepcopy(self.raw_palettes['FONTS_02']), 'COLONY2': copy.deepcopy(self.raw_palettes['FONTS_02']), 'COLPUPS': copy.deepcopy(self.raw_palettes['FONTS_02']), 'COLSUM': copy.deepcopy(self.raw_palettes['FONTS_02']), 'COLSYSDI': copy.deepcopy(self.raw_palettes['FONTS_02']), 'GAME': copy.deepcopy(self.raw_palettes['FONTS_01']), 'INFO': copy.deepcopy(self.raw_palettes['FONTS_01']), 'MAINMENU': copy.deepcopy(self.raw_palettes['FONTS_06']), 'OFFICER': copy.deepcopy(self.raw_palettes['FONTS_02']), 'PLANETS': copy.deepcopy(self.raw_palettes['FONTS_02']), 'RACEICON': copy.deepcopy(self.raw_palettes['FONTS_02']), 'SR_R9_SC': copy.deepcopy(self.raw_palettes['FONTS_02']), 'SHIPS': copy.deepcopy(self.raw_palettes['IFONTS_3']) } # ------------------------------------------------------------------------------ def __get_img_key(self, img_key, subkey1=None, subkey2=None, subkey3=None): """Helper method - returns whole image key from given parts""" for subkey in [subkey1, subkey2, subkey3]: if subkey is None: break img_key += ".%s" % subkey ## print img_key return img_key # ------------------------------------------------------------------------------ def set_image(self, image_data, img_key, subkey1=None, subkey2=None, subkey3=None): """Stores a given image object to image pool udner given image key""" self.__image_pool[self.__get_img_key(img_key, subkey1, subkey2, subkey3)] = image_data # ------------------------------------------------------------------------------ def get_image(self, img_key, subkey1=None, subkey2=None, subkey3=None): """Returns an image object from image pool identified by image key""" full_key = self.__get_img_key(img_key, subkey1, subkey2, subkey3) if self.has_image(full_key): return self.__image_pool[full_key] else: print "ERROR: get_image(%s) failed" % full_key return None # ------------------------------------------------------------------------------ def has_image(self, img_key, subkey1=None, subkey2=None, subkey3=None): """Returns True if image pool contains required image key""" return self.__image_pool.has_key( self.__get_img_key(img_key, subkey1, subkey2, subkey3)) # ------------------------------------------------------------------------------ def __load_lbx_solid_image(self, lbx_key, picture_id, palette_key, img_key, subkey1=None, subkey2=None, subkey3=None): """Loads an LBX image object into image pool, the image is considered as non-transparent""" self.set_image( self.lbx[lbx_key].get_surface(picture_id, 0, self.palettes[palette_key], None), img_key, subkey1, subkey2, subkey3) # ------------------------------------------------------------------------------ def __load_lbx_transparent_image(self, lbx_key, picture_id, palette_key, color_key, img_key, subkey1=None, subkey2=None, subkey3=None): """Loads an LBX image object into image pool, transparent LBX image has once color that is considered as fully transparent""" self.set_image( self.lbx[lbx_key].get_surface(picture_id, 0, self.palettes[palette_key], color_key), img_key, subkey1, subkey2, subkey3) # ------------------------------------------------------------------------------ def get_planet_background(self, terrain_id, picture_index): """Returns planet background image object from image pool""" bg_pics = [0, 3, 6, 9, 12, 15, 18, 23, 24, 27] img_index = bg_pics[terrain_id] + picture_index if not self.has_image('background', 'planet_terrain', img_index): self.__load_lbx_transparent_image('PLANETS.LBX', img_index, 'PLANETS', 0x0, 'background', 'planet_terrain', img_index) return self.get_image('background', 'planet_terrain', img_index) # ------------------------------------------------------------------------------ def __load_graphic(self, graphic_ini): """Loads images to image pool graphic_ini is supposed to be a list of strings from graphic.ini (each line = one string) Only LBX archive images are supported now, but can be extended to support any common graphical format e.g. PNG, JPG or GIF """ print "Loading graphic..." for line in graphic_ini: # if line and line[0] != "#": # print line line = line.split("=", 1) img_keys = line[0].strip().split(".", 3) # print img_keys subkey1 = subkey2 = subkey3 = None img_key = img_keys.pop(0) if len(img_keys): subkey1 = str(img_keys.pop(0)) if len(img_keys): subkey2 = str(img_keys.pop(0)) if len(img_keys): subkey3 = str(img_keys.pop(0)) options = line[1].split("|") source_file = options[0].strip() source_type = source_file.split(".")[-1].lower() # TODO: add support for non-original graphic if source_type == "lbx": # original LBX image = source_file | source_index | palette_key | <transparent> source_index = int(options[1].strip()) lbx_palette = options[2].strip() lbx_transparent = (len(options) == 4) and (options[3].strip() == "transparent") if lbx_transparent: self.__load_lbx_transparent_image(source_file, source_index, lbx_palette, 0x00, img_key, subkey1, subkey2, subkey3) else: self.__load_lbx_solid_image(source_file, source_index, lbx_palette, img_key, subkey1, subkey2, subkey3) print "... Loading graphic Done" # ------------------------------------------------------------------------------ def __load_ships_lbx(self, color='all', file='ships_lbx.ini'): """Loads ships to image pool Either loads all ships of all colors (color=all) or only of one color. All ships are in ship.lbx in blocks, every color in it's own block of 50 images. There are 8 blocks for each color and one (400-449) that has monsters and Antarans. This is in a separate method because there are ~400 images in the lbx to load, too many to put into lbx.md5 file """ block_length = 50 # from the ships.lbx file. colors = [ 'red', 'yellow', 'green', 'white', 'blue', 'brown', 'purple', 'orange' ] if color == 'all': for j in xrange(len(colors)): self.__load_ships_lbx(colors[j]) if color in colors: i = colors.index(color) offset = block_length * i for ii in range(50): idx = offset + ii #self.__load_lbx_transparent_image('SHIPS.LBX', idx, str(ii%17+1), 0x00, 'SHIP', i, ii) self.__load_lbx_transparent_image('SHIPS.LBX', idx, 'SHIPS', 0x00, 'SHIP', i, ii) return print('->loading ships...finished') # ------------------------------------------------------------------------------ def draw_line(self, (x1, y1), (x2, y2), color_list): """ Draws a line from [x1, y1] to [x2, y2] using the list of colors as pixel bitmap. The colors from list are used around one by one. If there's only one color in the list the line drawing is passed to pygame.draw_lie If the color list is empty, no drawing is performed """ cols = len(color_list) if cols == 0: """no color, no drawing...""" elif cols == 1: """in case of 1 color line use original pygame function""" return pygame.draw.line(self.DISPLAY, color_list[0], (x1, y1), (x2, y2), 1) else: xx = float(x2 - x1) yy = float(y2 - y1) if xx == 0: xxx = 0 yyy = 1 elif yy == 0: xxx = 1 yyy = 0 else: xxx = min(abs(xx / yy), 1) * (xx / abs(xx)) yyy = min(abs(yy / xx), 1) * (yy / abs(yy)) pxarray = pygame.PixelArray(self.DISPLAY) x, y = float(x1), float(y1) pixel_count = int(max(abs(xx), abs(yy))) for i in range(pixel_count): pxarray[int(round(x))][int(round(y))] = color_list[i % cols] x += xxx y += yyy rect = pygame.Rect(x1, y1, x2, y2) rect.normalize() return rect
bitmap[(x + y * w) * 3 + 2] = data[pixel_offset + x * 3 + 2] pixel_offset += pitch return (w, h, 24, bitmap) # Create a 640x480 window with 24 BPP. WINDOW_W = 640 WINDOW_H = 480 pygame.display.init() window = pygame.display.set_mode([WINDOW_W, WINDOW_H], 0, 24) # Load a test bitmap. image_w, image_h, image_bpp, image_data = MyLoadBMP("test.bmp") # "Manually" copy the lines of the loaded bitmap to the pygame frame buffer. pixels = pygame.PixelArray(window) center_x = (WINDOW_W - image_w) // 2 center_y = (WINDOW_H - image_h) // 2 for y in range(image_h): for x in range(image_w): pixel = image_data[(x + y * image_w) * 3:(x + y * image_w) * 3 + 3] pixel = pixel[0] | (pixel[1] << 8) | (pixel[2] << 16) pixels[center_x + x, center_y + y] = pixel # Redraw the screen (i.e. display the frame buffer we were drawing on). pygame.display.flip() # Wait until the window is closed or the ESC button is pressed. while True: event = pygame.event.wait() if event.type == KEYDOWN and event.key == K_ESCAPE:
BLACK=(0,0,0) RED=(255,0,0) GREEN=(0,255,0) BLUE=(0,0,255) YELLOW=(255,255,0) CYAN=(0,255,255) PURPLE=(255,0,255) COLOR=(WHITE,BLACK,RED,GREEN,BLUE,YELLOW,CYAN,PURPLE) SCREEN_X=800 SCREEN_Y=600 setDisplay=pygame.display.set_mode((SCREEN_X,SCREEN_Y)) singlePixel=pygame.PixelArray(setDisplay) while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() while 1: color=COLOR[random.randint(0,7)] xpos=random.randint(1,SCREEN_X) ypos=random.randint(1,SCREEN_Y) if xpos >SCREEN_X: sys.exit() if ypos>SCREEN_Y:
def _noise_patch(env="gaussian", size=96, stdev=12, col1="white", col2="black", bgmode="avg"): """ Returns a pygame surface containing a noise patch. See canvas.noise_patch() """ env = _match_env(env) # Generating a noise patch takes quite some time, so keep # a cache of previously generated noise patches to speed up # the process. global canvas_cache key = "noise_%s_%s_%s_%s_%s_%s" % (env, size, stdev, col1, col2, bgmode) if key in canvas_cache: return canvas_cache[key] # Create a surface surface = pygame.Surface((size, size)) px = pygame.PixelArray(surface) col1 = _color(col1) col2 = _color(col2) # rx and ry reflect the real coordinates in the # target image for rx in range(size): for ry in range(size): # Distance from the center ux = rx - 0.5 * size uy = ry - 0.5 * size r = math.sqrt(ux**2 + uy**2) # Get the amplitude without the envelope (0 .. 1) amp = random.random() # The envelope adjustment if env == "g": f = math.exp(-0.5 * (ux / stdev)**2 - 0.5 * (uy / stdev)**2) elif env == "l": f = max(0, (0.5 * size - r) / (0.5 * size)) elif env == "c": if (r > 0.5 * size): f = 0.0 else: f = 1.0 else: f = 1.0 # Apply the envelope if bgmode == "avg": amp = amp * f + 0.5 * (1.0 - f) else: amp = amp * f r = col1.r * amp + col2.r * (1.0 - amp) g = col1.g * amp + col2.g * (1.0 - amp) b = col1.b * amp + col2.b * (1.0 - amp) px[rx][ry] = r, g, b canvas_cache[key] = surface del px return surface
pygame.init() pygame.camera.init() image = pygame.image.load("/home/janek/Bilder/camera/hand1.jpg") SIZE = (400,300) screen = pygame.display.set_mode(SIZE) SIZE = screen.get_size() b = pygame.transform.scale(image,SIZE) image = pygame.Surface(SIZE) image.blit(b,(0,0)) WIDTH = image.get_width() HEIGHT = image.get_height() SIZE = image.get_size() image.set_alpha(255) pix = pygame.PixelArray(image) i = 0 render = True print(len(pix)) print(len(pix[0])) #pix.replace((0,0,0),(0,0,0),.1) def want(): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() for x in range(WIDTH): for y in range(HEIGHT):
if event.type == pg.KEYDOWN: if event.key == pg.K_ESCAPE: quit() max_vel = 5 cir = lambda pos, color, radi: pg.draw.circle(window, C_BWRGBYCM[color], (int( pos[0]), int(pos[1])), radi, 0) objec = [[ randint(0, width), randint(0, height), randint(-max_vel, max_vel), randint(-max_vel, max_vel) ] for i in range(2000)] maper = lambda vari, minV, maxV, minO, maxO: (vari - minV) / (maxV - minV) * ( maxO - minO) + minO pixel = tuple(pg.PixelArray(window)) while 1: event_check() window.fill(C_BWRGBYCM[0]) schem = [[0 for y in range(0, width)] for x in range(0, width)] for point in objec: for x in range(0, width): for y in range(0, height): dis = dist((point[0], point[1]), (x, y)) if dis <= 55: col = int(maper(dis, 0, 55, 55, 0)) else: col = 0 schem[x][y] += col # pixel[x][y]=(col,col,col) point[0] += point[2] point[1] += point[3] if point[0] <= 0: point[2] *= -1
DISPLAYSURF.fill(WHITE) #Surface.fill(color) : Filled a surface with coloar ''' pygame.draw : Draw a figure If 'width' parameter bigger then 0, draw a non filled figure ''' pygame.draw.polygon(DISPLAYSURF, GREEN, ((146, 0), (291, 106), (236, 277), (56, 277), (0, 106))) pygame.draw.line(DISPLAYSURF, BLUE, (60, 60), (120, 60), 4) pygame.draw.line(DISPLAYSURF, BLUE, (120, 60), (60, 120)) pygame.draw.line(DISPLAYSURF, BLUE, (60, 120), (120, 120), 4) pygame.draw.circle(DISPLAYSURF, BLUE, (300, 50), 20, 0) pygame.draw.ellipse(DISPLAYSURF, RED, (300, 250, 40, 80), 1) pygame.draw.rect(DISPLAYSURF, RED, (200, 150, 100, 50)) ''' pygame.PixelArray(Surface) : Return pixels of surface, We will access random pixel that used '[]' operator ''' pixObj = pygame.PixelArray(DISPLAYSURF) pixObj[480][380] = BLACK pixObj[482][382] = BLACK pixObj[484][384] = BLACK pixObj[486][386] = BLACK pixObj[488][388] = BLACK del pixObj #'del' is python keyword that delete memory while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit()
def scavengersAttack(self, displaySurface, width, height, step): finished = False currentTimer = 0 lowerThird = int(6*(g.height/10)) centerWidth = int(g.width/16)*2 displaySurface.fill(g.BLACK) # Reset image buffer. # Print the Scavenger's analysis and orders. if self.scavengerStep <= 6: # Show the ship being examined displaySurface.blit(self.shipScaled, (0, 0)) self.bufferSurfaceImage.set_colorkey(g.RED) self.bufferSurfaceImage.set_colorkey(g.BLACK) if self.scavengerStep < 6: currentTimer = 3 if self.scavengerStep >= 1: h.renderText([self.introText6[0]], g.font, displaySurface, g.GREEN, 0, centerWidth, lowerThird) if self.scavengerStep >= 2: h.renderText([self.introText6[1]], g.font, displaySurface, g.GREEN, 0, centerWidth, lowerThird+(g.offset)) if self.scavengerStep >= 3: h.renderText([self.introText6[2]], g.font, displaySurface, g.GREEN, 0, centerWidth, lowerThird+(g.offset*2)) if self.scavengerStep >= 4: h.renderText([self.introText6[3]], g.font, displaySurface, g.GREEN, 0, centerWidth, lowerThird+(g.offset*3)) if self.scavengerStep >= 5: h.renderText([self.introText6[4]], g.font, displaySurface, g.GREEN, 0, centerWidth, lowerThird+(g.offset*4)) # Now we switch to shrinking the screen into the viewing panel. if self.scavengerStep == 6: # No Timer, this needs to be FAST! self.bufferSurfaceImage = pygame.Surface((g.width,g.height)) self.bufferSurfaceImage.set_colorkey(g.RED) self.bufferSurfaceImage.fill(g.BLACK) self.bufferSurfaceImage.set_colorkey(g.BLACK) self.bufferSurfaceImage.blit(displaySurface, (0, 0)) # Surface prepared! self.scavengerStep += 1 elif (self.scavengerStep >= 7 and self.scavengerStep <= 13): self.shrinkBufferSurface(self.scavengerStep-6) displaySurface.set_colorkey(g.RED) displaySurface.fill(g.BLACK) displaySurface.set_colorkey(g.BLACK) displaySurface.blit(self.bufferSurfaceImage, (int((g.width/16)*((self.scavengerStep-6)*1.6)), int((g.height/10)*(self.scavengerStep-6)))) self.scavengerStep += 1 # Backup display into Buffer. elif self.scavengerStep == 14: # Insert sacred pixel of bug fix! #bugFix = pygame.PixelArray(displaySurface) # Ommmmm... #bugfix[0][0] = (1,1,1) # *Monk chant* de sacra pixel insertis bugfix *bell toll* #bugfix.close() # No Timer, this needs to be FAST! #self.bufferSurfaceImage = displaySurface.copy() # Prior Surface sampled! self.scavengerStep += 1 # Prepare display surface for later frames. if (self.scavengerStep >= 15 and self.scavengerStep <= 279): displaySurface.set_colorkey(g.RED) displaySurface.fill(g.BLACK) displaySurface.set_colorkey(g.BLACK) displaySurface.blit(self.bufferSurfaceImage, (int((g.width/16)*(7*1.6)), int((g.height/10)*7))) if (self.scavengerStep >= 15 and self.scavengerStep <= 270): # No Timer, this needs to be FAST! # TODO: Fix mysterous bug here! # Note: Voodoo bug! Looks to be hardware surface mapping issue! # Surface prepared! self.alienShipScaled.set_alpha(0 + (self.scavengerStep-15)) if self.scavengerStep == 270: self.scavengerStep = 272 else: self.scavengerStep += 5 # Draw Command Deck if (self.scavengerStep >= 15 and self.scavengerStep <= 279): displaySurface.blit(self.alienShipScaled, (0, 0)) # Make dot move twice to Thrice. # Then draw reticules (3 of em, largest to smallest, 1 at a time). # Need to draw ship dot moving into position on X and Y screens. if self.scavengerStep >= 272 and self.scavengerStep <= 275: currentTimer = 1 adjustment = self.scavengerStep-272 displayArray = pygame.PixelArray(displaySurface) displayArray[int((g.width/320)*183)-adjustment, int((g.height/200)*131)+adjustment] = g.WHITE displayArray[int((g.width/320)*62), int((g.height/200)*148)+adjustment] = g.WHITE displayArray.close() # Draw targeting reticule. elif self.scavengerStep >= 276 and self.scavengerStep <= 279: currentTimer = 1 # Temp. circles = self.scavengerStep-275 displayArray = pygame.PixelArray(displaySurface) displayArray[int((g.width/320)*180), int((g.height/200)*134)] = g.WHITE displayArray[int((g.width/320)*62), int((g.height/200)*151)] = g.WHITE displayArray.close() h.targettingReticule(displaySurface, int((g.width/320)*180), int((g.height/200)*134), g.VILE_PINK, circles, 4, 1) h.targettingReticule(displaySurface, int((g.width/320)*62), int((g.height/200)*151), g.VILE_PINK, circles, 4, 1) if self.scavengerStep >= 280: finished = True # Our timer for this sequence. if h.GameStopwatch.stopwatchSet: if h.GameStopwatch.getElapsedStopwatch() > currentTimer: h.GameStopwatch.resetStopwatch() self.scavengerStep += 1 else: h.GameStopwatch.setStopwatch() return finished
tile_size = 32 map_size = 16 RED = (255,0,0) # класный цвет BLUE = (0,0,255) # синий map = Map(map_size, map_size) # создадим приведение ghost = Ghost(0, 0, tile_size, map_size) while not map.set(ghost,random.randint(0,15),random.randint(0,15)): # поищем место чтобы не в стене pass # добавим еще приведение # ghost2 = Ghost(0, 0, tile_size, map_size) ghost2=SmartGhost(0,0,tile_size,map_size) # картинка приведения у нас только одна - # перекрасим приведение в синий цвет pxarr = pygame.PixelArray(ghost2.image) # подсмотрено в интернете pxarr.replace(RED, BLUE,0.5) # как перекрашивать del pxarr # важно удалять объект PixelArray - иначе не работает дольше while not map.set(ghost2,random.randint(0,15),random.randint(0,15)): pass # создадим пакмана pacman = Pacman(5, 5, tile_size, map_size) while not map.set(pacman,random.randint(0,15),random.randint(0,15)): pass background = None #pygame.image.load("./resources/background.png") screen = pygame.display.get_surface() while 1: # здесь основной цикл process_events(pygame.event.get(), pacman) pygame.time.delay(100)
print(len(pixels)) running = True while running: clock.tick(FPS) for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() # add any other events here (keys, mouse, etc.) # Game loop part 2: Updates ##### # Game loop part 3: Draw ##### screen.fill(GREEN) canvas = pygame.PixelArray(screen) for i in range(len(pixels) // width): for j in range(width): if j + i * width >= len(pixels): break v = pixels[j + i * width] * 0x111111 canvas[j * 2 + 0, i * 2 + 0] = v canvas[j * 2 + 1, i * 2 + 0] = v canvas[j * 2 + 0, i * 2 + 1] = v canvas[j * 2 + 1, i * 2 + 1] = v canvas[1012 * 4 // 5, i] = 0x6622ff canvas.close() # after drawing, flip the display pygame.display.flip()
def load_level(level, width, height): """ Load the level number n from the file level_n.png The pixels form a 5 row 10 column grid covering 50% of the screen leaving the top 20% and the bottom 30% empty """ try: im_surf = pygame.image.load( os.path.join("levels", "level_{}.png".format(level))) except pygame.error: raise NoMoreLevels() if im_surf.get_size() != (10, 5): raise RuntimeError("Level files must be 10 pixels wide by 5 pixels " "high. This one is {}".format(im_surf.get_size())) pixels = pygame.PixelArray(im_surf) grid_width = int(width / 10) grid_height = int(height / 10) bricks = [] for x in range(10): for y in range(5): left = x * grid_width top = (y + 2) * grid_height colour = im_surf.unmap_rgb(pixels[x, y])[:3] # Strip alpha if colour == (0, 0, 0): # Black pixel: no brick continue elif colour == (255, 0, 0): # Red pixel: brick with 1 life bricks.append( Brick(pygame.Rect(left, top, grid_width, grid_height), colour, 1)) elif colour == (255, 255, 0): # Yellow pixel: brick with 2 life bricks.append( Brick(pygame.Rect(left, top, grid_width, grid_height), colour, 2)) elif colour == (0, 255, 0): # Green pixel: brick with 3 life bricks.append( Brick(pygame.Rect(left, top, grid_width, grid_height), colour, 3)) elif colour == (0, 0, 255): # Blue pixel: brick with 1 life and multi-ball release! bricks.append( Brick(pygame.Rect(left, top, grid_width, grid_height), colour, 1, multiball=True)) elif colour == (255, 0, 255): # Pink pixel: brick with 1 life inverted ball bouncing bricks.append( Brick(pygame.Rect(left, top, grid_width, grid_height), colour, 1, invert=True)) elif colour == (100, 100, 100): # Grey pixel: indestructible brick bricks.append( Brick(pygame.Rect(left, top, grid_width, grid_height), colour, -1)) else: raise RuntimeError("Invalid colour {} encountered in level {}" "".format(colour, level)) return bricks
BLUE = (0, 0, 255) #draw on the HiRez HiRez.fill(WHITE) pygame.draw.polygon(HiRez,GREEN,((146, 0),(291,106),(236,277),(56,277)\ ,(0,106))) pygame.draw.line(HiRez, BLUE, (60, 60), (120, 60), 4) pygame.draw.line(HiRez, BLUE, (120, 60), (60, 120)) pygame.draw.line(HiRez, BLUE, (60, 120), (120, 120), 4) pygame.draw.circle(HiRez, BLUE, (300, 50), 20, 0) pygame.draw.ellipse(HiRez, RED, (300, 250, 40, 80), 1) pygame.draw.rect(HiRez, RED, (200, 150, 100, 50)) pix = pygame.PixelArray(HiRez) pix[480][380] = BLACK pix[482][382] = BLACK pix[484][384] = BLACK pix[486][384] = BLACK pix[488][388] = BLACK del pix while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() pygame.display.update()
import pygame pygame.init() white, black = (255,255,255), (0,0,0) red, green, blue = (255,0,0), (0,255,0), (0,0,255) display_width, display_height = 800, 600 gameDisplay = pygame.display.set_mode((display_width, display_height)) gameDisplay.fill(black) pixAr = pygame.PixelArray(gameDisplay) # convert gameDisplay to pixel array. pixAr[10][20] = green # plot pixel in x,y coordinate (10,20) pygame.draw.line(gameDisplay, blue, (100,200), (300,450), 5) # draw line x1,y1,x2,y2,thickness. pygame.draw.rect(gameDisplay, red, (400,400,50,20)) # draw rectangle x,y,width,height. pygame.draw.circle(gameDisplay, white, (150,150),75) # draw circle x,y,radius. pygame.draw.polygon(gameDisplay, green, ((225,275),(275,400),(300,450),(400,400))) # draw polygon with list of tuples with x,y. while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() pygame.display.update()
def __init__(self,fname): self.img = pygame.image.load(fname) self.pa = pygame.PixelArray(self.img)
pygame.transform.scale(buffer, (256 * 3, 192 * 3), screen) pygame.display.flip() fp = file("level1.pl5", "rb") paleta_file = fp.read() fp.close() # Close file paleta = [] for i in range(0, 16): color1 = struct.unpack("B", paleta_file[2 * i])[0] color2 = struct.unpack("B", paleta_file[2 * i + 1])[0] r = (color1 << 1) & 0xf0 b = (color1 << 5) & 0xf0 g = color2 << 5 paleta.append([r, g, b]) # Convert file read into an array of RGB values pixels = pygame.PixelArray(tiles_image) imagen = [] for y in range(0, 16): for x in range(0, 128): px = [(pixels[2 * x, y] >> 16) & 255, (pixels[2 * x, y] >> 8) & 255, pixels[2 * x, y] & 255] px1 = closest_color(px, paleta) px = [(pixels[2 * x + 1, y] >> 16) & 255, (pixels[2 * x + 1, y] >> 8) & 255, pixels[2 * x + 1, y] & 255] px2 = closest_color(px, paleta) imagen.append(px1 * 16 + px2) export_tileset(imagen, 'armas.SR5')
pygame.display.set_caption('Shapes') black = (0, 0, 0) red = (255, 0, 0) white = (255, 255, 255) green = (0, 255, 0) blue = (0, 0, 255) DISPLAYSURF.fill(white) pygame.draw.line(DISPLAYSURF, blue, (60, 60), (60, 120), 4) pygame.draw.line(DISPLAYSURF, blue, (100, 60), (60, 95), 2) pygame.draw.line(DISPLAYSURF, blue, (60, 95), (100, 120), 2) pygame.draw.circle(DISPLAYSURF, red, (300, 50), 20, 0) pygame.draw.ellipse(DISPLAYSURF, red, (300, 200, 40, 80), 1) pygame.draw.rect(DISPLAYSURF, green, (200, 150, 100, 50)) pix = pygame.PixelArray(DISPLAYSURF) pix[380][280] = black pix[382][282] = black pix[384][284] = black pix[386][286] = black pix[388][288] = black del pix while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() pygame.display.update()
def _gabor(orient, freq, env="gaussian", size=96, stdev=12, phase=0, col1="white", col2="black", bgmode="avg"): """ Returns a pygame surface containing a Gabor patch See canvas.gabor() """ env = _match_env(env) # Generating a Gabor patch takes quite some time, so keep # a cache of previously generated Gabor patches to speed up # the process. global canvas_cache key = "gabor_%s_%s_%s_%s_%s_%s_%s_%s_%s" % (orient, freq, env, size, stdev, phase, col1, col2, bgmode) if key in canvas_cache: return canvas_cache[key] # Create a surface surface = pygame.Surface((size, size)) px = pygame.PixelArray(surface) # Conver the orientation to radians orient = math.radians(orient) col1 = _color(col1) col2 = _color(col2) # rx and ry reflect the real coordinates in the # target image for rx in range(size): for ry in range(size): # Distance from the center dx = rx - 0.5 * size dy = ry - 0.5 * size # Get the coordinates (x, y) in the unrotated # Gabor patch t = math.atan2(dy, dx) + orient r = math.sqrt(dx**2 + dy**2) ux = r * math.cos(t) uy = r * math.sin(t) # Get the amplitude without the envelope (0 .. 1) amp = 0.5 + 0.5 * math.cos(2.0 * math.pi * (ux * freq + phase)) # The envelope adjustment if env == "g": f = math.exp(-0.5 * (ux / stdev)**2 - 0.5 * (uy / stdev)**2) elif env == "l": f = max(0, (0.5 * size - r) / (0.5 * size)) elif env == "c": if (r > 0.5 * size): f = 0.0 else: f = 1.0 else: f = 1.0 # Apply the envelope if bgmode == "avg": amp = amp * f + 0.5 * (1.0 - f) else: amp = amp * f r = col1.r * amp + col2.r * (1.0 - amp) g = col1.g * amp + col2.g * (1.0 - amp) b = col1.b * amp + col2.b * (1.0 - amp) px[rx][ry] = r, g, b canvas_cache[key] = surface del px return surface
return (redre, greenre, bluere) #1-trit mono channel conversion. (used with 3-trit RGB) def shadlook0(string): if string == "-": return 0 if string == "0": return 127 if string == "+": return 255 dispsurf0 = pygame.Surface((114, 81)) dispsurf1 = pygame.Surface((54, 38)) dispsurf0pixarray = pygame.PixelArray(dispsurf0) dispsurf1pixarray = pygame.PixelArray(dispsurf1) #precompute mono display mapped values g0m1 = dispsurf1.map_rgb((127, 127, 127)) gnm1 = dispsurf1.map_rgb((0, 0, 0)) gpm1 = dispsurf1.map_rgb((255, 255, 255)) g0m0 = dispsurf0.map_rgb((127, 127, 127)) gnm0 = dispsurf0.map_rgb((0, 0, 0)) gpm0 = dispsurf0.map_rgb((255, 255, 255)) #mapped lookup functions for 1-trit mono display modes. def shadlook0mapped1(string): if string == "-":
def moo2_draw_image_frame(surface, picture, frame, localPalette, x=0, y=0, DEBUG=None): # localPalette = [] # debug_output(" Drawing frame #%i (frame offset is 0x%x)" % (frame, picture['offsets'][frame])) # print "* globalPalette: " + str(globalPalette) # print "globalPalette ID: " + str(id(globalPalette)) # localPalette = copy.deepcopy(globalPalette) # localPalette = globalPalette[:] # localPalette = globalPalette # print "localPalette ID: " + str(id(localPalette)) # print # print "* localPalette: " + str(localPalette) # print "tested palette ... before applycation of local palette: " + str(localPalette) # print "tested palette ... before applycation of local palette: " + str(localPalette) # return # print picture['palette'][1] # dump set the black color as transparent, let's see if it will break something :-O px = pygame.PixelArray(surface) pos = 12 + (len(picture['offsets']) << 2) # offset * 4 if picture['f_junction']: debug_output(" TODO: junction") if picture['f_functional_color']: debug_output(" TODO: functional color") if picture['f_fill_background']: # FIXME: COLORKEY is hardcoded, should be determined somehow? surface.fill(COLORKEY) surface.set_colorkey(COLORKEY) if picture['f_no_compression']: debug_output(" TODO: no compression") if picture['f_internal_palete']: # debug_output(" Image has local palette") colorShift = ord( picture['data'][pos]) + (ord(picture['data'][pos + 1]) << 8) pos += 2 localColors = ord( picture['data'][pos]) + (ord(picture['data'][pos + 1]) << 8) pos += 2 # debug_output(" Local palette shift: " + str(colorShift)) # debug_output(" Local palette colors: " + str(localColors)) for i in range(localColors): a = ord(picture['data'][pos]) r = ord(picture['data'][pos + 1]) * 4 g = ord(picture['data'][pos + 2]) * 4 b = ord(picture['data'][pos + 3]) * 4 # debug_output("* localPalette COLOR BEFORE update: " + str(localPalette[colorShift + i])) # debug_output("* globalPalette COLOR BEFORE update: " + str(globalPalette[colorShift + i])) localPalette[colorShift + i]['alpha'] = a localPalette[colorShift + i]['rgb'] = (r << 16) + (g << 8) + b # debug_output("* localPalette [%i] COLOR AFTER update: %s" % (i, str(localPalette[colorShift + i]))) # debug_output("* globalPalette [%i] COLOR AFTER: %s" % (i, str(globalPalette[colorShift + i]))) pos += 4 # debug_output() # debug_output("* localPalette UPDATED: " + str(localPalette)) # debug_output("* globalPalette: " + str(globalPalette)) X = x pos = picture['offsets'][frame] if (ord(picture['data'][pos]) == 1) and (ord(picture['data'][pos + 1]) == 0): # print "heading 0x01 0x00 looks ok" pos += 2 startY = ord( picture['data'][pos]) + (ord(picture['data'][pos + 1]) << 8) # print "startY: " + str(startY) Y = y + startY pos += 2 while pos < picture['offsets'][frame + 1]: pixelCount = ord( picture['data'][pos]) + (ord(picture['data'][pos + 1]) << 8) # print "pixelCount: %i" % pixelCount # if pixelCount == 1: # print "color at [0,0] %i" % px[0][0] pos += 2 # print "pixelCount: " + str(pixelCount) if pixelCount > 0: xIndent = ord(picture['data'][pos]) + ( ord(picture['data'][pos + 1]) << 8) X += xIndent pos += 2 # print "xIndent: " + str(xIndent) for i in range(pixelCount): pixel = ord(picture['data'][pos]) # if localPalette[pixel]['alpha']: # px[X][Y] = localPalette[pixel]['rgb'] # pixel = ord(picture['data'][pos]) # print " got alpha: %i" % localPalette[pixel]['alpha'] # else: px[X][Y] = localPalette[pixel]['rgb'] # pixel = ord(picture['data'][pos]) pos += 1 # put-pixel onto surface # px[X][Y] = localPalette[pixel]['rgb'] X += 1 if (pixelCount % 2) == 1: pos += 1 # print else: yIndent = ord(picture['data'][pos]) + ( ord(picture['data'][pos + 1]) << 8) pos += 2 if yIndent != 1000: Y += yIndent X = x else: return