小游戏系列——贪吃蛇

2025-05-03193
AI 快速预览详细 收起
本文介绍了如何使用mpython和Python代码实现经典的贪吃蛇游戏。项目名称为“贪吃蛇”,硬件清单包括mpython设备。最终效果是玩家可以通过AB键控制蛇的方向,吃到食物并逐渐变长。难度等级适中,适合初学者入门。

AB键左右转

 

 

from mpython import *
import random
import time

GRID_SIZE = 4
SCREEN_WIDTH = 128
SCREEN_HEIGHT = 64

# 游戏变量
snake = []
direction = 0  # 0右 1下 2左 3上
food = (0, 0)
move_delay = 400  # 毫秒
last_move_time = time.ticks_ms()
last_input_time = time.ticks_ms()
input_interval = 50  # 毫秒
last_a = 1
last_b = 1
score = 0

def generate_food():
   global food
   max_x = SCREEN_WIDTH // GRID_SIZE
   max_y = SCREEN_HEIGHT // GRID_SIZE
   while True:
       fx = random.randint(0, max_x - 1) * GRID_SIZE
       fy = random.randint(0, max_y - 1) * GRID_SIZE
       if (fx, fy) not in snake:
           food = (fx, fy)
           break

def draw():
   oled.fill(0)
   for i, (x, y) in enumerate(snake):
       if i == 0:
           oled.rect(x, y, GRID_SIZE, GRID_SIZE, 1)  # 空心方块作为蛇头
       else:
           oled.fill_rect(x, y, GRID_SIZE, GRID_SIZE, 1)  # 实心身体
   oled.fill_rect(food[0], food[1], GRID_SIZE, GRID_SIZE, 1)  # 食物
   oled.show()

def game_over():
   global score
   oled.fill(0)
   oled.text("Game Over", 27, 20)
   oled.text("Score: {}".format(score), 29, 38)
   oled.show()
   while True:
       if button_a.value() == 0 or button_b.value() == 0:
           time.sleep(0.2)
           break

def reset_game():
   global snake, direction, food, score
   global last_move_time, last_input_time, last_a, last_b
   snake = [(40, 32), (36, 32), (32, 32)]
   direction = 0
   generate_food()
   score = 0
   last_move_time = time.ticks_ms()
   last_input_time = time.ticks_ms()
   last_a = 1
   last_b = 1

reset_game()

while True:
   now = time.ticks_ms()

   # 处理方向输入
   if time.ticks_diff(now, last_input_time) >= input_interval:
       a = button_a.value()
       b = button_b.value()

       if a == 0 and last_a == 1:
           direction = (direction + 3) % 4  # 左转
       if b == 0 and last_b == 1:
           direction = (direction + 1) % 4  # 右转

       last_a = a
       last_b = b
       last_input_time = now

   # 移动蛇
   if time.ticks_diff(now, last_move_time) >= move_delay:
       head_x, head_y = snake[0]
       if direction == 0:
           head_x += GRID_SIZE
       elif direction == 1:
           head_y += GRID_SIZE
       elif direction == 2:
           head_x -= GRID_SIZE
       elif direction == 3:
           head_y -= GRID_SIZE

       new_head = (head_x, head_y)

       # 碰撞检测
       if (
           head_x < 0 or head_x >= SCREEN_WIDTH or
           head_y < 0 or head_y >= SCREEN_HEIGHT or
           new_head in snake
       ):
           game_over()
           reset_game()
           continue

       snake.insert(0, new_head)

       if new_head == food:
           score += 1
           generate_food()
       else:
           snake.pop()

       draw()
       last_move_time = now

创作许可协议

本项目采用 None(不开放任何权利,保留所有权利) 进行许可。

评论(0)
- 没有更多了 -