Morse电码转换器
本帖最后由 szjuliet 于 2020-12-14 22:05 编辑https://www.bilibili.com/video/BV1Ji4y157q8/
# Morse电码转换器
> 使用Scrach制作的Morse电码转换器,可以将文本转换为Morse电码,也可以将Morse电码转换为文本,还可以听音辨码,使用者根据听到的电码音频来猜电码内容。

## **学习目标**
+ 了解Morse电码
+ 掌握全局变量和局部变量的用法
+ 列表从文件中导入
+ 学习随机数的用法
+ 熟练运用列表的索引,根据索引获取列表项
## 摩尔斯电码(Morse code)
摩尔斯电码是一种时通时断的信号代码,通过不同的排列顺序来表达不同的英文字母、数字和标点符号。是由美国人艾尔菲德·维尔与萨缪尔·摩尔斯在1836年发明。
摩尔斯电码是一种早期的数字化通信形式,但是它不同于现代只使用0和1两种状态的二进制代码,它的代码包括五种:
+ 点(·):1
+ 划(-):111
+ 字符内部的停顿(在点和划之间):0
+ 字符之间的停顿:000
+ 单词之间的停顿:0000000
## **步骤1 素材准备**
a.准备26个字母的Morse电码音频。
到网站[https://morsecode.world/international/translator.html](https://morsecode.world/international/translator.html)播放26个字母的电码音频并录制分割,得到26个字母独立的音频文件。
b.准备音效文件
在“听音辨码”环节中有一个“Ready, Go!”的音效,找到音效在线播放并录制下来。
c. 准备txt文件(csv文件亦可)
+ letter.txt,以字母表的顺序存放26个英文字母,每行一个字母
+ morse.txt,以字母表的顺序存放26个英文字母的Morse电码,每行一个字母电码
+ words_alpha.txt,以字母表的顺序存放370103个单词,只包含字母,不包含其它符号,每行一个单词



## **步骤2 添加背景和角色**
### 1. 背景
背景是标题,在编辑器里制作“Morse电码转换器”标题。

### 2. 角色
+ TexttoMorse,实现文本到电码的转换功能

+ MorsetoText,实现电码到文本的转换功能

+ Guess,听音辨码。听Morse电码声音判断是何电码。

## **步骤3 程序编写**
a. 定义全局变量
在Scratch中,变量分为全局变量和局部变量两种。全局变量对所有角色都起作用,局部变量只对当前角色起作用。为了让程序结构清晰,我们仅定义3个全局变量,其余只在某个角色中使用的变量我们在角色中定义局部变量。这3个全局变量是:
+ alphabet:列表变量,按字母表顺序保存26个英文字母,从文件letters.txt中导入
+ morseCode:列表变量,按字母表顺序保存26个英文字母对应的Morse电码字符,从文件morse.txt中导入
+ words_alpha:列表变量,按字母表顺序保存的370103个英文单词,从文件words_alpha.txt中导入
因为是全局变量,所以可以在任何一个角色或背景中定义。

b. 为角色TexttoMorse编写代码
+ 局部变量
index_word:在遍历用户输入的单词时当前字母的索引,初始值为1
text_to_morse:文本最终转换的Morse电码的结果,初始值为""空字符串

+ 导入26个Morse电码的音频

+ 定义过程TexttoMorse,并添加一个输入项word

— 定义局部变量
— 遍历用户输入的所有字母,依次将每个字母对应的索引在Morse电码中的对应电码保存并播放该电码的音频。
— 循环结束后,输出转换结果。

**注:** 等待0.5秒的作用是将每个字母的Morse电码进行间隔,以便听的时候更好的区分。
+ 当角色被点击时
— 等待用户输入文本
— 将用户输入的文本作为输入项调用过程TexttoMorse

c. 为角色MorsetoText编写代码
+ 局部变量
index_line:在遍历用户输入的Morse电码时当前字符的索引,初始值为1
morse_to_text:电码最终转换的文本结果,初始值为""空字符串
singleCode:所转换的单个字母所对应的Morse电码

+ 导入26个Morse电码的音频(同前)
+ 定义过程MorsetoText,并添加一个输入项morse

— 定义局部变量
— 遍历用户输入的所有字符
如果当前字符是空格,说明上一个字母的Morse电码结束,将这个字母的Morse电码(即变量singleCode的值)添加到到变量morse_to_text中;
否则,说明当前字符仍然是某个字母Morse电码的一部分,将字符保存到变量singleCode中。
— 循环结束后,由于最后一个字符后面不再有空格,所以需要将singleCode的最后一次的值添加到变量morse_to_text中
— 输出转换结果

+ 当角色被点击时
— 等待用户输入Morse电码,不同字母的Morse电码之间以空格分隔
— 将用户输入的电码作为输入项调用过程MorsetoText

d. 为角色Guess编写代码
+ 局部变量
random_word:从列表words_alpha中随机选中的一个单词并保存到该变量中
index_word:遍历变量random_word中的所有字母时当前字母的索引,初始值为1
text_to_morse:文本最终转换的Morse电码的结果,初始值为""空字符串。此变量可选,因为最终结果无需输出。

+ 导入26个Morse电码的音频(同前)
+ 定义过程playcode,并添加一个输入项word

— 定义局部变量
— 遍历变量random_word中的所有字母,依次将每个字母对应的索引在Morse电码中的对应电码保存并播放该电码的音频。
— 循环结束后,输出转换结果。(可选)

+ 当角色被点击时
— 从列表words_alpha中随机选择一个单词并保存到变量random_word中
— 播放ReadyGo音效
— 调用过程playcode播放变量random_word中的每一个字母所对应的Morse电码音效
— 播放完毕后等待用户输入答案,答案不正确继续输入,正确则退出循环

## 思考
+ 本例只对字母进行了Morse电码的转换,如何对标点符号和数字进行转换?
+ 本例“听音辨码”中演示了对单词进行识别,如果是一个英文句子,要如何在播放时对不同单词之间进行分隔?(提示:同一字母内电码间隔一个单位,同一单词字母之间间隔3个单位,不同单词之间间隔7个单位)
页:
[1]