Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
在這篇文章中,我們將展示如何使用Python編程語言和Pygame庫來創建經典的貪食蛇遊戲。這個遊戲的目標是控制一條蛇,吃到屏幕上隨機出現的食物,並避免撞到自己或遊戲窗口的邊界。
首先,確保你已經安裝了Pygame庫。如果還沒有安裝,可以通過下面的命令來安裝:
pip install pygame
現在,開始編寫我們的貪食蛇遊戲的程式碼:
import pygame
import random
import time
# 初始化Pygame
pygame.init()
# 設定遊戲窗口
width, height = 500, 500
window = pygame.display.set_mode((width, height))
pygame.display.set_caption('貪食蛇遊戲')
# 設定顏色
white = (255, 255, 255)
red = (213, 50, 80)
green = (0, 255, 0)
blue = (50, 153, 213)
# 蛇的初始設定
snake_pos = [100, 50]
snake_body = [[100, 50],
[90, 50],
[80, 50]]
direction = 'RIGHT'
change_to = direction
# 食物的初始設定
food_pos = [random.randrange(1, (width//10)) * 10,
random.randrange(1, (height//10)) * 10]
food_spawn = True
# 設定遊戲速度
clock = pygame.time.Clock()
while True:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
change_to = 'UP'
if event.key == pygame.K_DOWN:
change_to = 'DOWN'
if event.key == pygame.K_LEFT:
change_to = 'LEFT'
if event.key == pygame.K_RIGHT:
change_to = 'RIGHT'
# 如果方向有變化,更新方向
if change_to == 'UP' and not direction == 'DOWN':
direction = 'UP'
if change_to == 'DOWN' and not direction == 'UP':
direction = 'DOWN'
if change_to == 'LEFT' and not direction == 'RIGHT':
direction = 'LEFT'
if change_to == 'RIGHT' and not direction == 'LEFT':
direction = 'RIGHT'
# 更新蛇的位置
if direction == 'UP':
snake_pos[1] -= 10
if direction == 'DOWN':
snake_pos[1] += 10
if direction == 'LEFT':
snake_pos[0] -= 10
if direction == 'RIGHT':
snake_pos[0] += 10
# 蛇身體增長機制
snake_body.insert(0, list(snake_pos))
if snake_pos[0] == food_pos[0] and snake_pos[1] == food_pos[1]:
food_spawn = False
else:
snake_body.pop()
if not food_spawn:
food_pos = [random.randrange(1, (width//10)) * 10,
random.randrange(1, (height//10)) * 10]
food_spawn = True
# 清空遊戲窗口
window.fill(blue)
# 繪製貪食蛇和食物
for pos in snake_body:
pygame.draw.rect(window, green,
pygame.Rect(pos[0], pos[1], 10, 10))
pygame.draw.rect(window, red,
pygame.Rect(food_pos[0], food_pos[1], 10, 10))
# 更新遊戲窗口
pygame.display.update()
# 控制遊戲速度
clock.tick(20)
# 檢查蛇是否撞到邊界或自己
if (snake_pos[0] not in range(0, width) or
snake_pos[1] not in range(0, height) or
snake_pos in snake_body[1:]):
pygame.quit()
quit()
在上面的程式碼中,我們首先初始化了Pygame庫,然後設定了遊戲窗口的大小和標題。接著,我們設定了蛇和食物的初始位置,並創建了一個遊戲循環來處理用戶輸入和遊戲邏輯。我們用pygame.event.get()
來檢測用戶的鍵盤輸入,並更新蛇的方向。
這只是貪食蛇遊戲的基本框架,你還可以增加碰撞檢測、得分系統和遊戲結束條件等功能,以使遊戲更加完整和有趣。透過這個教程,你應該能夠理解如何使用Python和pygame庫來創建基本的遊戲,並可以在此基礎上進一步探索和創建自己的遊戲。