簡陋的貪吃蛇小遊戲
# -*- coding:utf-8 -*-
# 匯入庫
import sys
import time
import random
import pygame
from pygame.locals import *
# 引數設定
WIDTH = 640
HEIGHT = 480
BLOCK = 20
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# 退出程式
def terminal():
pygame.quit()
sys.exit()
# 繪製食物
def draw_food(window, point):
rect = pygame.Rect(point[0], point[1], BLOCK, BLOCK)
pygame.draw.rect(window, RED, rect)
# 繪製貪吃蛇
def draw_snake(window, snake_body):
for point in snake_body:
rect = pygame.Rect(point[0], point[1], BLOCK, BLOCK)
pygame.draw.rect(window, GREEN, rect)
# 貪吃蛇移動
def move_snake(snake_body, direction, food_position):
if direction == 'up':
snake_body.insert(0, [snake_body[0][0], snake_body[0][1] - BLOCK])
if direction == 'down':
snake_body.insert(0, [snake_body[0][0], snake_body[0][1] + BLOCK])
if direction == 'left':
snake_body.insert(0, [snake_body[0][0] - BLOCK, snake_body[0][1]])
if direction == 'right':
snake_body.insert(0, [snake_body[0][0] + BLOCK, snake_body[0][1]])
# 吃到食物
if snake_body[0] == food_position:
food_position = [random.randrange(0, WIDTH, BLOCK), random.randrange(0, HEIGHT, BLOCK)]
else:
snake_body.pop()
# 是否撞牆、撞身體
alive = True
if snake_body[0][0] < 0 or snake_body[0][0] + BLOCK > WIDTH:
alive = False
elif snake_body[0][1] < 0 or snake_body[0][1] + BLOCK > HEIGHT:
alive = False
elif snake_body[0] in snake_body[1:]:
alive = False
return snake_body, food_position, alive
# 遊戲結束並退出程式
def game_over(window):
msg = pygame.font.SysFont('arial', 20)
msg = msg.render('Game over', 1, RED)
window.blit(msg, (10, 10))
pygame.display.flip()
time.sleep(2) # 等待2秒後退出
terminal()
# 監控滑鼠、鍵盤
def monitor_action(direction):
for event in pygame.event.get():
if event.type == QUIT: # 右上角關閉按鈕
terminal()
if event.type == KEYDOWN:
if event.key == K_UP and direction != 'down':
direction = 'up'
elif event.key == K_DOWN and direction != 'up':
direction = 'down'
elif event.key == K_LEFT and direction != 'right':
direction = 'left'
elif event.key == K_RIGHT and direction != 'left':
direction = 'right'
elif event.key == K_ESCAPE: # ‘ESC’鍵退出程式
terminal()
return direction
# 執行遊戲
def run_game():
pygame.init() # 模組初始化
window = pygame.display.set_mode((WIDTH, HEIGHT)) # 新建視窗
pygame.display.set_caption('貪吃蛇遊戲') # 視窗標題
clock = pygame.time.Clock() # 計時器
# 貪吃蛇、食物初始狀態
food_position = [300, 300]
snake_body = [[100, 100], [80, 100]]
direction = 'right'
while True:
window.fill(WHITE) # 繪製背景
draw_food(window, food_position)
draw_snake(window, snake_body)
pygame.display.flip() # 重新整理螢幕
direction = monitor_action(direction) # 控制方向
snake_body, food_position, alive = move_snake(snake_body, direction, food_position) # 計算下一次繪製物體
if not alive:
game_over(window)
clock.tick(10) # 重新整理頻率,1秒重新整理5次
terminal()
return 0
# 呼叫函數
run_game()
執行效果: