本文主要是介绍显示学习4(基于树莓派Pico) -- 游戏,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
来自:https://github.com/zelacerda/micropython
代码改造了一下,让它可以跑起来。
简单分析一下代码。外层是一个死循环,有一个状态机来对应不同的场景。
def loop():while True:if state == 0: splash_screen()elif state == 1: game_waiting()elif state == 2: game_running()elif state == 3: game_over()
0是最开始的场景,通过检查按键进行切换。
button = Pin(13, Pin.IN)
按键之后切换到running。
def game_running():global stateif clicked(): flappy_bird.flap()flappy_bird.move()if flappy_bird.crashed():flappy_bird.y = HEIGHT - flappy_bird.heightstate = 3obstacle_1.scroll()obstacle_2.scroll()if obstacle_1.collided(flappy_bird.y) or obstacle_2.collided(flappy_bird.y):state = 3draw()
看了running其实就明白,所有的操作,以帧为单位。
进入这一帧时,首先调用move函数,根据按键来更新小鸟的位置,然后判断小鸟是否飞出去了。
然后更新障碍物的位置,是scroll接口,然后判断障碍物和小鸟是否碰撞。
更新位置之后,调用draw接口,在Framebuffer中进行更新后显示。
显示的部分,还有挺有趣。小鸟,障碍物是这样表示的,是三个字符串:
# Bitmap images
BIRD = '07e018f021f871ecf9ecfcfcbe7e4c81717e4082307c0f80'
COL1 = '201c'*26+'ffff'+'800f'*4+'ffff'
COL2 = 'ffff'+'800f'*4+'ffff'+'201c'*26
然后基于这三个字符串创建的三个Framebuffer对象。
显示的时候一次调用blit方法加进去,有点类似memcpy。Framebuffer 的 blit 方法是用于将一个区域的图像数据从一个帧缓冲区复制到另一个帧缓冲区的方法。在图形编程中,blit 是 "block transfer"(块传输)的简称,通常用于在内存中进行图像数据的复制或传输操作。
在上面一旦检测到飞出画面或者碰到障碍物,就进到最后一个场景,结束画面。如果没问题就调用show接口,让屏幕正常显示继续循环。这个倒是没啥好说的。
可以看出,常规游戏的实现思路,就是基于2D图形的,以帧为单位,所有的逻辑操作都是基于2D的坐标体系。显示方面封装后就直接看做一块内存,逻辑处理完之后控制内存中数据的变化,最后把改动刷新到显示器。
改造后完整代码如下:
game.py
'''
Flappy Bird for ESP8266 modules
github.com/zelacerda/micropythonVersion 1.0
2017 - by zelacerda
'''import ssd1306
from framebuf import FrameBuffer as FB
from machine import I2C, Pin
from utime import sleep
import time
#from urequests import post# Screen dimensions
WIDTH = 128
HEIGHT = 64# Initialize pins
i2c = I2C(1, scl=Pin(7), sda=Pin(6))
oled = ssd1306.SSD1306_I2C(WIDTH, HEIGHT, i2c)
button = Pin(13, Pin.IN)# Some helper functions
def random(a,b):seed = int(time.time() * 1000) # 将当前时间转换为毫秒级别的整数# 利用种子生成伪随机数random_num = (seed * 1103515245 + 12345) % (2**31)# 将随机数映射到指定范围[a, b]return random_num % (b - a + 1) + adef to_bytearray(s):return bytearray([int('0x'+s[i:i+2]) for i in range(0,len(s),2)])def write_high_score(n):f = open('fb_high_score', 'w')f.write(str(n))f.close()def read_high_score():return 0def send_score(n):url = "http://things.ubidots.com/api/v1.6/devices/NodeMCU?token="token = "A1E-5ZY9vbCGtRiqVinrnhrQxgA4FDSBaA"url += tokenheaders = {"Content-Type": "application/json"}data = '{"flappy-bird-score": ' + str(n) + '}'#post(url, data=data, headers=headers)# Bitmap images
BIRD = '07e018f021f871ecf9ecfcfcbe7e4c81717e4082307c0f80'
COL1 = '201c'*26+'ffff'+'800f'*4+'ffff'
COL2 = 'ffff'+'800f'*4+'ffff'+'201c'*26
bird_size = (16,12)
colu_size = (16,32)# Generate sprites
bird = FB(to_bytearray(BIRD),bird_size[0],bird_size[1],3)
col1 = FB(to_bytearray(COL1),colu_size[0],colu_size[1],3)
col2 = FB(to_bytearray(COL2),colu_size[0],colu_size[1],3)class FlappyBird:def __init__(self):self.height = bird_size[1]self.y = HEIGHT // 2 - self.height // 2self.vel = -wing_powerdef move(self):self.vel += gravityself.y = int(self.y + self.vel)def flap(self):self.vel = -wing_powerdef crashed(self):y_limit = HEIGHT - self.heightreturn self.y > y_limitclass Obstacle:def __init__(self, x):self.gap = random(6+gap_size, HEIGHT-6-gap_size)self.x = xself.score = 0def scroll(self):self.x -= velocityif self.x < -colu_size[0]:self.score += 1self.x = WIDTHself.gap = random(6+gap_size, HEIGHT-6-gap_size)def collided(self, y):if self.x < bird_size[0] and \self.x > -colu_size[0] and \(self.gap - y > gap_size or y + bird_size[1] - self.gap > gap_size):return Trueelse:return Falsedef clicked():global pressedif button.value() == 1 and not pressed:pressed = Truereturn Trueelif button.value() == 0 and pressed:pressed = Falsereturn Falsedef draw():oled.fill(0)oled.blit(bird, 0, flappy_bird.y)oled.blit(col1,obstacle_1.x,obstacle_1.gap-gap_size-colu_size[1])oled.blit(col2,obstacle_1.x,obstacle_1.gap+gap_size)oled.blit(col1,obstacle_2.x,obstacle_2.gap-gap_size-colu_size[1])oled.blit(col2,obstacle_2.x,obstacle_2.gap+gap_size)oled.fill_rect(WIDTH//2 - 13, 0, 26, 9, 0)oled.text('%03d' % (obstacle_1.score + obstacle_2.score), WIDTH//2 - 12, 0)oled.show()# Game parameters
high_score = read_high_score()
gap_size = 13
velocity = 3
gravity = .8
wing_power = 4
state = 0
pressed = False# Game state functions
def splash_screen():global stateoled.fill(0)oled.blit(col2, (WIDTH-colu_size[0])//2, HEIGHT-12)oled.blit(bird, (WIDTH-bird_size[0])//2, HEIGHT-12-bird_size[1])oled.rect(0, 0, WIDTH, HEIGHT, 1)oled.text('F L A P P Y', WIDTH//2-44, 3)oled.text('B I R D', WIDTH//2-28, 13)oled.text('Record: ' + '%03d' % high_score, WIDTH//2-44, HEIGHT//2-6)oled.show()state = 1def game_waiting():global state,score,flappy_bird,obstacle_1,obstacle_2, pressedif clicked():flappy_bird = FlappyBird()obstacle_1 = Obstacle(WIDTH)obstacle_2 = Obstacle(WIDTH + (WIDTH + colu_size[0]) // 2)state = 2def game_running():global stateif clicked(): flappy_bird.flap()flappy_bird.move()if flappy_bird.crashed():flappy_bird.y = HEIGHT - flappy_bird.heightstate = 3obstacle_1.scroll()obstacle_2.scroll()if obstacle_1.collided(flappy_bird.y) or obstacle_2.collided(flappy_bird.y):state = 3draw()def game_over():global state, high_scoreoled.fill_rect(WIDTH//2-32, 10, 64, 23, 0)oled.rect(WIDTH//2-32, 10, 64, 23, 1)oled.text('G A M E', WIDTH//2-28, 13)oled.text('O V E R', WIDTH//2-28, 23)score = obstacle_1.score + obstacle_2.scoreif score > high_score:high_score = scoreoled.fill_rect(WIDTH//2-48, 37, 96, 14, 0)oled.rect(WIDTH//2-48, 37, 96, 14, 1)oled.text('New record!',WIDTH//2-44, 40)write_high_score(high_score)oled.show()try:send_score(score)except:passstate = 1def loop():while True:if state == 0: splash_screen()elif state == 1: game_waiting()elif state == 2: game_running()elif state == 3: game_over()loop()
oled驱动,ssd1306.py
# MicroPython SSD1306 OLED driver, I2C and SPI interfacesfrom micropython import const
import framebuf# register definitions
SET_CONTRAST = const(0x81)
SET_ENTIRE_ON = const(0xA4)
SET_NORM_INV = const(0xA6)
SET_DISP = const(0xAE)
SET_MEM_ADDR = const(0x20)
SET_COL_ADDR = const(0x21)
SET_PAGE_ADDR = const(0x22)
SET_DISP_START_LINE = const(0x40)
SET_SEG_REMAP = const(0xA0)
SET_MUX_RATIO = const(0xA8)
SET_COM_OUT_DIR = const(0xC0)
SET_DISP_OFFSET = const(0xD3)
SET_COM_PIN_CFG = const(0xDA)
SET_DISP_CLK_DIV = const(0xD5)
SET_PRECHARGE = const(0xD9)
SET_VCOM_DESEL = const(0xDB)
SET_CHARGE_PUMP = const(0x8D)# Subclassing FrameBuffer provides support for graphics primitives
# http://docs.micropython.org/en/latest/pyboard/library/framebuf.html
class SSD1306(framebuf.FrameBuffer):def __init__(self, width, height, external_vcc):self.width = widthself.height = heightself.external_vcc = external_vccself.pages = self.height // 8self.buffer = bytearray(self.pages * self.width)super().__init__(self.buffer, self.width, self.height, framebuf.MONO_VLSB)self.init_display()def init_display(self):for cmd in (SET_DISP | 0x00, # off# address settingSET_MEM_ADDR,0x00, # horizontal# resolution and layoutSET_DISP_START_LINE | 0x00,SET_SEG_REMAP | 0x01, # column addr 127 mapped to SEG0SET_MUX_RATIO,self.height - 1,SET_COM_OUT_DIR | 0x08, # scan from COM[N] to COM0SET_DISP_OFFSET,0x00,SET_COM_PIN_CFG,0x02 if self.width > 2 * self.height else 0x12,# timing and driving schemeSET_DISP_CLK_DIV,0x80,SET_PRECHARGE,0x22 if self.external_vcc else 0xF1,SET_VCOM_DESEL,0x30, # 0.83*Vcc# displaySET_CONTRAST,0xFF, # maximumSET_ENTIRE_ON, # output follows RAM contentsSET_NORM_INV, # not inverted# charge pumpSET_CHARGE_PUMP,0x10 if self.external_vcc else 0x14,SET_DISP | 0x01,): # onself.write_cmd(cmd)self.fill(0)self.show()def poweroff(self):self.write_cmd(SET_DISP | 0x00)def poweron(self):self.write_cmd(SET_DISP | 0x01)def contrast(self, contrast):self.write_cmd(SET_CONTRAST)self.write_cmd(contrast)def invert(self, invert):self.write_cmd(SET_NORM_INV | (invert & 1))def show(self):x0 = 0x1 = self.width - 1if self.width == 64:# displays with width of 64 pixels are shifted by 32x0 += 32x1 += 32self.write_cmd(SET_COL_ADDR)self.write_cmd(x0)self.write_cmd(x1)self.write_cmd(SET_PAGE_ADDR)self.write_cmd(0)self.write_cmd(self.pages - 1)self.write_data(self.buffer)class SSD1306_I2C(SSD1306):def __init__(self, width, height, i2c, addr=0x3C, external_vcc=False):self.i2c = i2cself.addr = addrself.temp = bytearray(2)self.write_list = [b"\x40", None] # Co=0, D/C#=1super().__init__(width, height, external_vcc)def write_cmd(self, cmd):self.temp[0] = 0x80 # Co=1, D/C#=0self.temp[1] = cmdself.i2c.writeto(self.addr, self.temp)def write_data(self, buf):self.write_list[1] = bufself.i2c.writevto(self.addr, self.write_list)class SSD1306_SPI(SSD1306):def __init__(self, width, height, spi, dc, res, cs, external_vcc=False):self.rate = 10 * 1024 * 1024dc.init(dc.OUT, value=0)res.init(res.OUT, value=0)cs.init(cs.OUT, value=1)self.spi = spiself.dc = dcself.res = resself.cs = csimport timeself.res(1)time.sleep_ms(1)self.res(0)time.sleep_ms(10)self.res(1)super().__init__(width, height, external_vcc)def write_cmd(self, cmd):self.spi.init(baudrate=self.rate, polarity=0, phase=0)self.cs(1)self.dc(0)self.cs(0)self.spi.write(bytearray([cmd]))self.cs(1)def write_data(self, buf):self.spi.init(baudrate=self.rate, polarity=0, phase=0)self.cs(1)self.dc(1)self.cs(0)self.spi.write(buf)self.cs(1)
这篇关于显示学习4(基于树莓派Pico) -- 游戏的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!