一日一技:用Python做遊戲有多簡單

專注的阿熊發表於2022-06-07

import pygame

class Bg(pygame.sprite.Sprite):

     def __init__(self):

         super(Bg, self).__init__()

         bg_small = pygame.image.load('bg.png').convert_alpha()

         grass_land = bg_small.subsurface((0, 0, 128, 128))

         self.surf = pygame.transform.scale(grass_land, (800, 600))

         self.rect = self.surf.get_rect(left=0, top=0)  # 左上角定位

class Pig(pygame.sprite.Sprite):

     def __init__(self):

         super(Pig, self).__init__()

         self.surf = pygame.image.load('pig_in_car.png').convert_alpha()

         self.rect = self.surf.get_rect(center=(400, 300))  # 中心定位

     def update(self, keys):

         if keys[pygame.K_LEFT]:

             self.rect.move_ip((-5, 0))

         elif keys[pygame.K_RIGHT]:

             self.rect.move_ip((5, 0))

         elif keys[pygame.K_UP]:

             self.rect.move_ip((0, -5))

         elif keys[pygame.K_DOWN]:

             self.rect.move_ip((0, 5))

         # 防止小豬跑到螢幕外面

         if self.rect.left < 0:

             self.rect.left = 0

         if self.rect.right > 800:

             self.rect.right = 800

         if self.rect.top < 0:

             self.rect.top = 0

         if self.rect.bottom > 600:

             self.rect.bottom = 600

class Goddess(pygame.sprite.Sprite):

     def __init__(self):

         super(Goddess, self).__init__()

         building = pygame.image.load('building.png').convert_alpha()

         self.surf = 跟單網gendan5.combuilding.subsurface(((7 * 64 - 10, 0, 50, 100)))

         self.rect = self.surf.get_rect(center=(500, 430))  # 女神像的中心放到畫布 (500, 430) 的位置

def main():

     pygame.init()

     pygame.display.set_caption(' 未聞 Code :青南做的遊戲 ')  # 遊戲標題

     win = pygame.display.set_mode((800, 600))  # 視窗尺寸

     bg = Bg()

     goddess = Goddess()

     pig = Pig()

     all_sprites = [bg, goddess, pig]  # 注意新增順序,後新增的物件圖層在先新增的物件的圖層上面

     running = True

     while running:

         for event in pygame.event.get():

             if event.type == pygame.QUIT:  # 點選左上角或者右上角的 x 關閉視窗時,停止程式

                 running = False

         keys = pygame.key.get_pressed()

         pig.update(keys)

         for sprite in all_sprites:

             win.blit(sprite.surf, sprite.rect)

         pygame.display.flip()

if __name__ == '__main__':

     main()


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/69946337/viewspace-2899272/,如需轉載,請註明出處,否則將追究法律責任。

相關文章