# Python班
## 4/12社課
---
### 本次課程內容
* 全域變數
* 鍵盤按鍵偵測
---
## 前情提要
上次我們有做一個方塊從左跑到右的程式,把它開出來,我們今天要繼續用它來實做
---
### 角色跳躍
---
#### 目標
我們預期的最終的結果
按SPACE$\to$跳起來$\to$落地
----
#### 前置作業
先幫我創出一個類別叫做Player
要求:
1. 角色大小為20*50
2. 角色是深藍色
3. 請假想 y = 210處是地板,讓角色站在地板上
----
```=
class Player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((20, 40))
self.image.fill((0, 0, 255))
self.rect = self.image.get_rect()
self.rect.centerx = WIDTH // 2
self.rect.bottom = 210
self.vy = 0
```
----
因為等等跳起來會牽涉到角色的速度,所以我給這個類別的物件加了一個「$\texttt{self.vy}$」的變數
----
#### 怎麼跳起來
可以用下面這個模式
```=
self.rect.y -= self.vy
self.vy -= 1
if self.rect.bottom > 210:
self.rect.bottom = 210
self.vy = 0
```
----
但直接寫在$\texttt{update}$肯定不行,所以我們需要一個東西來判斷有沒有在「跳躍狀態」
----
#### 使用全域變數
我們用一個$\texttt{jumping}$來記錄角色的狀態
```=
if jumping:
self.rect.y -= self.vy
self.vy -= 1
if self.rect.bottom > 210:
self.rect.bottom = 210
self.vy = 0
jumping = False
```
----
然後把它寫在$\texttt{update}$裡
```=
def update(self):
if jumping:
self.rect.y -= self.vy
self.vy -= 1
if self.rect.bottom > 210:
self.rect.bottom = 210
self.vy = 0
jumping = False
```
----
但這樣會出錯,因為jumping理論上要是全域變數
所以我們在寫的時候要加上一句
```=
def update(self):
global jumping #here
if jumping:
self.rect.y -= self.vy
self.vy -= 1
if self.rect.bottom > 210:
self.rect.bottom = 210
self.vy = 0
jumping = False
```
告訴電腦我們現在用的是全域變數
---
### 鍵盤偵測
----
要想偵測鍵盤的按鍵,要這樣寫
```=
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
```
----
所以如果要按下空白後跳起,可以這樣寫
```=
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
jumping = True
```
----
還需要設置角色的起跳速度,所以我們可以去角色裡面定義一個函式叫做$\texttt{jump}$
```=
def jump(self):
self.vy = 10
```
----
所以最後就有
```=
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
jumping = True
player.jump()
```
---
---
# 謝謝大家
{"title":"112-2-Pygame-全域變數、按鍵偵測、角色跳躍","contributors":"[{\"id\":\"084e105f-92be-4605-b399-8d3c0ef40c64\",\"add\":6614,\"del\":4527}]"}