一、實驗內容:跳動的小球游戲介紹
二、實驗物件:《零基礎學Python》第13章 Pygame游戲編程 實體01
用以下代碼創建一個游戲彈窗:
匯入pygame模塊并且用init()方法初始化,設定視窗的寬和高,使用display模塊顯示表單,
點擊查看代碼
import sys
import pygame
pygame.init()
size=width,height=640,480 #初始化pygame
screen=pygame.display.set_mode(size)
使用pygameevent.get()獲取事件佇列,用for...in遍歷事件,type屬性判斷事件型別.
點擊查看代碼
for event in pygame.event.get():
if event.type == pygame.QUIT:
使用image模塊的load()方法加載圖片,在視窗中添加小球的代碼如下:
點擊查看代碼
ball=pygame.image.load("ball.png")
ballrect=ball.get_rect()
...
screen.blit(ball,ballrect) #將圖片畫到視窗上
將move()函式添加到while循壞內,實作小球不停地移動:
點擊查看代碼
while True:
clock.tick(60)
#檢查事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
ballrect = ballrect.move(speed)
添加碰撞檢測的功能和“時鐘”,“時鐘”是為了控制程式運行的時間,整個小游戲的完整代碼以及運行結果如下:
點擊查看代碼
#-*- coding:utf-8-*-
import sys
import pygame
pygame.init()
size=width,height=640,480 #初始化pygame
screen=pygame.display.set_mode(size)
color=(0,0,0) #設定顏色
ball=pygame.image.load("ball.png")
ballrect=ball.get_rect()
speed=[5,5]
clock=pygame.time.Clock() #設定時鐘
#執行死回圈,確保視窗一直顯示
while True:
clock.tick(60)
#檢查事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
ballrect = ballrect.move(speed)
#碰到左右邊緣
if ballrect.left < 0 or ballrect.right > width:
speed[0]=-speed[0]
#碰到上下邊緣
if ballrect.top < 0 or ballrect.bottom > height:
speed[1]=-speed[1]
screen.fill(color) #填充顏色
screen.blit(ball,ballrect) #將圖片畫到視窗上
pygame.display.flip() #更新全部顯示

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/539120.html
標籤:其他
上一篇:canary繞過
