Skip to content

Instantly share code, notes, and snippets.

@d33tah
Created April 18, 2022 11:56
Show Gist options
  • Save d33tah/45beb3beea10f4a2762d78aba924fcc4 to your computer and use it in GitHub Desktop.
Save d33tah/45beb3beea10f4a2762d78aba924fcc4 to your computer and use it in GitHub Desktop.
import pygame
import struct
import time
import math
import random
import sys
import select
FREQ = 44100
a = 30000
f = 600
wpm = 20
dit_length = 60 / (50 * wpm)
znaki = {
"A": ".-",
"B": "-...",
"C": "-.-.",
"D": "-..",
"E": ".",
"F": "..-.",
"G": "--.",
"H": "....",
"I": "..",
"J": ".---",
"K": "-.-",
"L": ".-..",
"M": "--",
"N": "-.",
"O": "---",
"P": ".--.",
"Q": "--.-",
"R": ".-.",
"S": "...",
"T": "-",
"U": "..-",
"V": "...-",
"W": ".--",
"X": "-..-",
"Y": "-.--",
"Z": "--..",
"1": ".----",
"2": "..---",
"3": "...--",
"4": "....-",
"5": ".....",
"6": "-....",
"7": "--...",
"8": "---..",
"9": "----.",
"0": "-----",
", ": "--..--",
".": ".-.-.-",
"?": "..--..",
"/": "-..-.",
"-": "-....-",
"(": "-.--.",
")": "-.--.-",
}
def zaladuj_slowa():
slowa = []
with open("/usr/share/dict/american-english") as f:
for line in f:
slowo = line.strip().upper()
if all(x for x in slowo if x in znaki):
slowa.append(slowo)
return slowa
slowa = zaladuj_slowa()
def zakoduj(slowo):
rawdata = []
laczna_dlugosc = 0
for litera in slowo:
for n, znak in enumerate(znaki[litera]):
dlugosc_dzwieku = 1 if znak == "." else 3
# nadaj znak - kropke albo kreske
num_samples = int(FREQ * dlugosc_dzwieku * dit_length)
laczna_dlugosc += num_samples
for x in range(num_samples):
t = (1 / FREQ) * x
val = int(a * math.sin(2 * math.pi * f * t))
rawdata.append(struct.pack("<h", val))
# nadaj przerwe
num_samples = int(FREQ * dit_length * 1)
laczna_dlugosc += num_samples
for x in range(num_samples):
val = int(a * math.sin(0))
rawdata.append(struct.pack("<h", val))
# koniec znaku? nadaj przerwe miedzy znakami
if n + 1 == len(znaki[litera]):
# 2, bo jedna przerwe juz nadalismy przed chwila:
num_samples = int(FREQ * dit_length * 2)
laczna_dlugosc += num_samples
for x in range(num_samples):
val = int(a * math.sin(0))
rawdata.append(struct.pack("<h", val))
return laczna_dlugosc, b"".join(rawdata)
pygame.mixer.pre_init(frequency=FREQ, size=-16, channels=1)
pygame.mixer.init()
max_dlugosc = 3
while True:
slowo = random.choice([x for x in slowa if len(x) <= max_dlugosc])
laczna_dlugosc, rawdata_bytes = zakoduj(slowo)
powtorek = 0
zle = []
while True:
powtorek += 1
pygame.mixer.Sound(rawdata_bytes).play()
time.sleep(laczna_dlugosc / FREQ)
czas_oczekiwania = (len(slowo) * 1) + 2
if select.select(
[
sys.stdin,
],
[],
[],
czas_oczekiwania,
)[0]:
odp = sys.stdin.readline().strip().upper()
else:
odp = ""
if odp == slowo:
print("Dobrze!")
break
elif odp != slowo and odp:
print("Zle.")
zle.append(odp)
elif odp == "?":
print(odp)
break
print(f"{powtorek} powtorek, {len(zle)} zlych prob")
pygame.quit()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment