本篇文章展示如何使用Pygame來控制遊戲中角色的移動。可參考此篇教學:「Day27-安裝使用PyGame套件」來安裝 Pygame;或是使用有內建Pygame的Mu Code Editor,本文將使用Mu Code Editor來示範。開啟Mu Editor後,要先設定程式碼撰寫的模式(Mode),請點選Mu Editor左上角的 Mode圖示:
選擇Pygame Zero:
按下 New 的圖示:
接著就要開始寫程式了!程式碼如下:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
import pygame | |
pygame.init() | |
# | |
# Step 1: Create the screen window | |
# | |
# Screen width, height | |
S_W = 500 | |
S_H = 500 | |
winScreen = pygame.display.set_mode((S_W, S_H)) | |
pygame.display.set_caption("Keyboard Demo") | |
# | |
# Step 2: Set the Ball's velocity, position, size | |
# | |
R = 20 | |
x = int((S_W - R) / 2) | |
y = int((S_H - R) / 2) | |
vel = 5 | |
run = True | |
while run: | |
pygame.time.delay(10) | |
# | |
# Step 3: Detect which key is pressed. | |
# | |
for event in pygame.event.get(): | |
if event.type == pygame.QUIT: | |
run = False | |
keys = pygame.key.get_pressed() | |
if keys[pygame.K_LEFT]: | |
x -= vel | |
if keys[pygame.K_RIGHT]: | |
x += vel | |
if keys[pygame.K_UP]: | |
y -= vel | |
if keys[pygame.K_DOWN]: | |
y += vel | |
# | |
# Step 4: Draw the ball. | |
# | |
winScreen.fill((0, 0, 0)) # Fills the screen with black | |
pygame.draw.circle(winScreen, (255, 255, 0), (x, y), R) | |
pygame.display.update() | |
pygame.quit() |
參考資料:
[1] https://techwithtim.net/tutorials/game-development-with-python/pygame-tutorial/pygame-tutorial-movement/
沒有留言:
張貼留言