目录
简介
使用合宙esp32c3模块,基于micropython平台开发的一款oled小游戏,恐龙快跑,所有代码已经给出,将两个py文件放进esp32c3里即可运行,使用的是硬件i2c,这个ssd1306.py文件是我优化过的,许多用法可查看源码即可推敲,只支持128*64的I2C oled一定要用我提供的ssd1306驱动。
效果展示
esp32 micropython oled恐龙快跑
源代码
main.py
from ssd1306 import SSD1306_I2C
from machine import Pin,I2C,ADC
import time
import random
i2c=I2C(0,scl=Pin(5),sda=Pin(4))
oled=SSD1306_I2C(i2c)
ps2x=ADC(Pin(2))
ps2x.atten(ADC.ATTN_11DB)
#生命值的绘制
live_list=[0x30,0x4C,0x42,0x21,0x21,0x42,0x4C,0x30]
#绘制恐龙
dinosaur=[0x03,0x01,0x00,0x00,0x00,0x00,0x01,0x03,0x07,0x7F,0xFF,0x8F,0xAF,0x8D,0xF9,0x78,
0xC0,0xE0,0xF0,0x78,0x7F,0xFD,0xF0,0xFC,0xFF,0xF9,0xF0,0xE0,0xC0,0x00,0x80,0x00]
#初始化屏幕
oled.fill(0)
oled.p8(live_list,0,0)
oled.p8(live_list,9,0)
oled.p8(live_list,18,0)
oled.text('0',120,0)
oled.p16(dinosaur,0,48)
oled.rect(117,53,10,10,True)
oled.show()
#设定游戏参数,一次跳跃用12帧数据处理
jump = 0
jump_num = [48,34,23,15,10,8]#根据恐龙的跳跃位置和自由落体运动规律得到的每帧绘制恐龙的位置
fall = False#降落标志
score = 0#分数
x = 0
live=3#生命值为3
#障碍物随机坐标
box1 = random.randint(40,120)
box2 = random.randint(40,120) + box1
speed = 3#初始游戏速度
while True:
#如果还有生命值
if live:
#当摇杆推动且恐龙在地平线上才触发跳动
if ps2x.read()>2500 and jump == 0:
jump = 1
#一直升高直到最高点
if jump != 0:
jump += 1 if not fall else -1
#降落到地面
if jump == 0:
fall = False
score += 1
if jump == 5:
fall = True#跳到最高点下落
x += speed
speed = 3 + score//10#速度随积分增加
#刷新屏幕
oled.fill(0)
#显示血量值
for i in range(live):
oled.p8(live_list,i*9,0)
#更新分数
oled.text(str(score),120,0)
#画小恐龙的外形
oled.p16(dinosaur,0,jump_num[jump])

本文介绍了使用ESP32C3模块和Micropython开发的OLED小游戏——恐龙快跑,包含源代码和实现思路,涉及血量值、分数计分、恐龙跳跃动画、障碍物移动以及碰撞检测等元素。
最低0.47元/天 解锁文章
1423





