def __init__(self, mapname): #make a surface #load the images #blit onto that shit. #pygame.Surface.__init__((WIDTH, HEIGHT)) super(TerrainLayer,self).__init__((WIDTH,HEIGHT)) self.fill([0,0,0]) thismap = Map.Map(mapname) imagekeys = thismap.aliases.keys() imagemap = {} for x in imagekeys: #load the image and key it the same temp,tmp = util.loadImage(thismap.aliases[x]) temptile = pygame.Surface((TILEX,TILEY)) temptile.blit(temp, tmp) imagemap[x] = temptile #blit the tiles... for y in range(HEIGHT/TILEY): for x in range(0, (WIDTH/TILEX)-4): if not thismap.belowLayer[y][x] == '.': self.blit(imagemap[thismap.belowLayer[y][x]], ((x+2)*TILEX, y*TILEY)) #load sprites for at layer self.atGroup = pygame.sprite.RenderPlain() for y in range(HEIGHT/TILEY): for x in range(0, (WIDTH/TILEX)-4): if not thismap.atLayer[y][x] == '.': sprite = pygame.sprite.Sprite(self.atGroup) sprite.image, sprite.rect = util.loadImage(thismap.aliases[thismap.atLayer[y][x]]) sprite.rect.topleft = ((x+2)*TILEX, y*TILEY)
def __init__(self, gameState, x, y, npcname): #load all images super(NPC, self).__init__() self.images = [0] * 4 self.images[UP], self.rect = util.loadImage(npcname + "Up.png") self.images[DOWN], self.rect = util.loadImage(npcname + "Down.png") self.images[LEFT], self.rect = util.loadImage(npcname + "Left.png") self.images[RIGHT], self.rect = util.loadImage(npcname + "Right.png") self.direction = UP self.setImage(self.images[self.direction]) self.setPos(x, y) self.gameState = gameState self.state = NPC.STATE_STOPPED self.destination = None
def __init__(self,gameState): super(Player,self).__init__() # load all images # up, down, left, right self.images = [0] * 4 self.images[0], self.rect = util.loadImage(PLAYER_IDLE_UP, -1) self.images[1], self.rect = util.loadImage(PLAYER_IDLE_DOWN, -1) self.images[2], self.rect = util.loadImage(PLAYER_IDLE_LEFT, -1) self.images[3], self.rect = util.loadImage(PLAYER_IDLE_RIGHT, -1) # 0 = up, 1 = down, 2 = left, 3 = right self.direction = 0 # assign image and position self.setImage(self.images[self.direction]) self.setPos(START_X, START_Y) # load sword self.swordLeft = pygame.sprite.Sprite() self.swordLeft.image,self.swordLeft.rect = util.loadImage("swordSwingLeft.png") self.swordUp = pygame.sprite.Sprite() self.swordUp.image,self.swordUp.rect = util.loadImage("swordSwingUp.png") self.swordRight = pygame.sprite.Sprite() self.swordRight.image,self.swordRight.rect = util.loadImage("swordSwingRight.png") self.swordDown = pygame.sprite.Sprite() self.swordDown.image,self.swordDown.rect = util.loadImage("swordSwingDown.png") self.gameState = gameState
def __init__(self, gameState): super(Player,self).__init__() # load all images # up, down, left, right self.images = [0] * 4 self.images[UP], self.rect = util.loadImage(PLAYER_IDLE_UP) self.images[DOWN], self.rect = util.loadImage(PLAYER_IDLE_DOWN) self.images[LEFT], self.rect = util.loadImage(PLAYER_IDLE_LEFT) self.images[RIGHT], self.rect = util.loadImage(PLAYER_IDLE_RIGHT) self.direction = UP # assign image and position self.setImage(self.images[self.direction]) self.setPos(START_X, START_Y) # load sword self.swordLeft = pygame.sprite.Sprite() self.swordLeft.image, self.swordLeft.rect = util.loadImage(SWORD_LEFT) self.swordUp = pygame.sprite.Sprite() self.swordUp.image, self.swordUp.rect = util.loadImage(SWORD_UP) self.swordRight = pygame.sprite.Sprite() self.swordRight.image, self.swordRight.rect = util.loadImage(SWORD_RIGHT) self.swordDown = pygame.sprite.Sprite() self.swordDown.image, self.swordDown.rect = util.loadImage(SWORD_DOWN) self.gameState = gameState #health self.health = 10 self.alive = True
def showScreen(self): self.showBackgroundImg() self.verifyLives() self.checkEndOfGame() selectedQuestion = self.selectQuestion() positions = self.renderQuestionRects(super().getScreen(), selectedQuestion) # if self.mustNextLevel(): # if self.state + 1 > 19: # pass # end game # self.state += 1 for i in range(0, 4): alpha = {0: "A", 1: "B", 2: "C", 3: "D"} if positions[i][1] > pygame.mouse.get_pos()[1] > positions[i][0]: if 800 > pygame.mouse.get_pos( )[0] > 700: # mudancas p considerar so hitbox do botao if pygame.mouse.get_pressed()[0]: if selectedQuestion.answer == alpha[i]: correctAnswer = util.loadImage( "images/correct.png") super().getScreen().blit(correctAnswer, (0, 0)) self.state += 1 self.lives -= 0 self.score += 1 lives = "Vidas :" + str(self.lives) + " de 3" self.button(lives, 700, 300, 165, 50, (12, 191, 117), (12, 191, 117), util.BLACK, 30, super().getScreen(), "rect", print) pygame.display.update() pygame.time.wait(3333) else: wrongAnswer = util.loadImage("images/wrong.png") super().getScreen().blit(wrongAnswer, (0, 0)) self.lives -= 1 self.state += 1 lives = "Vidas :" + str(self.lives) + " de 3" self.button(lives, 700, 300, 165, 50, (12, 191, 117), (12, 191, 117), util.BLACK, 30, super().getScreen(), "rect", print) pygame.display.update() pygame.time.wait(3333) pygame.display.update()
def __init__(self, x, y, pixels_per_movement): pygame.sprite.Sprite.__init__(self) self.pixels_per_movement = pixels_per_movement self.image = loadImage('monster-dropping.png') self.rect = self.image.get_rect() self.x = x self.y = y
def update(self, pygame, screen, background, deltaTime): if (self.image == None): self.image = util.loadImage(pygame, "piece.png") self.imageWidth = self.image.get_width() self.imageHeight = self.image.get_height() # range = 500 # self.position[0] += int(deltaTime*float(random.randint(-range, range))) # self.position[1] += int(deltaTime*float(random.randint(-range, range))) if ((self.imageScaleX != self.scale[0]) or (self.imageScaleY != self.scale[1])): scaleX = 1.0 + (self.scale[0] - self.imageScaleX) scaleY = 1.0 + (self.scale[1] - self.imageScaleY) scaleX = int(scaleX * float(self.imageWidth)) scaleY = int(scaleY * float(self.imageHeight)) if ((scaleX < self.imageWidthMaximum) and (scaleY < self.imageHeightMaximum)): self.image = pygame.transform.smoothscale( self.image, (scaleX, scaleY)) self.rect = self.image.get_rect(x=(self.position[0]), y=(self.position[1])) self.imagePositionX = self.position[0] self.imagePositionY = self.position[1] self.imageScaleX = self.scale[0] self.imageScaleY = self.scale[1] background.blit(self.image, tuple(self.position))
def __init__(self, type=TILE_T, rotation=0, column=-1, row=-1, item=None, people=0, home=-1, resting=False): pygame.sprite.Sprite.__init__(self) self.set_orientation(type, rotation) self.item = item self.people = people self.home = home self.location = (column, row) self.column = column self.row = row if not self.image: if type == TILE_I: image = util.loadImage("tile-i3.png") elif type == TILE_T: image = util.loadImage("tile-t3.png") elif type == TILE_L: image = util.loadImage("tile-l3.png") if rotation: image = pygame.transform.rotate(image, -90 * rotation) self.width = image.get_width() self.height = image.get_height() self.type = type self.rect = self.getTileLocation() self.sliding = -1 self.rotating = -1 self.rotation = 0 self.rotated = 0 self.image = image self.imageCopy = image self.falling = False self.trackMouse = False self.tick = 0 # put the floating tile in the correct location if resting: self.fallen() else: self.resting = False
def __init__(self, screen_rect, drawing_group): pygame.sprite.Sprite.__init__(self) self.screen_rect = screen_rect self.drawing_group = drawing_group self.image = loadImage('monster.png') self.rect = self.image.get_rect() self.x = 10 self.y = randint(0, screen_rect.centery) self.pixels_per_movement = randint(1, 5)
def BatteryPage(tim): global BattLevel oled.fill(0) icon = util.loadImage('icons/battery' + str(BattLevel) + '4.pbm') oled.blit(icon, 100, 0) oled.show() if (BattLevel < 4): BattLevel += 1 tim.init(period=1 * 1000, mode=Timer.ONE_SHOT, callback=BatteryPage) else: tim.init(period=1 * 1000, mode=Timer.ONE_SHOT, callback=page2)
def __init__(self, x, y): super(Magic,self).__init__() if Magic.loadedImage == 0: Magic.loadedImage,tmp = util.loadImage(MAGIC_ATTACK_IMAGE) self.setImage(Magic.loadedImage) self.setPos(x,y) self.setVel(Vector2(MAGIC_SPEED))
def checkEndOfGame(self): if self.state > 19: if self.lives > 0: wonGame = util.loadImage("images/winner.png") super().getScreen().blit(wonGame, (0, 0)) pygame.display.update() pygame.time.wait(3333) endScreen = util.loadImage("images/endscreen.png") super().getScreen().blit(endScreen, (0, 0)) score = "Pontos : " + str(self.score) self.button(score, 700, 300, 165, 50, (12, 191, 117), (12, 191, 117), util.BLACK, 30, super().getScreen(), "rect", print) pygame.display.update() pygame.time.wait(5555) self.state = -1 self.lives = 3 # END OF GAME pass
def __init__(self, x, y, direction, parent): super(Magic,self).__init__() self.dieoncollide = True self.parent = parent if not Magic.loadedImage: Magic.loadedImage,tmp = util.loadImage(MAGIC_ATTACK_IMAGE) self.setImage(Magic.loadedImage) self.setPos(x, y) self.setVel(direction.normalized() * MAGIC_SPEED) self.image = pygame.transform.rotate(self.image,270+360*(math.atan2(self.vel.x,self.vel.y)/6.28))
def verifyLives(self): if self.lives == 0: gameover = util.loadImage("images/gameover.png") super().getScreen().blit(gameover, (0, 0)) score = "Pontos : " + str(self.score) self.button(score, 700, 300, 165, 50, (12, 191, 117), (12, 191, 117), util.BLACK, 30, super().getScreen(), "rect", print) self.state = -1 self.lives = 3 pygame.display.update() pygame.time.wait(5555)
def __init__(self, mapname): #make a surface #load the images #blit onto that shit. #pygame.Surface.__init__((WIDTH, HEIGHT)) super(TerrainLayer, self).__init__((config.WIDTH, config.HEIGHT)) self.fill([0, 0, 0]) thismap = Map.Map(mapname) self.imagekeys = thismap.aliases.keys() self.imagemap = {} for x in self.imagekeys: #load the image and key it the same image, rect = util.loadImage(thismap.aliases[x]) surface = pygame.Surface((config.TILEX, config.TILEY)) surface.blit(image, rect) self.imagemap[x] = surface #blit the tiles... for y in range(config.HEIGHT / config.TILEY): for x in range(config.WIDTH / config.TILEX - 4): if thismap.belowLayer[y][x] != '.': self.blit(self.imagemap[thismap.belowLayer[y][x]], ((x + 2) * config.TILEX, y * config.TILEY)) #load sprites for at layer and over layer self.atGroup = pygame.sprite.RenderPlain() self.overGroup = pygame.sprite.RenderPlain() for y in range(config.HEIGHT / config.TILEY): for x in range(config.WIDTH / config.TILEX - 4): if thismap.atLayer[y][x] != '.': sprite = pygame.sprite.Sprite(self.atGroup) sprite.image, sprite.rect = util.loadImage(thismap.aliases[thismap.atLayer[y][x]]) sprite.rect.topleft = ((x + 2) * config.TILEX, y * config.TILEY) if thismap.overLayer[y][x] != '.': sprite = pygame.sprite.Sprite(self.overGroup) sprite.image, sprite.rect = util.loadImage(thismap.aliases[thismap.overLayer[y][x]]) sprite.rect.topleft = ((x + 2) * config.TILEX, y * config.TILEY)
def __init__(self, rotation, location): pygame.sprite.Sprite.__init__(self) self.image = util.loadImage("arrow.png") if rotation: self.image = pygame.transform.rotate(self.image, -90 * rotation) self.rect = self.image.get_rect() self.rect.center = (location[0] * 81 + TILE_X_OFFSET + 40, location[1] * 80 + TILE_Y_OFFSET + 40) self.tick = 0 self.movement = 0 self.direction = rotation self.location = location
def __init__(self, x, y): # Call super constructor and assign its image to TORPEDO_IMAGE super(Torpedo, self).__init__() # Load image on first torpedo if Torpedo.loadedImage == 0: Torpedo.loadedImage, tmp = util.loadImage(TORPEDO_IMAGE) # Assign pre-loaded image self.setImage(Torpedo.loadedImage) # Set position self.setPos(x, y) # Set velocity -- always moving downwards self.setVel(Vector2(TORPEDO_VEL))
def __init__(self): super(Enemy,self).__init__() # Load image if not already loaded if Enemy.loadedImage == 0: Enemy.loadedImage, tmp = util.loadImage(SUB_IMAGE, -1) # Assign image self.setImage(Enemy.loadedImage) # Random y coordinate. Ensure that it remains on screen and is reachable # by torpedos. y = random.randint(50, HEIGHT-10) self.setPos(-10,y) self.setVel(Vector2(SUB_VEL))
def __init__(self, player=PLAYER1, file="person1.png", items=[1, 2, 3], size=(32,48), location=(0,0), board=None, computer=True, name="Computer1"): pygame.sprite.Sprite.__init__(self) self.walkCycle = [[], [], [], [], []] self.walk_path = [] image = util.loadImage(file) for x in range(4): print x* size[0] print x*size[1] self.walkCycle[SOUTH].append(image.subsurface( pygame.Rect(x*size[0], 0*size[1], size[0], size[1]))) self.walkCycle[WEST].append(image.subsurface( pygame.Rect(x*size[0], 1*size[1], size[0], size[1]))) self.walkCycle[EAST].append(image.subsurface( pygame.Rect(x*size[0], 2*size[1], size[0], size[1]))) self.walkCycle[NORTH].append(image.subsurface( pygame.Rect(x*size[0], 3*size[1], size[0], size[1]))) self.items = items self.home = location self.name = name self.location = location self.dir = SOUTH self.frame = 0 self.image = self.walkCycle[self.dir][self.frame] self.imageCopy = self.walkCycle[self.dir][self.frame] self.warping = False self.moving = False self.sliding = -1 self.boardStatus = None tile = board.getTile(location) self.rect = self.image.get_rect() self.rect.center = tile.getTileLocation().center self.lastLocation = None self.board = board self.tick = 0
def preprocess(self, boxlabel_df, sampleFiles, shrink): # First create a list with required length self.dataStore = [None] * len(sampleFiles) sampleCount = len(sampleFiles) for fileIndex in range(sampleCount): print("Preprocess: {}/{} \r".format(fileIndex, sampleCount), end="", file=sys.stderr) fileName = sampleFiles.iloc[fileIndex].TrainImageId # Load and resize image img = sd_util.loadImage( os.path.join(sd_util.TRAIN_IMAGES, fileName)) if shrink != 1: img = sd_util.resizeImage(img, self.IMAGE_H, self.IMAGE_W) img = img.reshape((self.IMAGE_H, self.IMAGE_W, 1)) img -= 88 # The average grayscale of images is 88 selectedRows = boxlabel_df[boxlabel_df.ImageId == fileName] defectClasses = [None] * sd_util.NUM_CLASS margins = [self.IMAGE_W, 0, self.IMAGE_H, 0] for classIndex in range(sd_util.NUM_CLASS): if selectedRows.iloc[classIndex].hasBox: encodedBoxes = selectedRows.iloc[classIndex].EncodedBoxes rects = sd_util.encoded2rects(encodedBoxes) temp = np.zeros( (len(rects), 4)) # Convert it from tuple to np matrix temp[:, :] = rects rects = temp if shrink != 1: rects /= shrink defectClasses[classIndex] = rects if np.min(rects[:, 0]) < margins[0]: margins[0] = np.min(rects[:, 0]) if np.min(rects[:, 1]) < margins[1]: margins[1] = np.min(rects[:, 1]) if np.max(rects[:, 2]) > margins[2]: margins[2] = np.max(rects[:, 2]) if np.max(rects[:, 3]) > margins[3]: margins[3] = np.max(rects[:, 3]) self.dataStore[fileIndex] = (img, defectClasses, margins)
def __init__(self, file="items.png", size=(50,50), location=(0,0), offset=0): pygame.sprite.Sprite.__init__(self) rect = pygame.Rect(offset*size[0], 0, size[0], size[1]) if Item.image is None: Item.image = util.loadImage(file) self.image = Item.image.subsurface(rect) self.imageCopy = self.image self.location = location self.offset = offset self.rect = self.image.get_rect() self.rect.center = board.findPosition(location) self.falling = False self.sliding = -1 self.tick = 0
def makeGrid(pygame, width, height, widthGrid, heightGrid): name = "grid.png" image = Image.new("RGBA", (width, height), "black") pixels = image.load() other = None current = None for x in range(width): for y in range(height): check = False current = [] current.append(int((float(x) / float(width)) * float(widthGrid))) current.append(int((float(y) / float(height)) * float(heightGrid))) for i in range(3): for j in range(3): other = [] other.append(i - 1) other.append(j - 1) if not ((other[0] == 0) and (other[1] == 0)): other[0] = int((float(x + other[0]) / float(width)) * float(widthGrid)) other[1] = int((float(y + other[1]) / float(height)) * float(heightGrid)) if not ((other[0] == current[0]) and (other[1] == current[1])): check = True break if (check): break if (check): pixel = list(pixels[x, y]) length = len(pixel) for i in range(length): if (i == length - 1): break pixel[i] = 255 - pixel[i] pixels[x, y] = tuple(pixel) image.save(name) return util.loadImage(pygame, name)
def main(): pygame.init() title = 'Bee, Get the Nectar!' screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN) screenRect = screen.get_rect() Bee.loadImages() Flower.loadImages() background = loadImage('clover-large.jpg') drawTitle = True if drawTitle: font = pygame.font.Font(None, 48) text = font.render(title, 1, Color('white')) textpos = text.get_rect(centerx=screenRect.width/2, centery=25) background.blit(text, textpos) screen.blit(background, (0, 0)) pygame.display.flip() bee = Bee(screenRect) flowers = pygame.sprite.Group() score = Score() drawingGroup = pygame.sprite.RenderUpdates() drawingGroup.add(bee) drawingGroup.add(score) pygame.display.set_caption(title) pygame.mouse.set_visible(0) clock = pygame.time.Clock() angles = ((45, 90, 135), (0, 0, 180), (315, 270, 225)) # game loop loop = True while loop: # get input for event in pygame.event.get(): if event.type == QUIT \ or (event.type == KEYDOWN and event.key == K_ESCAPE): loop = False keystate = pygame.key.get_pressed() xdir = keystate[K_RIGHT] - keystate[K_LEFT] # -1, 0, or 1 ydir = keystate[K_DOWN] - keystate[K_UP] bee.setAngle(angles[xdir+1][ydir+1]) bee.rect = bee.rect.move((xdir * 8, ydir * 8)).clamp(screenRect) # Detect collisions for flower in pygame.sprite.spritecollide(bee, flowers, True): score.score += 1 flower.kill() if random.randint(0, 50) == 0: flower = Flower(screenRect) drawingGroup.add(flower) flowers.add(flower) drawingGroup.clear(screen, background) drawingGroup.update() changedRects = drawingGroup.draw(screen) pygame.display.update(changedRects) # maintain frame rate clock.tick(40) pygame.quit()
import pygame, random from pygame.locals import * from util import loadImage from bee import Bee from flower import Flower from score import Score pygame.init() TITLE = 'Bee, Get the Nectar!' screen = pygame.display.set_mode((1280, 720), 0) screenRect = screen.get_rect() Bee.loadImages() Flower.loadImages() background = loadImage('clover-large.jpg') font = pygame.font.Font(None, 48) text = font.render(TITLE, 1, Color('white')) textpos = text.get_rect(centerx=screenRect.width/2, centery=25) background.blit(text, textpos) screen.blit(background, (0, 0)) pygame.display.flip() bee = Bee(screenRect) flowers = pygame.sprite.Group() score = Score() drawingGroup = pygame.sprite.RenderUpdates() drawingGroup.add(bee) drawingGroup.add(score)
def __init__(self, imageFile=None, colorKey=None): super(HUDElement, self).__init__() if imageFile is not None: self.image, self.rect = util.loadImage(imageFile, colorKey)
def loadImages(): Flower.image = loadImage('flower.png')
def loadImage(self, imageFile, colorKey=None): self.image, self.rect = util.loadImage(imageFile, colorKey)
def __init__(self, caption, icon, width, height, state, lives, score, backgroundImg): super().__init__(caption, icon, width, height, state, lives, score) self.backgroundImg = util.loadImage(backgroundImg)
def __init__(self, x, y): pygame.sprite.Sprite.__init__(self) self.image = loadImage('projectile.png') self.rect = self.image.get_rect() self.x = x self.y = y
def createTFExample(self): """Convert XML derived dict to tf.Example proto. Notice that this function normalizes the bounding box coordinates provided by the raw data. Args: None Returns: example: The converted tf.Example. """ with tf.io.gfile.GFile(self.xml, 'r') as fid: xml_str = fid.read() xml = etree.fromstring(xml_str) data = dataset_util.recursive_parse_xml_to_dict(xml)['annotation'] # the image might be processed in a different location # so overwrite the path to the input image path for consistency data['path'] = self.jpg if self.crop == '' else self.__cropImage(data) print(f"Processing image {data['path']}") width = int(data['size']['width']) height = int(data['size']['height']) filename = data['filename'].encode('utf8') with tf.io.gfile.GFile(data['path'], 'rb') as fid: encoded_image_data = fid.read() image_format = 'jpeg'.encode('utf8') # List of normalized left x coordinates in bounding box (1 per box) xmins = [] # List of normalized right x coordinates in bounding box (1 per box) xmaxs = [] # List of normalized top y coordinates in bounding box (1 per box) ymins = [] # List of normalized bottom y coordinates in bounding box (1 per box) ymaxs = [] # List of string class name of bounding box (1 per box) classes_text = [] classes_id = [] # List of integer class id of bounding box (1 per box) image = util.loadImage(data['path']) for obj in data['object']: if obj['name'] not in classes or not self.__isValidBox( obj, width, height): print('Unexpected object: ' + str(obj) + ' in ' + data['path']) continue xmins.append(float(obj['bndbox']['xmin']) / width) ymins.append(float(obj['bndbox']['ymin']) / height) xmaxs.append(float(obj['bndbox']['xmax']) / width) ymaxs.append(float(obj['bndbox']['ymax']) / height) classes_text.append(obj['name'].encode('utf8')) classes_id.append(getClassID(obj['name'])) util.drawBox(image, self.__encodeBox(obj['bndbox'])) util.saveImage(image, str(data['path']).replace(".jpg", "-with-boxes.jpg")) tf_example = tf.train.Example(features=tf.train.Features( feature={ 'image/height': dataset_util.int64_feature(height), 'image/width': dataset_util.int64_feature(width), 'image/filename': dataset_util.bytes_feature(filename), 'image/source_id': dataset_util.bytes_feature(filename), 'image/encoded': dataset_util.bytes_feature(encoded_image_data), 'image/format': dataset_util.bytes_feature(image_format), 'image/object/bbox/xmin': dataset_util.float_list_feature(xmins), 'image/object/bbox/ymin': dataset_util.float_list_feature(ymins), 'image/object/bbox/xmax': dataset_util.float_list_feature(xmaxs), 'image/object/bbox/ymax': dataset_util.float_list_feature(ymaxs), 'image/object/class/text': dataset_util.bytes_list_feature(classes_text), 'image/object/class/label': dataset_util.int64_list_feature(classes_id), })) return tf_example