AZ-Delivery
Published

Hangman - Game on ESP32 with MicroPython

This is about making the game "hangman" with a OLED display, a 4x4 keypad and much more.

IntermediateFull instructions provided2 hours205
Hangman - Game on ESP32 with MicroPython

Things used in this project

Hardware components

ESP32 NodeMCU
×1
0,96 Zoll I2C OLED Display
×1
4x4 Matrix Keypad
×1
MCP23017 Serielles Interface
×1
Battery Expansion Shield
×1
Li-Akku Typ 18650
×1
WS2812B LED Ring
×1

Software apps and online services

Thonny
µPyCraft
MicropythonFirmware
keypad.py
mcp.py
i2cbus.py
oled.py
ssd1306.py
mring.py
hangman.py

Story

Read more

Code

Code snippet #1

Plain text
 # File: hangman.py
 # Author: Jürgen Grzesina
 # Rev. 1.0
 # Stand 16.06.2021
 # ****************************************************
 # Importgeschaeft
 # ****************************************************
 import os,sys       # System- und Dateianweisungen    
 ​
 import esp          # nervige Systemmeldungen aus
 esp.osdebug(None)
 ​
 import gc           # Platz fuer Variablen schaffen
 gc.collect()
 #
 from oled import OLED
 from ssd1306 import SSD1306_I2C
 from machine import Pin,I2C
 from keypad import KEYPAD_I2C,KEYPAD
 from i2cbus import I2CBus
 from mring import MAGIC_RING
 from time import sleep
 ​
 ​
 i2c=I2C(-1,scl=Pin(21),sda=Pin(22))
 ibus=I2CBus(i2c)
 ​
 d=OLED(i2c,128,64)
 keyHwadr=0x20 # HWADR des Portexpanders fuer das 4x4-Pad
 kp=KEYPAD_I2C(ibus,keyHwadr) #  Hardware Objekt am I2C-Bus
 k=KEYPAD(kp,d=d) # hardwareunabhaengige Methoden
 ​
 mr=MAGIC_RING(neoPin=12,neoCnt=12)
 ​
 d.yOffset=4
 A="ABCDEFGHI"
 B="JKLMNOPQR"
 C="STUVWXYZ "
 ​
 s="JOGILOEWSOBERFLASCHENELFVEREIN"
 U="_"*len(s)
 sb=bytearray(s.encode("utf8"))
 Ub=bytearray(U.encode("utf8"))
 alphaLength=12
 ​
 # *************** Funktionen declarieren *******************
 def showString(q=Ub):  # q ist ein Bytearray mit den Stringcodes
     laenge=len(q)
     zeilen=laenge//alphaLength
     rest=laenge%alphaLength
     for line in range(zeilen):
         for pos in range(alphaLength):
             d.writeAt(chr(q[line*alphaLength+pos]),pos,line+3,False)
     for pos in range(rest):
         d.writeAt(chr(q[zeilen*alphaLength+pos]),pos,zeilen+3,False)
     d.show()
 ​
 def getChar(delay=0.3):
     global cursorPos
     d.cursor(cursorPos,3,y=0,cset=True,show=True)
     d.clearFT(len(A)+1,0,len(A)+1,2)
     while 1:
         d.cursor(cursorPos,3,y=0,cset=True,show=True)
         taste=k.waitForKey(timeout=0,ASCII=True)
         sleep(delay)
         if taste=="*":
             d.cursor(cursorPos,3,y=0,cset=False,show=True)
             cursorPos=(cursorPos-1)%9
         if taste=="+":
             d.cursor(cursorPos,3,y=0,cset=False,show=True)
             cursorPos=(cursorPos+1)%9
         if taste in "ABC":
             z=eval(taste)[cursorPos]
             d.writeAt(z,len(A)+1,ord(taste)-65)
             d.writeAt(" ",cursorPos,ord(taste)-65)
             return z
         if taste=="\x0d":
             d.clearAll()
             d.writeAt("GAME OVER",3,2)
             sys.exit()
 ​
 def checkChar(c=""):
     global Ub
     global punkte
     pos=[]
     if c in s:
         p=-1
         while 1:
             p=s.find(c,p+1)
             if p!=-1:
                 Ub[p]=ord(c) # gefunden und ersetzt
             else:
                 break # fertig mit c
         showString(q=Ub) # anzeige updaten
         return True
     else:
         punkte-=1
         return gallows()
         
 def initGalgen():
     n=0
     galgen=[
         "d.fill_rect(d.width-25,d.height-3,24,3,1)", # Boden
         "d.fill_rect(d.width-3,d.height//2,3,d.height//2,1)", 
         "d.fill_rect(d.width-3,0,3,d.height//2,1)", # Mast
         "d.fill_rect(d.width-25,0,24,3,1)", # Balken
         "d.line(d.width-18,2,d.width-2,18,1)", # Stuetze
         "d.fill_rect(d.width-22,0,3,15,1)", # Strick
         "d.writeAt('O',13,1,False)",  # Kopf
         "d.fill_rect(d.width-22,19,3,20,1)", # Body
         "d.line(d.width-22,18,d.width-26,33,1)", # Arm links
         "d.line(d.width-19,18,d.width-14,33,1)", # Arm rechts
         "d.line(d.width-22,37,d.width-26,50,1)", # Bein links
         "d.line(d.width-19,37,d.width-14,50,1)", # Bein rechts
         ]
     def nextPart():
         nonlocal n
         exec(galgen[n])
         d.show()
         n+=1
         if n<=11:
             return True
         else:
             return False
     return nextPart
 ​
 def initSuperWord():
     L=[]
     f=open("superwords.txt","r")
     for w in f:
         w = w.strip(" \r\n\t")
         L.append(w)
     f.close()
     numbers=[]
     #print(L)
     def findOne():
         nonlocal numbers
         guess = os.urandom(3)[2]%len(L)
         print(len(numbers))
         while guess in numbers and len(numbers)<len(L):
             guess = os.urandom(3)[2]%len(L)
         if len(numbers)<len(L):
             numbers.append(guess)
         return L[guess]
     return findOne
 ​
 # **************** Hauptprogramm **************************
 showString(Ub)
 games=0
 gesamt=0
 getSuperWord=initSuperWord()
 while 1:
     punkte=12
     d.clearAll()
     d.writeAt(A+"  A",0,0,False)
     d.writeAt(B+"  B",0,1,False)
     d.writeAt(C+"  C",0,2,True)
     cursorPos=0
     gallows=initGalgen()
     s=getSuperWord()
     print("Superword=",s)
     s=s.upper()
     U="_"*len(s)
     Ub=bytearray(U.encode("utf8"))
     showString(Ub)
     games+=1
     ergebnis=True
     while ("_" in Ub) and ergebnis==True:
         zeichen=getChar()
         print(zeichen)
         sleep(1)
         ergebnis=checkChar(zeichen)
     if ergebnis == True:
         gesamt+=punkte
         d.blinkDisplay(3,0.5,0.5)
         d.clearFT(0,0,12,2)
         d.writeAt("GEWONNEN!!!",0,0,False)
         d.writeAt("PUNKTE {}".format(punkte),0,1,False)
     else:
         d.clearFT(0,0,12,2)
         d.writeAt("NEW GAME -",0,0,False)
         d.writeAt("NEW LUCK!!",0,1,False)
         showString(q=sb)
     d.writeAt("TOTAL {}".format(gesamt),0,2)
     taste=k.waitForKey(0,ASCII=True)
     if taste=="\x0d":
         print("Game over")
         d.clearAll()
         d.writeAt("GAME OVER",3,2)
         break

Github file

https://github.com/thonny/thonny/releases/download/v3.3.10/thonny-3.3.10.exe

Github file

https://github.com/DFRobot/uPyCraft/archive/master.zip

Credits

AZ-Delivery
16 projects • 3 followers
We are "AZ-Delivery - Your Expert for Microelectronics". Visit our shop with regularly new Blogs and free E-Books.
Contact
Thanks to Jürgen Grzesina.

Comments

Please log in or sign up to comment.