2021-05-12 14:32:11
在Ubuntu 18.04 LTS上Python模組pygame安裝
簡介
Pygame是跨平台Python模組,專為電子遊戲設計,包含影象、聲音。建立在SDL基礎上,允許實時電子遊戲研發而無需被低階語言(如機器語言和組合語言)束縛。
效果截圖如下
安裝
linuxidc@linuxidc:~/www.linuxidc.com/Linux公社 -$ sudo pip install pygame
[sudo] linuxidc 的密碼:
The directory '/home/linuxidc/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
The directory '/home/linuxidc/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
Collecting pygame
Downloading https://files.pythonhosted.org/packages/26/38/947e70c170e03f0e0aee61ae2e2157278d6146447d2b8cc8c46be5986b3e/pygame-1.9.4-cp27-cp27mu-manylinux1_x86_64.whl (12.0MB)
100% |████████████████████████████████| 12.0MB 27kB/s
Installing collected packages: pygame
Successfully installed pygame-1.9.4
驗證
linuxidc@linuxidc:~/www.linuxidc.com/Linux公社 -$ python
Python 2.7.15rc1 (default, Nov 12 2018, 14:31:15)
[GCC 7.3.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pygame
pygame 1.9.4
Hello from the pygame community. https://www.pygame.org/contribute.html
在命令列上輸入python,再import pygame, 如果沒有報錯,說明python安裝成功。
範例
下面借用網上的例子展示一下效果,給出《飄雪》的動畫效果,背景音樂是陳慧嫻那首《飄雪》
#!/usr/bin/env python
#coding: utf-8
#description: 製作下雪特效
#refer: https://github.com/crossin/snippet/blob/master/snow/snow.py
#date:2019-01-08
import pygame
import random
# 初始化pygame
pygame.init()
#可以配上點背景音樂
pygame.mixer.init()
pygame.mixer.music.load('飄雪.mp3')
pygame.mixer.music.play()
# 根據背景圖片的大小,設定螢幕長寬
SIZE = (1364, 569)
screen = pygame.display.set_mode(SIZE)
pygame.display.set_caption("飄雪")
bg = pygame.image.load('snow.jpg')
# 雪花列表
snow_list = []
# 初始化雪花:[x坐標, y坐標, x軸速度, y軸速度]
for i in range(200):
x = random.randrange(0, SIZE[0])
y = random.randrange(0, SIZE[1])
sx = random.randint(-1, 1)
sy = random.randint(3, 6)
snow_list.append([x, y, sx, sy])
clock = pygame.time.Clock()
# 遊戲主迴圈
done = False
while not done:
# 訊息事件迴圈,判斷退出
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# 黑背景/圖片背景
# screen.fill((0, 0, 0))
screen.blit(bg, (0, 0))
# 雪花列表迴圈
for i in range(len(snow_list)):
# 繪製雪花,顏色、位置、大小
pygame.draw.circle(screen, (255, 255, 255), snow_list[i][:2], snow_list[i][3]-3)
# 移動雪花位置(下一次迴圈起效)
snow_list[i][0] += snow_list[i][2]
snow_list[i][1] += snow_list[i][3]
# 如果雪花落出螢幕,重設位置
if snow_list[i][1] > SIZE[1]:
snow_list[i][1] = random.randrange(-50, -10)
snow_list[i][0] = random.randrange(0, SIZE[0])
# 重新整理螢幕
pygame.display.flip()
clock.tick(20)
# 退出
pygame.quit()
相關文章