pygame庫寫遊戲——入門

[用Python和Pygame寫遊戲-從入門到精通(1)](http://eyehere.net/2011/python-pygame-novice-professional-1/)

經過斷斷續續的學習,對python的語法有了一定的認識,並且通過廖雪峯的教程和慕課網上幾個課程的學習,模仿了其中幾個小程序的編寫。但是學習要回到實踐中來,想嘗試着編寫幾個小遊戲,發現需要學習pygame庫,而且脫離教程與模仿教程來編寫是兩種截然不同的體驗。
最終找到這位大神的博客(包含pygame庫的教學),代碼的每一行都有中文註釋,非常有助於我這種新手來理解每一行代碼的含義。
因此準備通過他的博客系統的學習pygame庫的使用,並且力圖達到可編寫小遊戲的level。
接下來的幾篇博客可以看做是自己學習中的總結吧。
1、安裝pygame庫——非常簡單,可百度。
2、檢測自己安裝的pygame庫版本:

import pygame
print(pygame.ver)
```我的版本爲1.9.3,不過版本號基本沒影響。
3、原博主的編寫的hello world!程序片段註釋非常的詳細,可以去看看。
4、自己嘗試編寫的程序
`background_filename = 'sushiplate.jpg'
mouse_filename = 'fugu.png'

import pygame
from pygame.locals import *

pygame.init()


pygame.mouse.set_visible(False)
pygame.event.set_grab(True)




<div class="se-preview-section-delimiter"></div>

#這裏可以把鼠標(小魚)上面的鼠標箭頭隱藏

screen = pygame.display.set_mode((640,480),NOFRAME,32)




<div class="se-preview-section-delimiter"></div>

#設置無邊框,也可嘗試其他的樣式
mouse_cursor = pygame.display.set_caption('hello world!')

background = pygame.image.load(background_filename).convert()
mouse_cursor = pygame.image.load(mouse_filename).convert_alpha()
while True:
  for event in pygame.event.get():
    if event.type == KEYDOWN:
      if event.key == K_SPACE:
        pygame.quit()
        #這裏做了比較大的改進,按下空格鍵,退出程序

  screen.blit(background,(0,0))

  x,y = pygame.mouse.get_pos()
  x-= mouse_cursor.get_width() /2
  y-= mouse_cursor.get_height() /2
  #注意這裏get_width()和/2中間有空格,否則會有錯誤

  screen.blit(mouse_cursor,(x,y))
  pygame.display.update()`


    ![新的hello world!程序——界面如下:](http://img.blog.csdn.net/20171128202246611?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvd2VpeGluXzQwNDk3NzEy/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
    觀察截圖中被魚替代的鼠標(顯然還有一個黑色的小鼠標沒有被完全覆蓋),這裏需要用到
    `pygame.mouse.set_visible(False)
pygame.event.set_grab(True)`
    ,但是我還沒學會-_-




<div class="se-preview-section-delimiter"></div>

for event in pygame.event.get():
if event.type == QUIT:
#接到推出事件後退出程序
pygame.quit()
“`
這是程序的退出機制,但是原博主用的是exit(),但是在我電腦上無法退出程序(程序無反應),因此改成pygame.quit()。

設置無邊框,也可嘗試其他的樣式

mouse_cursor = pygame.display.set_caption(‘hello world!’)

background = pygame.image.load(background_filename).convert()
mouse_cursor = pygame.image.load(mouse_filename).convert_alpha()
while True:
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_SPACE:
pygame.quit()
#這裏做了比較大的改進,按下空格鍵,退出程序

screen.blit(background,(0,0))

x,y = pygame.mouse.get_pos()
x-= mouse_cursor.get_width() /2
y-= mouse_cursor.get_height() /2
#注意這裏get_width()和/2中間有空格,否則會有錯誤

screen.blit(mouse_cursor,(x,y))
pygame.display.update()`


新的hello world!程序——界面如下:
觀察截圖中被魚替代的鼠標(顯然還有一個黑色的小鼠標沒有被完全覆蓋),這裏需要用到
,但是我還沒學會-_-

for event in pygame.event.get():
if event.type == QUIT:
#接到推出事件後退出程序
pygame.quit()

這是程序的退出機制,但是原博主用的是exit(),但是在我電腦上無法退出程序(程序無反應),因此改成pygame.quit()。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章