楽しいスキーヤーゲーム



Fun Skier Game



今日のPythonの学習コンテンツは非常に興味深いものです。クラスメソッドを使用して、スキーの悪役の動きを実現する方法を学ぶことです。これは、ゲームのツリーとフラグの動きに直接コード上で導き出すことができます。

import pygame import random pygame.init() Window = pygame.display.set_mode((640,600)) #Window size Window.fill([255, 255, 255]) # Fill the background with white class SkierClass(pygame.sprite.Sprite): '''Implementation of the inheritance of the sprite class, complete the ski villain'' def __init__(self,image,position,speed): ''' :param image: the path to the image :param position: list type, [x horizontal axis coordinate, y vertical axis coordinate] :param speed: list type, [horizontal axis speed, vertical axis speed] ''' pygame.sprite.Sprite.__init__(self) Self.image = pygame.image.load(image) #, load snowman image Self.rect = self.image.get_rect() # # Get the rectangle of the image boundary Self.rect.left,self.rect.top = position #Set the initial position of the image self.speed = speed def move(self): '''This method implements villain movement, using rec's built-in move method ''' retdata = self.rect.move(self.speed) Print('move method's return value', retdata) self.rect = retdata #Set the boundary condition of the move if self.rect.left 640: self.speed[0] = -self.speed[0] if self.rect.top 600: self.speed[1] = -self.speed[1] if __name__ == '__main__': # Create a single villain instance Ski = SkierClass('.skier_down.png', [500, 100],[0,1]) #Enter the input image path, position, speed # while True: for event in pygame.event.get(): if event.type == pygame.QUIT: Print('game exit') exit() Window.fill([255,255,255]) #Create a new background that covers the previous remaining villain ski.move() Window.blit(ski.image,ski.rect) #Add image to window display Pygame.display.update() #refresh