def __setCharacter(self): self.front_standing = pygame.image.load('mygameimages/pro_front.png') self.front_standing = pygame.transform.scale( self.front_standing, (self.size[0], self.size[1])) self.back_standing = pygame.image.load('mygameimages/pro_back.png') self.back_standing = pygame.transform.scale( self.back_standing, (self.size[0], self.size[1])) self.right_standing = pygame.image.load('mygameimages/pro_right.png') self.right_standing = pygame.transform.scale( self.right_standing, (self.size[0], self.size[1])) self.left_standing = pygame.transform.flip(self.right_standing, True, False) self.playerWidth, self.playerHeight = self.front_standing.get_size() animTypes = 'back_run back_walk front_run front_walk right_run right_walk'.split( ) self.animObjs = {} for animType in animTypes: imagesAndDurations = [('mygameimages/pro_%s.%s.png' % (animType, str(num).rjust(3, '0')), 0.1) for num in range(6)] self.animObjs[animType] = pyganim.PygAnimation(imagesAndDurations) self.animObjs['left_walk'] = self.animObjs['right_walk'].getCopy() self.animObjs['left_walk'].flip(True, False) self.animObjs['left_walk'].makeTransformsPermanent() self.animObjs['left_run'] = self.animObjs['right_run'].getCopy() self.animObjs['left_run'].flip(True, False) self.animObjs['left_run'].makeTransformsPermanent() self.moveConductor = pyganim.PygConductor(self.animObjs) self.moveConductor.scale((self.size[0], self.size[1]))
def load_animations(self): #right->0 #left->1 #up->2 #down->3 self.pacmanAnim = {} self.pacmanAnim[0] = ANIM.PygAnimation([ ('images/pacman_R1.png', sprite_speed), ('images/pacman_R2.png', sprite_speed) ]) self.pacmanAnim[2] = ANIM.PygAnimation([ ('images/pacman_U1.png', sprite_speed), ('images/pacman_U2.png', sprite_speed) ]) self.pacmanAnim[1] = self.pacmanAnim[0].getCopy() self.pacmanAnim[1].flip(True, False) self.pacmanAnim[1].makeTransformsPermanent() self.pacmanAnim[3] = self.pacmanAnim[2].getCopy() self.pacmanAnim[3].flip(False, True) self.pacmanAnim[3].makeTransformsPermanent() #init animations self.moveConductor = ANIM.PygConductor(self.pacmanAnim) self.moveConductor.play()
def __init__(self, img, position=(16, 16), width=32, height=32, num=3, st=0): self.img_width = width self.img_height = height anim_types = ['front', 'left', 'right', 'back'] self.anim_objs = {} self.standing = {} i = 0 for anim_type in anim_types: rects = [(num * width, i * height, width, height) for num in range(num)] all_images = pyganim.getImagesFromSpriteSheet(img, rects=rects) self.standing[anim_type] = all_images[st] frames = list(zip(all_images, [100] * len(all_images))) self.anim_objs[anim_type] = pyganim.PygAnimation(frames) i += 1 self.move_conductor = pyganim.PygConductor(self.anim_objs) self.pos_x, self.pos_y = position self.pos_x -= self.standing['front'].get_width() / 2 self.pos_y -= self.standing['front'].get_height() / 2
def __init__(self, img, x, y, folder, power, v_lim, jump_power, stable=True): global CHARACTERS global FPS self.right_standing = img.convert_alpha() self.left_standing = pygame.transform.flip(self.right_standing, True, False) # FIXME: Стойку тоже нужно анимировать super().__init__(img, x, y, stable) self.on_ground = self.left = self.right = self.down = self.up = self.jumping = False self.v_x = 0 self.v_y = 0 self.power = power # Ускорение при беге self.v_lim = v_lim # Предельная скорость self.jump_power = jump_power # Сила прыжка (в единицах G) self.direction = 'right' CHARACTERS.add(self) animTypes = 'jump roll run'.split() self.animObjs = {} for animType in animTypes: animType_r = 'right_' + animType animType_l = 'left_' + animType path = './resources/characters/%s/%s/' % (folder, animType_r) files = os.listdir(path) num_files = 0 for file in files: if file[-4:] == '.png': # В папке могут содержаться скрытые системные файлы, например, Thumbs.db num_files += 1 imagesAndDurations = [(path + str(num) + '.png', 60) for num in range(1, num_files + 1)] # FIXME: Какое нужно время между кадрами? self.animObjs[animType_r] = pyganim.PygAnimation( imagesAndDurations) self.animObjs[animType_l] = self.animObjs[animType_r].getCopy() self.animObjs[animType_l].flip(True, False) # Отразить по горизонтали self.animObjs[animType_l].makeTransformsPermanent() self.moveConductor = pyganim.PygConductor(self.animObjs)
def __init__(self): animTypes = "\MarioRunningD \MarioRunningG".split() animtypes_ennemies = "\Goomba \Pyrhana".split() self.animObjs = {} for animType in animTypes: imagesAndDurations = [ (mario_path + "%s%s.gif" % (animType, str(num).rjust(3, '0')), 0.1) for num in range(len(animTypes)) ] self.animObjs[animType] = pyganim.PygAnimation(imagesAndDurations) for animtype in animtypes_ennemies: imagesAndDurations = [ (ennemy_path + "%s%s.gif" % (animtype, str(num).rjust(1, '0')), 0.1) for num in range(len(animtypes_ennemies)) ] self.animObjs[animtype] = pyganim.PygAnimation(imagesAndDurations) self.moveConductor = pyganim.PygConductor(self.animObjs) self.moveConductor.play()
def __init__(self, POS): super().__init__() self.size = (44, 64) self.image = pygame.Surface(self.size) self.rect = self.image.get_rect() self.health = 2 self.rect.x = POS[0] self.rect.y = POS[1] self.frame_sp = 0.1 self.animObjs = {} imagesAndDurations = [ ('Sprites/enemy/snake/snake0.png', self.frame_sp), ('Sprites/enemy/snake/snake1.png', 0.3), ('Sprites/enemy/snake/snake2.png', self.frame_sp) ] self.animObjs['attack'] = pyganim.PygAnimation(imagesAndDurations) imagesAndDurations = [('Sprites/enemy/snake/snake0.png', self.frame_sp) ] self.animObjs['idle'] = pyganim.PygAnimation(imagesAndDurations) self.animObjs['right_attack'] = self.animObjs['attack'].getCopy() self.animObjs['right_attack'].flip(True, False) self.animObjs['right_attack'].makeTransformsPermanent() self.animObjs['right_idle'] = self.animObjs['idle'].getCopy() self.animObjs['right_idle'].flip(True, False) self.animObjs['right_idle'].makeTransformsPermanent() self.snakeConductor = pyganim.PygConductor(self.animObjs) self.snakeConductor.play()
def __init__(self, key: str): """ Инициализет анимацию объекта :param key: ID анимации в базе данных """ try: img, width, height, num, st, x, y = Life.database.init_life(key) except ValueError: logging.error("ID=%s not found" % (key, )) return self.img_width = width self.img_height = height self.anim_objs = [None] * 4 self.standing = [None] * 4 # 0-front, 1-left, 2-right, 3-back for i in range(4): rects = [(x + num * width, y + i * height, width, height) for num in range(num)] all_images = pyganim.getImagesFromSpriteSheet(img, rects=rects) all_images = list(map(lambda a: a.convert_alpha(), all_images)) self.standing[i] = all_images[st] frames = list(zip(all_images, [120] * len(all_images))) self.anim_objs[i] = pyganim.PygAnimation(frames) self.move_conductor = pyganim.PygConductor(self.anim_objs) self.pos_x = -1 self.pos_y = -1 self.run_rate = 0.45 self.walk_rate = 0.15 self.key = key self.direction = 0 self.direction_x = 0 self.direction_y = 0 self.level = -1 self.face = self.load_face()
def __init__(self, img, position=(16, 16), width=32, height=32, num=3, lines=1): self.img_width = width self.img_height = height rects = [] for i in range(lines): for n in range(num): rects.append((n * width, i * height, width, height)) all_images = pyganim.getImagesFromSpriteSheet(img, rects=rects) frames = list(zip(all_images, [100] * len(all_images))) self.anim_objs = pyganim.PygAnimation(frames) self.move_conductor = pyganim.PygConductor(self.anim_objs) self.pos_x, self.pos_y = position self.pos_x -= all_images[0].get_width() / 2 self.pos_y -= all_images[0].get_height() / 2
("sprites/left.png", 100), ("sprites/left3.png", 100), ("sprites/left.png", 10)]) charanim["walkright"] = pyganim.PygAnimation([("sprites/right2.png", 100), ("sprites/right.png", 100), ("sprites/right3.png", 100), ("sprites/right.png", 10)]) charanim["walkup"] = pyganim.PygAnimation([("sprites/up2.png", 100), ("sprites/up.png", 100), ("sprites/up3.png", 100), ("sprites/up.png", 10)]) charanim["walkdown"] = pyganim.PygAnimation([("sprites/down2.png", 100), ("sprites/down.png", 100), ("sprites/down3.png", 100), ("sprites/down.png", 10)]) moveConductor = pyganim.PygConductor(charanim) # mainmenu animations mainmenuanim = {} mainmenuanim["splashscreen"] = pyganim.PygAnimation([ ("sprites/splash1.png", 500), ("sprites/splash2.png", 500) ]) mainmenuConductor = pyganim.PygConductor(mainmenuanim) pygame.mixer.music.load('track0.ogg') mainwin = pygame.display.set_mode( (WINDOWWIDTH, WINDOWHEIGHT )) # this sets height and width of my window and creates a window. pygame.display.set_caption("2084 Ver 0.1.0.3") # sets window title
] animObjs[animType] = pyganim.PygAnimation(imagesAndDurations) # create the right-facing sprites by copying and flipping the left-facing sprites animObjs['right_walk'] = animObjs['left_walk'].getCopy() animObjs['right_walk'].flip(True, False) animObjs['right_walk'].makeTransformsPermanent() animObjs['right_run'] = animObjs['left_run'].getCopy() animObjs['right_run'].flip(True, False) animObjs['right_run'].makeTransformsPermanent() # have the animation objects managed by a conductor. # With the conductor, we can call play() and stop() on all the animtion # objects at the same time, so that way they'll always be in sync with each # other. moveConductor = pyganim.PygConductor(animObjs) direction = DOWN # player starts off facing down (front) BASICFONT = pygame.font.Font('freesansbold.ttf', 16) WHITE = (255, 255, 255) BGCOLOR = (100, 50, 50) mainClock = pygame.time.Clock() x = 300 # x and y are the player's position y = 200 WALKRATE = 4 RUNRATE = 12 instructionSurf = BASICFONT.render('Arrow keys to move. Hold shift to run.', True, WHITE)
# Подготовка спрайтов для PygAnimation animationObjects = {} imagesAndDurations = [(image_array[3], 0.1), (image_array[2], 0.1), (image_array[1], 0.1)] animationObjects['right_walk'] = pyganim.PygAnimation(imagesAndDurations) # Переворачиваем спрайты по вертикали налево animationObjects['left_walk'] = animationObjects['right_walk'].getCopy() animationObjects['left_walk'].flip(True, False) animationObjects['left_walk'].makeTransformsPermanent() # have the animation objects managed by a conductor. # With the conductor, we can call play() and stop() on all the animation # objects at the same time, so that way they'll always be in sync with each # other. moveConductor = pyganim.PygConductor(animationObjects) # Направление движения спрайтов по умолчанию direction = RIGHT # Быть в цикле до момента, пока пользователь не решит закрыть программу done = False # Используется для определения скорости обновления экрана clock = pygame.time.Clock() # Счетчик кадров dt = 0 # Начальные координаты спрайта x = 300
class Player(Sprite): right_jumping = pygame.image.load('data/dave_right_jump.png') left_jumping = pygame.transform.flip(right_jumping, True, False) animObjs = {} imagesAndDurations = [ ('data/dave_right_walk.%s.png' % str(num).rjust(3, '0'), 0.1) for num in range(4) ] animObjs['right_walk'] = pyganim.PygAnimation(imagesAndDurations) animObjs['left_walk'] = animObjs['right_walk'].getCopy() animObjs['left_walk'].flip(True, False) animObjs['left_walk'].makeTransformsPermanent() moveConductor = pyganim.PygConductor(animObjs) def __init__(self, location, *groups): Sprite.__init__(self, *groups) self.image = pygame.image.load('data/dave_front.png') self.front_standing = self.image self.direction = 'left' self.rect = pygame.rect.Rect(location, self.image.get_size()) self.resting = False self.walking = False self.dy = 0 def update(self, dt, game): last = self.rect.copy() key = pygame.key.get_pressed() if key[pygame.K_LEFT]: if self.resting: self.walking = True self.direction = 'left' if self.walking: self.moveConductor.play() self.image = self.animObjs['left_walk'].getCurrentFrame() else: self.image = self.left_jumping self.rect.x -= 100 * dt if key[pygame.K_RIGHT]: if self.resting: self.walking = True self.direction = 'right' if self.walking: self.moveConductor.play() self.image = self.animObjs['right_walk'].getCurrentFrame() else: self.image = self.right_jumping self.rect.x += 100 * dt if self.resting and key[pygame.K_UP]: self.walking = False self.moveConductor.stop() if self.direction == 'left': self.image = self.left_jumping else: self.image = self.right_jumping self.dy = -500 self.dy = min(400, self.dy + 40) self.rect.y += self.dy * dt if self.rect.y > last.y + 1: self.moveConductor.stop() self.walking = False new = self.rect self.resting = False for cell in game.tilemap.layers['triggers'].collide(new, 'blockers'): if last.right <= cell.left and new.right > cell.left: self.moveConductor.pause() new.right = cell.left if last.left >= cell.right and new.left < cell.right: self.moveConductor.pause() new.left = cell.right if last.bottom <= cell.top and new.bottom > cell.top: self.resting = True if not self.walking: self.image = self.front_standing new.bottom = cell.top self.dy = 0 if last.top >= cell.bottom and new.top < cell.bottom: new.top = cell.bottom self.dy = 0 if game.exit_door and game.tilemap.layers['triggers'].collide( new, 'exit'): print("Good work! 9 more to go") game.running = False game.tilemap.set_focus(new.x, new.y)
("sprites/up.png", 10)]) charanim["walkdown"] = pyganim.PygAnimation([("sprites/down2.png", 100), ("sprites/down.png", 100), ("sprites/down3.png", 100), ("sprites/down.png", 10)]) charanim["shootright"] = pyganim.PygAnimation([ ("sprites/muzzleflash.png", 125), ("sprites/muzzleflash2.png", 125), ("sprites/muzzleflash3.png", 125), ("sprites/muzzleflash4.png", 125) ]) # I can invert the right facing sprite to save time creating another image charanim["shootleft"] = charanim["walkleft"].getCopy() charanim["shootleft"].flip(True, False) charanim["shootleft"].makeTransformsPermanent() moveConductor = pyganim.PygConductor(charanim) def drawmainwin(): mainwin.blit(background, (0, 0)) #def mainLoop(): running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == KEYDOWN: # KEYDOWN detects if a key is being pressed and is held down
".png", 100), ("sprites/left.png", 10)]), "walkright": pyganim.PygAnimation([("sprites/right2.png", 100), ("sprites/right.png", 100), ("sprites/right3.png", 100), ("sprites/right.png", 10)]), "walkup": pyganim.PygAnimation([("sprites/up2.png", 100), ("sprites/up.png", 100), ("sprites/up3.png", 100), ("sprites/up.png", 10)]), "walkdown": pyganim.PygAnimation([ ("sprites/down2.png", 100), ("sprites/down.png", 100), ("sprites/down3.png", 100), ("sprites/down.png", 10) ]) } moveConductor = pyganim.PygConductor(charanim) # Demon walking animations demonanim = { "walkleft": pyganim.PygAnimation([("sprites/demonsprites/demon1left2.png", 100), ("sprites/demonsprites/demon1left3.png", 100), ("sprites/demonsprites/demon1left4.png", 100), ("sprites/demonsprites/demon1left5.png", 100), ("sprites/demonsprites/demon1left6.png", 100), ("sprites/demonsprites/demon1left7.png", 100)]) } demonanim["walkright"] = demonanim["walkleft"].getCopy() demonanim["walkright"].flip(True, False) demonanim["walkright"].makeTransformsPermanent() demonanimConductor = pyganim.PygConductor(demonanim)
import sys import time import pyganim #used for animations #initialises pygame, was told this was necessary pygame.init() #pygame.mixer.init() #pygame.mixer.music.load('track0.ogg') #pygame.mixer.music.play() #mainmenu animations mainmenuanim = {} mainmenuanim["splashscreen"] = pyganim.PygAnimation([ ("sprites/splash1.png", 500), ("sprites/splash2.png", 500) ]) mainmenuConductor = pyganim.PygConductor(mainmenuanim) pygame.mixer.init() pygame.mixer.music.load('track0.ogg') #pygame.mixer.music.play() WINDOWWIDTH = 1600 WINDOWHEIGHT = 900 mainwin = pygame.display.set_mode( (WINDOWWIDTH, WINDOWHEIGHT )) # this sets height and width of my window and creates a window. pygame.display.set_caption("2084 Ver 0.1.0.3") # sets window title running = True #menulive = True
def __init__(self): self.animTypes = 'run jump idle hurt run_shoot jump_shoot idle_shoot left_run left_jump left_idle left_idle_shoot left_run_shoot left_jump_shoot'.split( ) self.animObjs = {} for animType in self.animTypes: if animType[0:1] == 'j': imagesAndDurations = [ ('Sprites/player/player_%s.png' % (animType), 1.0) ] elif animType[0:1] == 'r': imagesAndDurations = [('Sprites/player/player_%s_%s.png' % (animType, str(num).rjust(1, '0')), 0.1) for num in range(4)] elif animType == 'idle': imagesAndDurations = [('Sprites/player/player_idle0.png', 4.5), ('Sprites/player/player_idle1.png', 0.1)] elif animType[0:1] == 'i': imagesAndDurations = [('Sprites/player/player_idle_shoot.png', 1.0)] elif animType[0:1] == 'hurt': imagesAndDurations = [('Sprites/player/player_hurt.png', 1.0)] else: pass self.animObjs[animType] = pyganim.PygAnimation(imagesAndDurations) self.animObjs['left_run'] = self.animObjs['run'].getCopy() self.animObjs['left_run'].flip(True, False) self.animObjs['left_run'].makeTransformsPermanent() self.animObjs['left_hurt'] = self.animObjs['hurt'].getCopy() self.animObjs['left_hurt'].flip(True, False) self.animObjs['left_hurt'].makeTransformsPermanent() self.animObjs['left_idle'] = self.animObjs['idle'].getCopy() self.animObjs['left_idle'].flip(True, False) self.animObjs['left_idle'].makeTransformsPermanent() self.animObjs['left_jump'] = self.animObjs['jump'].getCopy() self.animObjs['left_jump'].flip(True, False) self.animObjs['left_jump'].makeTransformsPermanent() self.animObjs['left_jump_shoot'] = self.animObjs['jump_shoot'].getCopy( ) self.animObjs['left_jump_shoot'].flip(True, False) self.animObjs['left_jump_shoot'].makeTransformsPermanent() self.animObjs['left_run_shoot'] = self.animObjs['run_shoot'].getCopy() self.animObjs['left_run_shoot'].flip(True, False) self.animObjs['left_run_shoot'].makeTransformsPermanent() self.animObjs['left_idle_shoot'] = self.animObjs['idle_shoot'].getCopy( ) self.animObjs['left_idle_shoot'].flip(True, False) self.animObjs['left_idle_shoot'].makeTransformsPermanent() self.playerConductor = pyganim.PygConductor( self.animObjs) # animation blend tree
def __init__(self, x, y, e, solid, animated, img, frames): super().__init__(x, y, e, solid, animated, img) self.frames = frames self.frame_conductor = pyganim.PygConductor(frames)
def runGame(main_char=None, camera=None): """main_char is optional parameter that is only passed if we just loaded a game.""" mouse_x, mouse_y = ( 0, 0 ) #define these here to clear whatever happened on the splash screen char_just_died = False #used later to break out of game loop # Setting up the variables for main character: main_anim_objs = loadPygAnimObjs( 'mainwalkup mainwalkdown mainwalkright mainwalkleft mainattackup mainattackdown mainattackright mainattackleft', 3, 0.1) #load all the animation objects to be drawn onto the screen # The move conductor will either play or stop the animation # Have the animation objects managed by a conductor. # With the conductor, we can call play() and stop() on all the animation # objects at the same time, so that way they'll always be in sync with each other. main_move_conductor = pyganim.PygConductor(main_anim_objs) main_width = IMAGESDICT['up standing'].get_rect().size[0] #width of image main_height = IMAGESDICT['up standing'].get_rect().size[1] #height #Actually create the main character object, but only if it is a new game. Also create the camera object. if not main_char and not camera: #if these variables are not defined camera = Camera(0, 0) #create a camera object main_char = Character(WINWIDTH // 2 - (main_width // 2), WINHEIGHT // 2 - (main_height // 2), main_width, main_height, MAIN_CHAR_WALKRATE, camera) setSpawnPosition(main_char, camera, 150, 200) #spawn the character at (150,200) #Setting up the variables for 'skeleton' monsters: skel_anim_objs = loadPygAnimObjs( 'skelwalkup skelwalkdown skelwalkright skelwalkleft skelattackup skelattackdown skelattackright skelattackleft', 8, 0.2) skel_move_conductor = pyganim.PygConductor(skel_anim_objs) skel_width = pygame.image.load('sprites/skelwalkup.png').get_rect().size[0] skel_height = pygame.image.load( 'sprites/skelwalkup.png').get_rect().size[1] skels = [] #blank list to hold skeleton objects skel_rects = [] #blank list to hold skeleton rectangle objects # Object used for drawing the map: map_obj, water_rects = getMapObj( ) #contains the x, y coordinates of each tile, while water_rects holds the world coordinates of all the tiles with water # Surfaces, fonts, and rectangles for drawing the UI (level box, etc.). Some are also defined inside the game loop as well, to reflect attribute changes level_font = pygame.font.SysFont( 'bookmanoldstyle', 40) #the font used for displaying the level of the character text_font = pygame.font.SysFont('bookmanoldstyle', 20) #the font used for everything else #some surfaces/rectangles must be defined here, even though they are redefined later, only to use the dimensions of their rectangles #the first text box text_box_surf, text_box_rect = getTextSurfAndRect(text_font, 'Health: ', WINWIDTH // 2 - 37, WINHEIGHT - 40, BLACK) text_box = pygame.transform.scale( IMAGESDICT['text box'], (text_box_rect.width, text_box_rect.height)) #status_box, which keeps track of total health, exp to level, and attack power is defined here exp_text_rect = getTextSurfAndRect( text_font, 'Level Completion: {0}% '.format(main_char.getPercentExp()), WINWIDTH - 130, WINHEIGHT - 75, BLACK)[1] status_box = pygame.transform.scale( IMAGESDICT['text box'], (exp_text_rect.width, exp_text_rect.height * 3)) #buttons to save game or return to the main menu save_box_surf, save_box_rect = getTextSurfAndRect(text_font, ' Save Game ', 70, 50, WHITE) return_box_surf, return_box_rect = getTextSurfAndRect( text_font, ' Main Menu ', 70, 20, WHITE) #play the background music for the game pygame.mixer.music.load('the_kings_crowning.mp3') pygame.mixer.music.play( -1, 0) #start the music at 0 - it will loop until stopped while True: #main game loop # Resetting a couple variables that should by default by False: mouse_clicked = False main_char.just_leveled = False # Updating the water rectangles so that their coordinates depend on the camera's position moving_water_rects = [ ] #water rects that stay in the same world position for water_rect in water_rects: moving_water_rects.append( pygame.Rect(water_rect.x - camera.x, water_rect.y - camera.y, TILESIZE, TILESIZE)) # Drawing the map: drawMap(map_obj, camera) # Spawn all of the necessary skeletons so there are always NUM_SKELS of them on the map if len(skels) < NUM_SKELS: for i in range(len(skels), NUM_SKELS ): #add however many skel/skel_rect objects we need x_spawn = random.randint( 500, 5000) #spawn each skeleton in a random spot y_spawn = random.randint(500, 2000) skels.append( Monster(x_spawn, y_spawn, skel_width, skel_height, SKEL_WALKRATE, camera, SKEL_ATTK_POW, SKEL_HEALTH)) #add a skeleton object skel_rects.append(skels[i].createRectangle( )) #create the rectangle objects for each skeleton skels[ i].moving_down = True #the initial direction of the skeleton for i in range(NUM_SKELS): skel_rects[i] = skels[i].createRectangle( ) #update the rectangle the skeleton will be blitted onto main_char_rect = main_char.createRectangle( ) # the rectangle that the main character animation will be blitted onto for event in pygame.event.get(): # event handling loop for user input if event.type == QUIT: terminate() elif event.type == KEYDOWN: if event.key == K_ESCAPE: terminate() if event.key == K_a and main_char.wielding: main_char.attacking = True if event.key == K_r and main_char.dead: char_just_died = True #variable used later if event.key == K_LEFT: main_char.moving_left = True main_char.moving_right = False if not main_char.moving_up and not main_char.moving_down: # only change the direction to up if the player wasn't moving up/down main_char.direction = 'left' elif event.key == K_RIGHT: main_char.moving_right = True main_char.moving_left = False if not main_char.moving_up and not main_char.moving_down: main_char.direction = 'right' elif event.key == K_UP: main_char.moving_up = True main_char.moving_down = False if not main_char.moving_left and not main_char.moving_right: # only change the direction to up if the player wasn't moving left/right main_char.direction = 'up' elif event.key == K_DOWN: main_char.moving_down = True main_char.moving_up = False if not main_char.moving_left and not main_char.moving_right: main_char.direction = 'down' elif event.type == KEYUP: if event.key == K_w: #wielding or unwielding weapon if main_char.wielding: main_char.wielding = False else: main_char.wielding = True if event.key == K_a and main_char.wielding: main_char.attacking = False #Stopping the player's movement in a certain direction(s) if event.key == K_UP: main_char.moving_up = False #If the player was moving in a sideways direction before, change the direction the player is facing. if main_char.moving_left: main_char.direction = 'left' if main_char.moving_right: main_char.direction = 'right' elif event.key == K_LEFT: main_char.moving_left = False if main_char.moving_up: main_char.direction = 'up' if main_char.moving_down: main_char.direction = 'down' elif event.key == K_RIGHT: main_char.moving_right = False if main_char.moving_up: main_char.direction = 'up' if main_char.moving_down: main_char.direction = 'down' elif event.key == K_UP: main_char.moving_up = False elif event.key == K_DOWN: main_char.moving_down = False if main_char.moving_left: main_char.direction = 'left' if main_char.moving_right: main_char.direction = 'right' elif event.type == MOUSEMOTION: mouse_x, mouse_y = event.pos elif event.type == MOUSEBUTTONUP: mouse_x, mouse_y = event.pos mouse_clicked = True # Handling possible game reset: if char_just_died: # If the main_char just died and we returned to the main menu - show the splash screen and then break out of the game loop so the game resets action = showSplashScreen( ) #show the splash screen until the user either loads or runs a game char_just_died = False pygame.mixer.music.stop() #stop the background music return action #exit this game loop and return the action of whether we need to load a game or not. # Handling each skeleton's battle, movement, etc. - only do this stuff if the main character is alive if main_char.dead == False: for i in range( len(skels) - 1, -1, -1 ): #For every skeleton object, perform all the code below. #It is necessary to iterate over the list in reverse, so deleting items from it works. rand_num = random.randint(1, 60) if rand_num == 1 and not skels[ i].attacking: # this will happen, on average, once every 2 seconds(since 30 FPS * 2 = 60) skels[i].changeDirectionRandom( ) #change the direction the monster is moving # Player attacking monster: if main_char_rect.colliderect( skel_rects[i] ): #an attack may not have been successfully landed, but we have definitely 'aggroed' the monster main_char.performBattle(skels[i], skel_rects[i]) if skels[i].aggroed and not skels[i].chasing: # Face the player skels[i].facePlayer(main_char) # Monster chasing player if skels[i].aggroed and not main_char_rect.colliderect( skel_rects[i]): # If the monster is out of attack range but aggroed, it will chase the main_char until its rectangle collides with the character's - combat then starts again skels[i].chasing = True if skels[i].chasing: skels[i].chaseMainChar(main_char, main_char_rect) # Monster attacking player: if skels[i].attacking and skel_rects[i].colliderect( main_char_rect): skels[i].performMonsterBattle(main_char) # Seeing whether monster is dead if skels[i].health <= 0: skels[ i].dying = True #it will be dying before it is actually dead and deleted death_anim_frames = 6 #the number of image files used for the animation death_frame_time = 0.2 #arbitrary value if not hasattr(skels[i], 'start_death_time' ): #this code will only happen once skels[i].start_death_time = time.time( ) #mark the start time of when the monster starts dying #Recreate the anim_objs object for dying to reset the frame at 0 - this is done so the dying animation looks the same each time. death_anim_obj = loadDeathPygAnimObj( death_anim_frames, death_frame_time, 'skeldie') elapsed_dying_time = time.time() - skels[ i].start_death_time #the time the dying animation has been going on for if elapsed_dying_time <= ( death_anim_frames * death_frame_time ): #if the skeleton dying animation is still going on skels[i].performDeathAnimation(death_anim_obj, camera) else: #The dying animation is over - the monster is now officially dead skels[i].dead = True main_char.experience += skels[ i].full_health #add experience to the character del skels[i] del skel_rects[i] else: #if monster is still alive, draw/animate it performMovement(skels[i], skel_rects[i], skel_move_conductor, skel_anim_objs, camera, moving_water_rects) # Drawing the main character, or playing its death animation: if main_char.health <= 0: #if dying or dead - this does essentially the same stuff as when a monster dies, but plays a 'game over' screen as well main_char.dead = True #The big 'game over' text game_over_font = pygame.font.SysFont('realvirtue', 125) game_over_surf, game_over_rect = getTextSurfAndRect( game_over_font, 'Game Over', WINWIDTH // 2, WINHEIGHT // 2, RED) pygame.draw.rect(DISPSURFACE, BLACK, game_over_rect) DISPSURFACE.blit(game_over_surf, game_over_rect) #The text telling you to go back to the home screen - drawn right below the game over text return_font = pygame.font.SysFont('realvirtue', 35) return_surf, return_rect = getTextSurfAndRect( return_font, "Press 'r' to return to the Main Menu.", WINWIDTH // 2, WINHEIGHT // 2 + (game_over_rect.height // 2) + 25, RED) pygame.draw.rect(DISPSURFACE, BLACK, return_rect) DISPSURFACE.blit(return_surf, return_rect) else: #main_char is alive performMovement(main_char, main_char_rect, main_move_conductor, main_anim_objs, camera, moving_water_rects) #draw/animate the main char if main_char.experience >= main_char.exp_to_level: #check if the character has leveled up main_char.levelUp() pygame.draw.rect( DISPSURFACE, YELLOW, main_char_rect) #blink the character yellow if so congrats_font = pygame.font.SysFont('realvirtue', 125) congrats_surf, congrats_rect = getTextSurfAndRect( congrats_font, 'LEVELED UP!', WINWIDTH // 2, WINHEIGHT // 2, YELLOW) DISPSURFACE.blit(congrats_surf, congrats_rect) main_char.just_leveled = True # Drawing the user interface with the function. The function is only passed the values not defined inside the game loop. drawCharState(main_char, text_box, text_box_rect, text_box_surf, status_box, text_font, level_font) drawButtons(save_box_surf, save_box_rect, return_box_surf, return_box_rect, False, False) # Handle mouse-clicking or motion - this is done after drawing the buttons incase they need to be redrawn. if mouse_clicked: if save_box_rect.collidepoint( mouse_x, mouse_y ): #if we are over (and clicked on) the 'save game' text rectangle saveGame(main_char, camera) elif return_box_rect.collidepoint( mouse_x, mouse_y): #clicked on 'main menu' saveGame(main_char, camera) action = showSplashScreen() pygame.mixer.music.stop() #stop the background music return action #exit the game loop and return the action of whether we need to load a game or not. else: #must be a mouse over event if save_box_rect.collidepoint( mouse_x, mouse_y): #if we are over the 'save game' text rectangle drawButtons(save_box_surf, save_box_rect, return_box_surf, return_box_rect, True, False) elif return_box_rect.collidepoint(mouse_x, mouse_y): drawButtons(save_box_surf, save_box_rect, return_box_surf, return_box_rect, False, True) pygame.display.update() #update/redraw the screen FPSCLOCK.tick(FPS) # make sure the FPS stays at the value FPS if main_char.just_leveled: #if we just leveled up, freeze the screen for a second so it shows the congratulations text for longer time.sleep(1)
WALKRATE = 3 # how many pixels to move while walking per frame ANIMRATE = 0.15 # how many seconds each frame of link's walking animation lasts # creating the PygAnimation objects for walking in all directions walkingAnim = {} walkingAnim[DOWN] = pyganim.PygAnimation(((down1, ANIMRATE), (down2, ANIMRATE))) walkingAnim[UP] = pyganim.PygAnimation(((up1, ANIMRATE), (up2, ANIMRATE))) walkingAnim[LEFT] = pyganim.PygAnimation(((left1, ANIMRATE), (left2, ANIMRATE))) # create the right-facing sprites by copying and flipping the left-facing sprites walkingAnim[RIGHT] = walkingAnim[LEFT].getCopy() walkingAnim[RIGHT].flip(True, False) walkingAnim[RIGHT].makeTransformsPermanent() # The PygConductor object keeps the animations of each direction in sync animConductor = pyganim.PygConductor(walkingAnim) def drawmainwin(): global stepCount mainwin.blit(background, (0,0)) if left: mainwin.blit(left1, (x,y)) elif right: mainwin.blit(right1, (x,y)) elif up: mainwin.blit(up1, (x,y)) elif down: mainwin.blit(down1, (x,y)) else: mainwin.blit(charstill, (x,y))
class Player(Entity): # battle stats # health - total health, once 0 death() should be called health = 0 # atk - amount of damage done to target atk = 0 # what items the enemy has, should only have 1 or 2 unless boss, similar to player.inventory[] equipped = [] # Inventory and Defense Items e.g. armor, shield # all items Entity is holding NON-EQUIPPED inventory = [] # Speed of the player speed = 0 # movement variables # moveUp = moveRight = moveDown = moveLeft = False LEFT, RIGHT, UP, DOWN = 'left right up down'.split() direction = DOWN moveup = movedown = moveleft = moveright = False hit_box = None # animations # test_img = pygame.image.load('resources/sprites/link/dev_link.png') up_sprites = pygame.image.load('resources/sprites/link/link_up.png') down_sprites = pygame.image.load('resources/sprites/link/link_down.png') right_sprites = pygame.image.load('resources/sprites/link/link_right.png') # mirrored right-facing sprites left_sprites = pygame.transform.flip(pygame.image.load('resources/sprites/link/link_right.png'), True, False) # walking sprites animations link_sprites = {'UP': pyganim.PygAnimation([('resources/sprites/link/link_up.png', 100), ('resources/sprites/link/link_up1.png', 100), ('resources/sprites/link/link_up2.png', 100), ('resources/sprites/link/link_up3.png', 100), ('resources/sprites/link/link_up4.png', 100), ('resources/sprites/link/link_up5.png', 100), ('resources/sprites/link/link_up6.png', 100), ('resources/sprites/link/link_up7.png', 100)]), 'DOWN': pyganim.PygAnimation([('resources/sprites/link/link_down.png', 100), ('resources/sprites/link/link_down1.png', 100), ('resources/sprites/link/link_down2.png', 100), ('resources/sprites/link/link_down3.png', 100), ('resources/sprites/link/link_down4.png', 100), ('resources/sprites/link/link_down5.png', 100), ('resources/sprites/link/link_down6.png', 100), ('resources/sprites/link/link_down7.png', 100)]), 'RIGHT': pyganim.PygAnimation([('resources/sprites/link/link_right.png', 100), ('resources/sprites/link/link_right1.png', 100), ('resources/sprites/link/link_right2.png', 100), ('resources/sprites/link/link_right3.png', 100), ('resources/sprites/link/link_right4.png', 100), ('resources/sprites/link/link_right5.png', 100), ('resources/sprites/link/link_right6.png', 100), ('resources/sprites/link/link_right7.png', 100)]), 'LEFT': pyganim.PygAnimation([('resources/sprites/link/link_right.png', 100), ('resources/sprites/link/link_right1.png', 100), ('resources/sprites/link/link_right2.png', 100), ('resources/sprites/link/link_right3.png', 100), ('resources/sprites/link/link_right4.png', 100), ('resources/sprites/link/link_right5.png', 100), ('resources/sprites/link/link_right6.png', 100), ('resources/sprites/link/link_right7.png', 100)]), } # inverting RIGHT sprites to get LEFT facing ones link_sprites['LEFT'].flip(True, False) link_sprites['LEFT'].makeTransformsPermanent() # conductor object controls animations easier link_conductor = pyganim.PygConductor(link_sprites) def __init__(self, x, y, e): super().__init__(x, y, e) self.health = 300 self.atk = 100 self.inventory = [] self.equipped = None self.speed = 2 # directional variables self.direction = self.DOWN self.moveup = self.movedown = self.moveleft = self.moveright = False # hitbox for the player, used in collision # make the hitbox forgiving since the sprite is almost half the size self.hit_box = pygame.Rect((self.Xpos + 8, self.Ypos + 5), (16, 21)) def draw(self, dis, cent_x, cent_y): # PLAY animation and draw correct animation for direction if self.moveleft or self.moveright or self.moveup or self.movedown: self.link_conductor.play() if self.direction == self.UP: self.link_sprites['UP'].blit(dis, (cent_x, cent_y)) if self.direction == self.DOWN: self.link_sprites['DOWN'].blit(dis, (cent_x, cent_y)) if self.direction == self.RIGHT: self.link_sprites['RIGHT'].blit(dis, (cent_x, cent_y)) if self.direction == self.LEFT: self.link_sprites['LEFT'].blit(dis, (cent_x, cent_y)) # STOP animation and draw idle sprite for last direction else: self.link_conductor.stop() if self.direction == self.UP: dis.blit(self.up_sprites, (cent_x, cent_y)) if self.direction == self.DOWN: dis.blit(self.down_sprites, (cent_x, cent_y)) if self.direction == self.RIGHT: dis.blit(self.right_sprites, (cent_x, cent_y)) if self.direction == self.LEFT: dis.blit(self.left_sprites, (cent_x, cent_y)) def hurt(self, damage): self.health -= damage if self.health < 1: self.kill() def attack(self): pass def use_item(self): pass def kill(self): pass
def LoadSprites(self, choice): if choice == 1: self.front_standing = self.ScaleSprite( 'sprites/player/cowboy_3.00.png') self.back_standing = self.ScaleSprite( 'sprites/player/cowboy_6.00.png') self.left_standing = self.ScaleSprite( 'sprites/player/cowboy_4.00.png') self.right_standing = self.ScaleSprite( 'sprites/player/cowboy_1.00.png') self.upleft_standing = self.ScaleSprite( 'sprites/player/cowboy_8.00.png') self.upright_standing = self.ScaleSprite( 'sprites/player/cowboy_7.00.png') self.downleft_standing = self.ScaleSprite( 'sprites/player/cowboy_5.00.png') self.downright_standing = self.ScaleSprite( 'sprites/player/cowboy_2.00.png') animTypes = '6 3 1 4 2 5 7 8'.split() self.animObjs = {} for animType in animTypes: imagesAndDurations = [('sprites/player/cowboy_%s.%s.png' % (animType, str(num).rjust(2, '0')), 0.1) for num in range(4)] self.animObjs[animType] = pyganim.PygAnimation( imagesAndDurations) ##cowboy walk animation elif choice == 2: self.front_standing = self.ScaleSprite( 'sprites/player/cowgirl_3.00.png') self.back_standing = self.ScaleSprite( 'sprites/player/cowgirl_6.00.png') self.left_standing = self.ScaleSprite( 'sprites/player/cowgirl_4.00.png') self.right_standing = self.ScaleSprite( 'sprites/player/cowgirl_1.00.png') self.upleft_standing = self.ScaleSprite( 'sprites/player/cowgirl_8.00.png') self.upright_standing = self.ScaleSprite( 'sprites/player/cowgirl_7.00.png') self.downleft_standing = self.ScaleSprite( 'sprites/player/cowgirl_5.00.png') self.downright_standing = self.ScaleSprite( 'sprites/player/cowgirl_2.00.png') animTypes = '6 3 1 4 2 5 7 8'.split() self.animObjs = {} for animType in animTypes: imagesAndDurations = [('sprites/player/cowgirl_%s.%s.png' % (animType, str(num).rjust(2, '0')), 0.1) for num in range(4)] self.animObjs[animType] = pyganim.PygAnimation( imagesAndDurations) ##cowgirl walk animation self.moveConductor = pyganim.PygConductor(self.animObjs) self.moveConductor.scale( (SPRITE_WIDTH, int(SPRITE_WIDTH * SPRITE_H_W_RATIO)))
import pyganim #------------------------------------------------------------------------------------------------------------------------------- #ANIMATIONS - Mechanism: Nested Lists containing file names in a Dictionary #1.Moving Goku/Vegeta Move_Chars = 'dbz_goku_flyback dbz_goku_zoop dbz_vegeta_flyback dbz_vegeta_zoop '.split( ) Move_Char = {} for Char in Move_Chars: imagesAndDurations = [ ('Images/Move_Char/%s.%s.png' % (Char, str(num).rjust(3, '0')), 0.1) for num in range(1, 5) ] Move_Char[Char] = pyganim.PygAnimation(imagesAndDurations) Move_Char_Conductor = pyganim.PygConductor(Move_Char) Move_Char_Conductor = Move_Char_Conductor.scale2x() #2.Bomb Animations Attack_Bombs = 'dbz_goku_bomb dbz_vegeta_blast'.split() Attack_Bomb = {} for Bomb in Attack_Bombs: imagesAndDurations = [ ('Images/Attack_Bomb/%s.%s.png' % (Bomb, str(num).rjust(3, '0')), 0.1) for num in range(1, 9) ] Attack_Bomb[Bomb] = pyganim.PygAnimation(imagesAndDurations, loop=False) Attack_Bomb_Conductor = pyganim.PygConductor(Attack_Bomb) Attack_Bomb_Conductor = Attack_Bomb_Conductor.scale2x()