一、Pygame庫 Pygame是一個(gè)利用SDL庫寫的游戲庫,SDL庫全名:Simple DirectMedia Layer,據(jù)說是SamLantinga寫的大牛寫的為了讓Loki(公司)更好的向linux上移植Windows的游戲,后來倒閉了 SDL是使用C寫的,Pygame是Python中的一個(gè)常用的庫 接下來記錄使用Pycharm編寫Python3.7的個(gè)人版超級瑪麗游戲,Pygame更適合于制作2D游戲開發(fā) 二、先放上代碼和第一個(gè)背景界面 1 import pygame ,sys 2 3 pygame.init() 4 size = width,height = 1000,750 #設(shè)置整個(gè)界面的大小 5 speed = [1,1] 6 BLACK = 2,100,30 7 8 9 screen = pygame.display.set_mode((size)) 10 pygame.display.set_caption(" 三川之水") 11 12 pygame.mixer.music.load("music/home.mp3") 13 pygame.mixer.music.set_volume(0.2) 14 pygame.mixer.music.play(-1) 15 16 background = pygame.image.load("image/background.png").convert() 17 ball = pygame.image.load(r"image/ball.png") 18 ballrect = ball.get_rect() 19 20 fps = 180 21 myclock = pygame.time.Clock() 22 23 24 25 while True: 26 for event in pygame.event.get(): 27 if __name__ == '__main__': 28 if event.type == pygame.QUIT: 29 sys.exit() 30 elif event.type == pygame.KEYDOWN: 31 if event.key == pygame.K_LEFT: 32 #speed[0] = speed[0] if speed[0] == 0 else (abs(speed[0]) - 1)* int (speed[0]/abs(speed[0])) 33 if speed[0] >= 0: 34 speed[0] = speed[0] - 1 35 elif speed[0] == 0: 36 speed[0] = -speed[0] 37 else: 38 speed[0] = speed[0] - 1 39 elif event.key == pygame.K_RIGHT: 40 speed[0] = speed[0] 1 if speed[0] > 0 else speed[0] - 1 41 elif event.key == pygame.K_UP: 42 speed[1] = speed[1] 1 if speed[1] > 0 else speed[1] - 1 43 elif event.key == pygame.K_DOWN: 44 speed[1] = speed[1] if speed[1] == 0 else (abs(speed[1]) - 1) * int(speed[1] / abs(speed[1])) 45 46 ballrect = ballrect.move(speed[0],speed[1]) 47 if ballrect.left < 0 or ballrect.right > width: 48 speed[0] = -speed[0] 49 if ballrect.top < 0 or ballrect.bottom > height: 50 speed[1] = -speed[1] 51 52 screen.blit(background,(0,0)) 53 screen.blit(ball,ballrect) 54 pygame.display.update() 55 myclock.tick(fps)View Code ? 來源:https://www./content-4-398051.html |
|