Skip to content

活動

Poetry generator

中等級數 | MakeCode, Python | LED 螢幕, 加速計 | 文法, 詩歌, 隨機化

步驟1:製作

它是什麼?

The poetry generator project creates random phrases that you can use in a poem, as a password or to start a story. It's nice to share especially poetic or funny phrases with your friends.  

這兩支影片為您示範了製作內容和編碼方法:

What will you learn?

You will learn about arrays, a special kind of variable. Arrays are a useful way of storing data in lists.

運作方式

  • When you shake your BBC micro:bit, a random phrase is created that consists of an adjective, noun, verb, then adverb, for example, ‘beautiful bird eats swiftly’.
  • You can either use your phrase to start a poem or alongside other phrases generated by this program to write an entire poem.
  • The program uses four arrays called ‘adjectives’, ‘nouns’, ‘verbs’, and ‘adverbs’.
  • Each array stores a list of words. Each item in an array is called an element. The elements are numbered with an index. For example, the array ‘noun’ includes three elements: element 0, bird; element 1, butterfly; and element 2, dragonfly. The indices are numbered from 0 because computers start counting at 0.
  • When you shake your micro:bit, a random number between 0 and 2 is chosen for each array. The elements for those indices are shown on the micro:bit’s LED display.

你需要的東西

  • micro:bit (或,MakeCode simulator)
  • MakeCode編輯器
  • 電池組(選配)

步驟2:編碼

1# Imports go at the top
2from microbit import *
3import random
4
5adjectives = ['beautiful', 
6           'delicate',
7           'bright']
8
9nouns = ['bird', 
10           'butterfly',
11           'dragonfly']
12
13verbs = ['eats', 
14           'flies',
15           'flutters']
16
17adverbs = ['swiftly', 
18           'silently',
19           'skillfully']
20
21while True:
22    if accelerometer.was_gesture('shake'):
23        choice = random.randint(0, len(adjectives)-1)
24        display.scroll(adjectives[choice])        
25        choice = random.randint(0, len(nouns)-1)
26        display.scroll(nouns[choice])
27        choice = random.randint(0, len(verbs)-1)
28        display.scroll(verbs[choice])
29        choice = random.randint(0, len(adverbs)-1)
30        display.scroll(adverbs[choice]) 

步驟3:進階

  • Add more adjectives, nouns, verbs, and adverbs to the program.
  • Find a way to generate more lines for your poem using other inputs such as button A or button B.
  • Can you write a program to generate a haiku?