首先,我們需要導入pygame
庫來實現游戲的圖形化界面:
import pygame
然后,定義一些常量來表示游戲窗口的寬度和高度、蛇身的大小、食物的大小等:
WIDTH = 600
HEIGHT = 400
SNAKE_SIZE = 20
FOOD_SIZE = 20
接下來,定義一個Snake
類來表示蛇的屬性和行為:
class Snake:
def __init__(self):
self.head = [100, 50] # 蛇頭的位置
self.body = [[100, 50], [90, 50], [80, 50]] # 蛇身的位置
self.direction = "RIGHT" # 蛇的移動方向
def move(self):
if self.direction == "RIGHT":
self.head[0] += SNAKE_SIZE
elif self.direction == "LEFT":
self.head[0] -= SNAKE_SIZE
elif self.direction == "UP":
self.head[1] -= SNAKE_SIZE
elif self.direction == "DOWN":
self.head[1] += SNAKE_SIZE
# 將新的蛇頭位置添加到蛇身中
self.body.insert(0, list(self.head))
# 如果蛇頭和食物的位置重合,則蛇吃到了食物,身體增長
if self.head[0] == food.position[0] and self.head[1] == food.position[1]:
food.generate() # 生成新的食物
else:
self.body.pop() # 否則,蛇身減少一個位置
def change_direction(self, direction):
# 不允許蛇直接掉頭
if direction == "RIGHT" and self.direction != "LEFT":
self.direction = "RIGHT"
elif direction == "LEFT" and self.direction != "RIGHT":
self.direction = "LEFT"
elif direction == "UP" and self.direction != "DOWN":
self.direction = "UP"
elif direction == "DOWN" and self.direction != "UP":
self.direction = "DOWN"
然后,定義一個Food
類來表示食物的屬性和行為:
class Food:
def __init__(self):
self.position = [0, 0]
def generate(self):
# 隨機生成食物的位置
self.position[0] = random.randint(1, (WIDTH - FOOD_SIZE) / FOOD_SIZE) * FOOD_SIZE
self.position[1] = random.randint(1, (HEIGHT - FOOD_SIZE) / FOOD_SIZE) * FOOD_SIZE
接下來,初始化游戲并創建蛇和食物的實例:
pygame.init()
window = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("貪吃蛇小游戲")
snake = Snake()
food = Food()
food.generate()
然后,創建一個游戲循環,處理用戶的輸入和游戲邏輯:
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
snake.change_direction("RIGHT")
elif event.key == pygame.K_LEFT:
snake.change_direction("LEFT")
elif event.key == pygame.K_UP:
snake.change_direction("UP")
elif event.key == pygame.K_DOWN:
snake.change_direction("DOWN")
snake.move()
# 判斷蛇是否撞到墻壁或自己的身體
if snake.head[0] >= WIDTH or snake.head[0] < 0 or snake.head[1] >= HEIGHT or snake.head[1] < 0 or snake.head in snake.body[1:]:
pygame.quit()
sys.exit()
window.fill((255, 255, 255))
# 繪制蛇的身體
for pos in snake.body:
pygame.draw.rect(window, (0, 255, 0), pygame.Rect(pos[0], pos[1], SNAKE_SIZE, SNAKE_SIZE))
# 繪制食物
pygame.draw.rect(window, (255, 0, 0), pygame.Rect(food.position[0], food.position[1], FOOD_SIZE, FOOD_SIZE))
pygame.display.update