aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorRatakor <contact@ratakor.com>2023-02-18 12:36:23 +0100
committerRatakor <contact@ratakor.com>2023-02-18 12:36:23 +0100
commit9a95fa24214d1134f7c9c70a5154c3d158228ea4 (patch)
tree6ad005a64c9794330a3784abfd45af704da35aa0
-rw-r--r--Assembleur.py245
-rw-r--r--Machine/Binon.py41
-rw-r--r--Machine/Exécuteur.py27
-rw-r--r--Machine/Mot.py52
-rw-r--r--Machine/Mém.py153
-rw-r--r--Machine/Ordi.py74
-rw-r--r--Machine/Proc.py58
-rw-r--r--Machine/Périph.py179
-rw-r--r--Machine/VérifBinon.py87
-rw-r--r--Machine/VérifMot.py56
-rw-r--r--Machine/VérifMém.py89
-rw-r--r--Machine/VérifOrdi.py34
-rw-r--r--Machine/VérifProc.py111
-rw-r--r--Machine/diagrammes.pdfbin0 -> 1034372 bytes
-rw-r--r--Machine/graphics.py1015
-rw-r--r--README.md1
16 files changed, 2222 insertions, 0 deletions
diff --git a/Assembleur.py b/Assembleur.py
new file mode 100644
index 0000000..da8c3fa
--- /dev/null
+++ b/Assembleur.py
@@ -0,0 +1,245 @@
+# assembleur
+
+vc = 16
+
+def traduire_A(instr):
+ # traduit une instruction du genre @nombre en le nombre avec le plus fort binon à zéro
+ # (donc nombre est compris entre 0 et 32767)
+ # par exemple @0 donnera 0000 0000 0000 0000 soit (0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0)
+ # par exemple @21 donnera 0000 0000 0001 0101 soit (1,0,1,0, 1,0,0,0, 0,0,0,0, 0,0,0,0)
+ # par exemple @32767 donnera 0111 1111 1111 1111 soit (1,1,1,1, 1,1,1,1, 1,1,1,1, 1,1,1,0)
+
+ # nombre ou symbole, @21 ou @étiquette
+ global vc
+ param = instr[1:]
+ if param.isdigit():
+ nombre = int(param)
+ else:
+ try:
+ nombre = symboles[param]
+ except KeyError:
+ nombre = vc
+ symboles[param] = nombre
+ print("Ajoute symbole " + param + " avec valeur " + str(nombre))
+ vc += 1
+
+ bin = format(nombre, '016b') # format(21) -> "0000000000010101"
+ liste = []
+ for chiffre in bin[::-1]:
+ liste.append(int(chiffre))
+ return tuple(liste)
+
+"""
+def traduire_A(instr):
+ nombre = int(instr[1;])
+ return tuple(int(chiffre) for chiffre in format(nombre, '016b')[::-1])
+"""
+dests = {
+# "" : (0,0,0),
+ "M" : (1,0,0),
+ "D" : (0,1,0),
+ "MD" : (1,1,0),
+ "A" : (0,0,1),
+ "AM" : (1,0,1),
+ "AD" : (0,1,1),
+ "AMD" : (1,1,1)
+}
+
+sauts = {
+# "" : (0,0,0),
+ "JGT" : (1,0,0),
+ "JEQ" : (0,1,0),
+ "JGE" : (1,1,0),
+ "JLT" : (0,0,1),
+ "JNE" : (1,0,1),
+ "JLE" : (0,1,1),
+ "JMP" : (1,1,1)
+}
+
+calculs = {
+ "0" : (0,1,0,1,0,1,0),
+ "1" : (1,1,1,1,1,1,0),
+ "-1" : (0,1,0,1,1,1,0),
+ "D" : (0,0,1,1,0,0,0),
+ "A" : (0,0,0,0,1,1,0),
+ "M" : (0,0,0,0,1,1,1),
+ "!D" : (1,0,1,1,0,0,0),
+ "!A" : (1,0,0,0,1,1,0),
+ "!M" : (1,0,0,0,1,1,1),
+ "-D" : (1,1,1,1,0,0,0),
+ "-A" : (1,1,0,0,1,1,0),
+ "-M" : (1,1,0,0,1,1,1),
+ "D+1" : (1,1,1,1,1,0,0),
+ "A+1" : (1,1,1,0,1,1,0),
+ "M+1" : (1,1,1,0,1,1,1),
+ "D-1" : (0,1,1,1,0,0,0),
+ "A-1" : (0,1,0,0,1,1,0),
+ "M-1" : (0,1,0,0,1,1,1),
+ "D+A" : (0,1,0,0,0,0,0),
+ "D+M" : (0,1,0,0,0,0,1),
+ "D-A" : (1,1,0,0,1,0,0),
+ "D-M" : (1,1,0,0,1,0,1),
+ "A-D" : (1,1,1,0,0,0,0),
+ "M-D" : (1,1,1,0,0,0,1),
+ "D&A" : (0,0,0,0,0,0,0),
+ "D&M" : (0,0,0,0,0,0,1),
+ "D|A" : (1,0,1,0,1,0,0),
+ "D|M" : (1,0,1,0,1,0,1)
+}
+
+symboles = {
+ "R0" : 0,
+ "R1" : 1,
+ "R2" : 2,
+ "R3" : 3,
+ "R4" : 4,
+ "R5" : 5,
+ "R6" : 6,
+ "R7" : 7,
+ "R8" : 8,
+ "R9" : 9,
+ "R10" : 10,
+ "R11" : 11,
+ "R12" : 12,
+ "R13" : 13,
+ "R14" : 14,
+ "R15" : 15
+}
+
+pc = 0
+
+def traduire_C(instr):
+ # traduit uns instruction du genre dest=calcul;saut avec dest et saut optionels
+ # donc du genre
+ # calcul
+ # dest=calcul
+ # calcul;saut
+ # dest=calcul;saut
+ # l'encodage est (111 calcul dest saut)
+
+ éléments = instr.split('=') # "D+1;JEQ" -> ("D+1;JEQ")
+ if len(éléments) == 1:
+ dest = (0,0,0)
+ reste = instr
+ else:
+ dest = dests[éléments[0]] # A -> (0,0,1)
+ reste = éléments[1]
+
+ suite = reste.split(';') # -> ("D+1","JEQ")
+ if len(suite) == 1:
+ saut = (0,0,0)
+ else:
+ saut = sauts[suite[1]]
+ reste = suite[0]
+
+ calcul = calculs[reste] # D+1 -> (1,1,1,1,1,0,0)
+
+ return saut+dest+calcul+(1,1,1)
+
+def résoudre_L(instr):
+ global pc
+ # "(étiquette)"
+ # clef & valeur
+ clef = instr[1:-1]
+ valeur = pc
+ symboles[clef] = valeur
+ print("Ajoute symbole " + clef + " avec valeur " + str(valeur)) # Ajoute symbole fin avec valeur 3
+
+def traduire(instr): # analyse sémantique
+ if instr[0] == '(':
+ return None
+ elif instr[0] == '@':
+ return traduire_A(instr)
+ else:
+ return traduire_C(instr)
+
+def extraire(ligne): # analyse lexicale
+ instr = ""
+ peutetre_commentaire = False
+
+ for lettre in ligne:
+ if lettre == '/':
+ if peutetre_commentaire:
+ break
+ else:
+ peutetre_commentaire = True
+ elif lettre == ' ' or lettre == '\n':
+ continue
+ else:
+ if peutetre_commentaire:
+ peutetre_commentaire = False
+ instr += '/'
+ instr += lettre
+
+ return instr
+
+def vérifier(instr): # analyse syntaxique
+ return instr
+
+def résoudre(instr):
+ global pc
+ if instr[0] == '(':
+ return résoudre_L(instr)
+ else:
+ pc += 1
+
+def assemble(nom_source, nom_objet):
+
+ with open(nom_source) as fichier:
+ source = fichier.readlines()
+
+ # permière passe, résolution des symboles
+ for ligne in source:
+ instr = extraire(ligne)
+ if instr:
+ résoudre(instr)
+
+ # deuxième passe, traduction des instructions
+ objet=[]
+ for ligne in source:
+ instr = extraire(ligne)
+ if instr:
+ if not vérifier(instr):
+ # erreur dans le programme source
+ exit(0)
+ code = traduire(instr)
+ if code:
+ objet.append(code)
+
+ with open(nom_objet, "w") as fichier:
+ fichier.writelines(str(code)+'\n' for code in objet)
+
+def main():
+ src, obj = input("src : "), input("obj : ")
+ assemble(src,obj)
+
+main()
+
+"""
+// second essai
+ @fin # équiv. à @7 # addr instr 0 pc (program counter)
+// instruction plus difficile
+ D=D-1;JEQ // décrémente D et saute si c'est nul # addr instr 1
+// instruction finale
+ D=0 // remet D à zéro # addr instr 2
+ @temp # addr instr 3, addr mémoire 16
+ M=D # addr instr 4
+ @temp2 # addr instr 5, addr mémoire 17
+ M=D # addr instr 6
+ @temp # addr instr 7, addr mémoire 16
+ M=D # addr instr 8
+(fin) # donc fin vaut 9
+(autrefin) # donc autrefin vaut 9
+
+======
+
+(1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0)
+(0,1,0,0,1,0,0,1,1,1,0,0,0,1,1,1)
+(0,0,0,0,1,0,0,1,0,1,0,1,0,1,1,1)
+(0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0)
+(1,0,0,0,0,0,0,0,1,1,0,0,0,1,1,1)
+(1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0)
+(1,0,0,0,0,0,0,0,1,1,0,0,0,1,1,1)
+(0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0)
+(1,0,0,0,0,0,0,0,1,1,0,0,0,1,1,1)
+"""
diff --git a/Machine/Binon.py b/Machine/Binon.py
new file mode 100644
index 0000000..92ed622
--- /dev/null
+++ b/Machine/Binon.py
@@ -0,0 +1,41 @@
+# Opérations sur binons (encodés par un entier valant 0 ou 1).
+
+# Circuit de base
+def nand(a,b):
+ return ((1,1),(1,0))[a][b]
+
+# Circuits dérivés pour logique
+def not_(a):
+ return nand(a,a)
+
+def and_(a,b):
+ return not_(nand(a,b))
+
+def or_(a,b):
+ return nand(not_(a),not_(b))
+
+def xor(a,b):
+ return or_(and_(a,not_(b)),and_(not_(a),b))
+
+def mux(sel,a,b):
+ return or_(and_(a,not_(sel)),and_(b,sel))
+
+def dmux(sel,inp):
+ return and_(not_(sel),inp),and_(sel,inp)
+
+def dmux4way(sel,inp):
+ ab, cd = dmux(sel[1],inp)
+ return dmux(sel[0],ab) + dmux(sel[0],cd)
+
+def dmux8way(sel,inp):
+ abcd, efgh = dmux(sel[2],inp)
+ return dmux4way(sel[:2],abcd) + dmux4way(sel[:2],efgh)
+
+# Circuits dérivés pour arithmétique
+def halfadder(a,b):
+ return xor(a,b), and_(a,b)
+
+def fulladder(a,b,c):
+ aplusb, r1 = halfadder(a,b)
+ aplusbplusc, r2 = halfadder(aplusb,c)
+ return aplusbplusc, or_(r1,r2)
diff --git a/Machine/Exécuteur.py b/Machine/Exécuteur.py
new file mode 100644
index 0000000..2781b27
--- /dev/null
+++ b/Machine/Exécuteur.py
@@ -0,0 +1,27 @@
+from Ordi import *
+
+def lire(nom_de_fichier):
+ with open(nom_de_fichier) as fichier:
+ contenu = tuple(tuple(int(ligne[position]) for position in range(1,1+16*3,3)) for ligne in fichier)
+ return contenu
+
+
+objet = input("Nom du programme à exécuteur ? ")
+données = input("Nom des données à charger ? ")
+
+contenu_rom = lire("..\\Programmes\\" + objet + ".mot")
+print(len(contenu_rom), "instructions")
+
+if données:
+ contenu_ram = lire("..\\Programmes\\" + données + ".mot")
+else:
+ contenu_ram = ()
+print(len(contenu_ram), "données")
+
+ordi = ordinateurIO()
+ordi.loadram(contenu_ram)
+ordi.loadrom(contenu_rom)
+
+print(ordi)
+ordi.reset(trace=0,pasàpas=0)
+print(ordi)
diff --git a/Machine/Mot.py b/Machine/Mot.py
new file mode 100644
index 0000000..35999df
--- /dev/null
+++ b/Machine/Mot.py
@@ -0,0 +1,52 @@
+from functools import reduce
+from Binon import *
+
+# Opérations sur mots (encodés par un tuple d'entiers valant 0 ou 1).
+# Remarque: les fonctions ne dépendent pas de la longueur du mot,
+# même si en pratique ce seront des mots de 16 binons.
+
+# Circuits dérivés pour logique
+def not16(A):
+ return tuple(not_(a) for a in A)
+
+def and16(A,B):
+ return tuple(and_(a,b) for a,b in zip(A,B))
+
+def or16(A,B):
+ return tuple(or_(a,b) for a,b in zip(A,B))
+
+def or16way(A):
+ return reduce(or_, A)
+
+def mux16(sel,A,B):
+ return tuple(mux(sel,a,b) for a,b in zip(A,B))
+
+def mux4way16(sel, A, B, C, D):
+ return mux16(sel[1], mux16(sel[0], A, B), mux16(sel[0], C, D))
+
+def mux8way16(sel, A, B, C, D, E, F, G, H):
+ return mux16(sel[2], mux4way16(sel[:2], A, B, C, D), mux4way16(sel[:2], E, F, G, H))
+
+# Circuits dérivés pour arithmétique
+#
+# Remarque: pour les opérations logiques, les binons d'un mot sont équivalents mais pour
+# les opérations arithmétiques, le mot représente un nombre dont les binons sont les chiffres.
+# Ils sont alors rangés du moins significatif au plus significatif de manière à ce que
+# leur place correspondent à leur puissance.
+# Par exemple: (1,0,0,0, 0,0,0,0, 1,0,0,0, 0,0,0,0) représente 257 avec 1 en position 0 et en
+# position 8, soit 2**0 + 2**8 = 1 + 256 = 257
+def add16(A,B):
+ r = 0
+ return tuple(résultat[0] for a,b in zip(A,B) if (résultat := fulladder(a,b,r), r := résultat[1]))
+
+def inc16(A):
+ r = 1
+ return tuple(résultat[0] for a in A if (résultat := halfadder(a,r), r := résultat[1]))
+
+
+##### Utilitaires #####
+def entier(A):
+ return reduce(lambda x,y: x*2+y, A[::-1])
+
+def hexa(A):
+ return f"{entier(A):0{4}X}"
diff --git a/Machine/Mém.py b/Machine/Mém.py
new file mode 100644
index 0000000..4000b4e
--- /dev/null
+++ b/Machine/Mém.py
@@ -0,0 +1,153 @@
+from Mot import *
+
+# Rétention de valeurs.
+# Il ne s'agit plus de simples fonctions mais de mécanismes qui gardent des valeurs.
+# Il faut donc utiliser des objets et donc définir les classes correspondantes.
+
+# Rétention d'un binon
+class binon:
+
+ def __init__(self):
+ self.val = 0
+
+ def __str__(self):
+ return str(self.val)
+
+ def probe(self):
+ return self.val
+
+ def set(self, load, inp):
+ self.val = mux(load, self.val, inp)
+
+# Rétention d'un mot
+class registre:
+
+ # Remarque: contrairement aux fonctions de Mot, 16 est fixé car il faut garder une donnée
+ # (et donc connaître sa taille) et non simplement faire un calcul dessus
+ TAILLE = 16 # en binons
+
+ def __init__(self):
+ # Remarque: (binon(),)*registre.TAILLE donnerait TAILLE fois le MÊME binon
+ self.binons = tuple(binon() for _ in range(registre.TAILLE))
+
+ def __str__(self):
+ return hexa(self.probe())
+
+ # Remarque: le paramètre adresse permet d'éviter un cas particulier dans l'objet ram
+ def probe(self, adresse=None):
+ return tuple(b.probe() for b in self.binons)
+
+ def set(self, load, inp, adresse=None):
+ for b,val in zip(self.binons, inp):
+ b.set(load, val)
+
+
+# Rétention d'un mot avec comportement spécial
+class compteur(registre):
+
+ def set(self, reset, load, inc, inp):
+ actuel = self.probe()
+ plus1 = inc16(actuel)
+ zero = (0,)*len(actuel)
+ super().set(or_(reset, or_(load, inc)),
+ mux16(reset,
+ mux16(load,
+ mux16(inc, actuel,
+ plus1),
+ inp),
+ zero))
+
+
+# Rétention d'un groupe de mots
+#
+# Une RAM est composée de blocs qui peuvent eux-même être des RAMs plus petites et finalement
+# de simples registres.
+# Remarque: L'adresse d'un registre est décomposée en binons d'ordre supérieur qui désignent
+# le bloc et le restant qui désigne l'adresse du registre dans le bloc.
+
+class ram:
+
+ # Nombre de blocs adressables en fonction de la taille de l'adresse en binons
+ TAILLE_ADRESSE = 3
+ NUM_BLOCS = 2**TAILLE_ADRESSE
+
+ def __init__(self, quantité): # en registres
+ # La quantité totale de registres doit pouvoir être répartie entre les blocs
+ assert quantité % ram.NUM_BLOCS == 0
+ self.taille_bloc = quantité // ram.NUM_BLOCS
+
+ # Chaque bloc est soit un registre, soit une RAM plus petite (récursion)
+ self.blocs = tuple((registre() if self.taille_bloc==1 else ram(self.taille_bloc)) for _ in range(ram.NUM_BLOCS))
+
+ def __str__(self):
+ chaîne = "$"+str(self.taille_bloc)+":\n"
+ for bloc in self.blocs:
+ chaîne += str(bloc) + " "
+ chaîne += "\n:"+str(self.taille_bloc)+"$\n"
+ return chaîne
+
+ def probe(self, adresse):
+ # Les binons supérieurs (donc en fin de tuple) permettent de sélectioner un bloc
+ # et les binons restants désignent l'adresse dans ce bloc (récursion)
+ return mux8way16(adresse[-ram.TAILLE_ADRESSE:], *(bloc.probe(adresse[:-ram.TAILLE_ADRESSE]) for bloc in self.blocs))
+
+ def set(self, load, inp, address):
+ loads = dmux8way(address[-ram.TAILLE_ADRESSE:], load)
+ for l,bloc in zip(loads, self.blocs):
+ bloc.set(l, inp, address[:-ram.TAILLE_ADRESSE])
+
+
+ ##### Utilitaires #####
+
+ # !!! REMARQUE !!!
+ # Comme indiqué en tête de Mot, toutes les fonctions 16 marchent en fait
+ # sur des mots de n'importe quelle longueur. On n'a donc pas besoin de
+ # connaître la taille de l'adresse (qui dépend de la taille de l'objet ram)
+ # pour l'incrémenter.
+
+ def store(self, contenu, adresse):
+ for x in contenu:
+ self.set(1, x, adresse)
+ adresse = inc16(adresse)
+
+ def dump(self, adresse, quantité):
+ chaîne = hexa(adresse) + ':'
+ while quantité > 0:
+ valeur = self.probe(adresse)
+ chaîne += " " + hexa(valeur)
+ adresse = inc16(adresse)
+ quantité -= 1
+ return chaîne
+
+
+###### TRICHERIE POUR PERFORMANCE ######
+# La définition récursive de ram est trop lente pour être utlisable.
+# Cette implémentation calque l'interface de la classe ram mais utilise
+# directement un tableau de registres pour éviter la récursion.
+###### L'IMPLÉMENTATION NE SUIT PAS L'ÉLECTRONIQUE MAIS SE COMPORTE PAREILLEMENT ######
+class ramfake(ram):
+
+ TAILLE = 32768 # en registres, fixée à 32K mots
+
+ def __init__(self):
+ self.registres = tuple(registre() for _ in range(ramfake.TAILLE))
+
+ def __str__(self):
+ chaîne = "$RAMFAKE:"
+ limite = 256
+ for adr in range(limite):
+ if adr % 16 == 0:
+ chaîne += "\n"+f"{adr:0{4}X}"+":"
+ chaîne += str(self.registres[adr])
+ chaîne += "\n:RAMFAKE$\n"
+ return chaîne
+
+ def probe(self, adresse):
+ adr = entier(adresse)
+ return self.registres[adr].probe() if adr < ramfake.TAILLE else (0,)*16
+
+ def set(self, load, inp, adresse):
+ adr = entier(adresse)
+ if load and adr < ramfake.TAILLE:
+ self.registres[adr].set(load, inp)
+
diff --git a/Machine/Ordi.py b/Machine/Ordi.py
new file mode 100644
index 0000000..4c94e6f
--- /dev/null
+++ b/Machine/Ordi.py
@@ -0,0 +1,74 @@
+from Mot import *
+from Mém import *
+from Proc import *
+from Périph import *
+
+
+class ordinateur:
+
+ def __init__(self):
+ self.CPU = CPU()
+ self.RAM = ramfake() #ram(32768)
+ self.ROM = ramfake() #ram(32768)
+ self.zéro = (0,)*self.CPU.D.TAILLE
+ self.adrzéro = self.zéro[:-1]
+
+ def __str__(self):
+ return "CPU:" + str(self.CPU) + \
+ "\nROM:" + self.ROM.dump(self.adrzéro, 32) + \
+ "\nRAM:" + self.RAM.dump(self.adrzéro, 32)
+
+ def _execute(self, instruction, inM, reset):
+
+ writeM, outM, addressM, pc = self.CPU.exec(instruction, inM, reset)
+ self.RAM.set(writeM, outM, addressM)
+ inM = self.RAM.probe(addressM)
+ instruction = self.ROM.probe(pc)
+ reset = 0
+ return pc, instruction, inM, reset
+
+ def reset(self, trace, pasàpas):
+
+ # inconnu et inconséquent
+ inM = self.zéro
+ instruction = self.zéro
+ reset = 1
+
+ # Remarque: la valeur de pc n'a pas à être initialisée (inconnu et inconséquent)
+ # et la boucle devrait être infinie mais une condition d'arrêt arbitraire (pc tout 1)
+ # est définie pour la simulation
+ pc = self.adrzéro
+ while pc != (1,)*len(pc):
+
+ pc, instruction, inM, reset = self._execute(instruction, inM, reset)
+
+ # Uniquement pour la simulation, ne fait pas partie de la logique du circuit
+ if trace:
+ print(self.CPU)
+ if pasàpas:
+ input("prochain pas ?")
+
+ ##### Utilitaires #####
+ def loadrom(self, programme):
+ self.ROM.store(programme, self.adrzéro)
+
+ def loadram(self, données):
+ self.RAM.store(données, self.adrzéro)
+
+
+class ordinateurIO(ordinateur):
+
+ def __init__(self):
+ super().__init__()
+ self.IO = IO()
+
+ def _execute(self, instruction, inM, reset):
+
+ writeM, outM, addressM, pc = self.CPU.exec(instruction, inM, reset)
+ RAMwriteM, RAMinM, RAMaddrM, DISPwriteM, DISPinM, DISPaddrM = chipsetIN(writeM, outM, addressM)
+ self.RAM.set(RAMwriteM, RAMinM, RAMaddrM)
+ self.IO.set(DISPwriteM, DISPinM, DISPaddrM)
+ inM = chipsetOUT(addressM, self.RAM.probe(RAMaddrM), self.IO.probe(DISPaddrM), self.IO.key())
+ instruction = self.ROM.probe(pc)
+ reset = 0
+ return pc, instruction, inM, reset
diff --git a/Machine/Proc.py b/Machine/Proc.py
new file mode 100644
index 0000000..6391afc
--- /dev/null
+++ b/Machine/Proc.py
@@ -0,0 +1,58 @@
+from Mot import *
+from Mém import *
+
+# Opérateur logique et arithmétique
+def ALU(x,y,zx,nx,zy,ny,f,no):
+ zero = (0,)*len(x)
+ x1 = mux16(zx, x, zero)
+ x2 = mux16(nx, x1, not16(x1))
+ y1 = mux16(zy, y, zero)
+ y2 = mux16(ny, y1, not16(y1))
+ xfy = mux16(f, and16(x2,y2), add16(x2,y2))
+ out = mux16(no, xfy, not16(xfy))
+ ng = out[15]
+ zr = not_(or16way(out))
+ return out, zr, ng
+
+# Cellule de traitement contenant des registres donc ce doit être une classe car elle retient des données
+class CPU:
+
+ def __init__(self):
+ self.A = registre()
+ self.D = registre()
+ self.PC = compteur()
+
+ def __str__(self):
+ return "A:"+str(self.A)+", D:"+str(self.D)+", PC:"+str(self.PC)
+
+ def exec(self, instruction, inM, reset):
+
+ jp, jz, jn, destM, destD, destA, no, f, ny, zy, nx, zx, mem, _, _, calcul = instruction
+
+ outALU = (0,)*len(inM) # inconnu mais inconséquent
+ inA = mux16(not_(calcul), outALU, instruction)
+ self.A.set(not_(calcul), inA)
+
+ x = self.D.probe()
+ y = mux16(mem, self.A.probe(), inM)
+ outALU, zr, ng = ALU(x,y,zx,nx,zy,ny,f,no)
+
+ inA = mux16(not_(calcul), outALU, instruction)
+ self.A.set(and_(calcul, destA), inA)
+ self.D.set(and_(calcul, destD), outALU)
+
+ outA = self.A.probe()
+
+ ps = and_(not_(ng), not_(zr))
+ jpos = and_(jp, ps)
+ jzer = and_(jz, zr)
+ jneg = and_(jn, ng)
+ jump = and_(calcul, or_(jneg, or_(jpos, jzer)))
+ self.PC.set(reset, jump, not_(jump), outA)
+
+ outM = outALU
+ writeM = and_(calcul, destM)
+ addressM = outA[:-1]
+ pc = self.PC.probe()[:-1]
+
+ return writeM, outM, addressM, pc
diff --git a/Machine/Périph.py b/Machine/Périph.py
new file mode 100644
index 0000000..15acbc6
--- /dev/null
+++ b/Machine/Périph.py
@@ -0,0 +1,179 @@
+from Mot import *
+
+
+def chipsetIN(writeM, inM, addrM):
+ sel = addrM[-2:]
+ RAMwriteM0, RAMwriteM1, DISPwriteM, _ = dmux4way(sel, writeM)
+ RAMwriteM = or_(RAMwriteM0, RAMwriteM1)
+ return RAMwriteM, inM, addrM, DISPwriteM, inM, addrM[:-2]
+
+def chipsetOUT(addrM, RAMoutM, DISPoutM, KBDoutM):
+ sel = addrM[-2:]
+ return mux4way16(sel, RAMoutM, RAMoutM, DISPoutM, KBDoutM)
+
+
+###### TRICHERIE CAR EN DEHORS DU DOMAINE DE SIMULATION ######
+from graphics import GraphWin
+class IO():
+
+ def __init__(self):
+ self.frame = [(0,)*16]*((512//16)*256)
+ self.window = GraphWin("Écran", 512, 256)
+ self.window.setBackground("black")
+
+ def probe(self, addressM):
+ return self.frame[entier(addressM)]
+
+ def set(self, writeM, inM, addressM):
+ if writeM == 0:
+ return
+ index = entier(addressM)
+ y = index // 32
+ xbase = (index % 32)*16
+ actuel = self.frame[index]
+ self.frame[index] = inM
+ for xdelta, (present, futur) in enumerate(zip(actuel, inM)):
+ if futur == present:
+ continue
+ elif futur == 1:
+ self.window.plot(xbase+xdelta, y, "white")
+ else:
+ self.window.plot(xbase+xdelta, y, "black")
+
+ keys = {
+ "space" : (0,0,0,0, 0,1,0,0, 0,0,0,0, 0,0,0,0),
+ "exclam" : (1,0,0,0, 0,1,0,0, 0,0,0,0, 0,0,0,0),
+ "quotedbl" : (0,1,0,0, 0,1,0,0, 0,0,0,0, 0,0,0,0),
+ #"pound" : (1,1,0,0, 0,1,0,0, 0,0,0,0, 0,0,0,0),
+ "dollar" : (0,0,1,0, 0,1,0,0, 0,0,0,0, 0,0,0,0),
+ "percent" : (1,0,1,0, 0,1,0,0, 0,0,0,0, 0,0,0,0),
+ "ampersand" : (0,1,1,0, 0,1,0,0, 0,0,0,0, 0,0,0,0),
+ "quoteright": (1,1,1,0, 0,1,0,0, 0,0,0,0, 0,0,0,0),
+ "parenleft" : (0,0,0,1, 0,1,0,0, 0,0,0,0, 0,0,0,0),
+ "parenright": (1,0,0,1, 0,1,0,0, 0,0,0,0, 0,0,0,0),
+ "asterisk" : (0,1,0,1, 0,1,0,0, 0,0,0,0, 0,0,0,0),
+ "plus" : (1,1,0,1, 0,1,0,0, 0,0,0,0, 0,0,0,0),
+ "comma" : (0,0,1,1, 0,1,0,0, 0,0,0,0, 0,0,0,0),
+ "minus" : (1,0,1,1, 0,1,0,0, 0,0,0,0, 0,0,0,0),
+ "period" : (0,1,1,1, 0,1,0,0, 0,0,0,0, 0,0,0,0),
+ "slash" : (1,1,1,1, 0,1,0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1, 1,1,1,0, 0,0,0,0, 0,0,0,0),
+
+ #"curlyleft"
+ #"bar"
+ #"curlyright"
+ #"tilde"
+
+ "Return" : (0,0,0,0, 0,0,0,1, 0,0,0,0, 0,0,0,0),
+ "BackSpace" : (1,0,0,0, 0,0,0,1, 0,0,0,0, 0,0,0,0),
+ "Left" : (0,1,0,0, 0,0,0,1, 0,0,0,0, 0,0,0,0),
+ "Up" : (1,1,0,0, 0,0,0,1, 0,0,0,0, 0,0,0,0),
+ "Right" : (0,0,1,0, 0,0,0,1, 0,0,0,0, 0,0,0,0),
+ "Down" : (1,0,1,0, 0,0,0,1, 0,0,0,0, 0,0,0,0),
+ "Home" : (0,1,1,0, 0,0,0,1, 0,0,0,0, 0,0,0,0),
+ "End" : (1,1,1,0, 0,0,0,1, 0,0,0,0, 0,0,0,0),
+ "Prior" : (0,0,0,1, 0,0,0,1, 0,0,0,0, 0,0,0,0),
+ "Next" : (1,0,0,1, 0,0,0,1, 0,0,0,0, 0,0,0,0),
+ "Insert" : (0,1,0,1, 0,0,0,1, 0,0,0,0, 0,0,0,0),
+ "Delete" : (1,1,0,1, 0,0,0,1, 0,0,0,0, 0,0,0,0),
+ "Escape" : (0,0,1,1, 0,0,0,1, 0,0,0,0, 0,0,0,0),
+ "F1" : (1,0,1,1, 0,0,0,1, 0,0,0,0, 0,0,0,0),
+ "F2" : (0,1,1,1, 0,0,0,1, 0,0,0,0, 0,0,0,0),
+ "F3" : (1,1,1,1, 0,0,0,1, 0,0,0,0, 0,0,0,0),
+ "F4" : (0,0,0,0, 1,0,0,1, 0,0,0,0, 0,0,0,0),
+ "F5" : (1,0,0,0, 1,0,0,1, 0,0,0,0, 0,0,0,0),
+ "F6" : (0,1,0,0, 1,0,0,1, 0,0,0,0, 0,0,0,0),
+ "F7" : (1,1,0,0, 1,0,0,1, 0,0,0,0, 0,0,0,0),
+ "F8" : (0,0,1,0, 1,0,0,1, 0,0,0,0, 0,0,0,0),
+ "F9" : (1,0,1,0, 1,0,0,1, 0,0,0,0, 0,0,0,0),
+ "F10" : (0,1,1,0, 1,0,0,1, 0,0,0,0, 0,0,0,0),
+ "F11" : (1,1,1,0, 1,0,0,1, 0,0,0,0, 0,0,0,0),
+ "F12" : (0,0,0,1, 1,0,0,1, 0,0,0,0, 0,0,0,0)
+ }
+
+ def key(self):
+ key = self.window.checkKey()
+ if key == "" or key not in IO.keys:
+ return (0,)*16
+ else:
+ print(key, IO.keys[key])
+ return IO.keys[key]
diff --git a/Machine/VérifBinon.py b/Machine/VérifBinon.py
new file mode 100644
index 0000000..1be5148
--- /dev/null
+++ b/Machine/VérifBinon.py
@@ -0,0 +1,87 @@
+from Binon import *
+
+# Vérification exhaustive des opérateurs de binons
+
+# Triplettes décrivant chaque opération exhaustivement
+
+NOM = 0
+FONCTION = 1
+OPÉRANDES = 2
+
+OPS= (("NAND",nand, (((0,0), 1),
+ ((0,1), 1),
+ ((1,0), 1),
+ ((1,1), 0))),
+ ("NOT",not_, (((0,), 1),
+ ((1,), 0))),
+ ("AND",and_, (((0,0), 0),
+ ((0,1), 0),
+ ((1,0), 0),
+ ((1,1), 1))),
+ ("OR", or_, (((0,0), 0),
+ ((0,1), 1),
+ ((1,0), 1),
+ ((1,1), 1))),
+ ("XOR",xor, (((0,0), 0),
+ ((0,1), 1),
+ ((1,0), 1),
+ ((1,1), 0))),
+ ("MUX",mux, (((0,0,0), 0),
+ ((0,0,1), 0),
+ ((0,1,0), 1),
+ ((0,1,1), 1),
+ ((1,0,0), 0),
+ ((1,0,1), 1),
+ ((1,1,0), 0),
+ ((1,1,1), 1))),
+ ("DMUX",dmux, (((0,0), (0,0)),
+ ((0,1), (1,0)),
+ ((1,0), (0,0)),
+ ((1,1), (0,1)))),
+ ("DMUX4WAY",dmux4way,
+ ((((0,0),0), (0,0,0,0)),
+ (((0,0),1), (1,0,0,0)),
+ (((1,0),0), (0,0,0,0)),
+ (((1,0),1), (0,1,0,0)),
+ (((0,1),0), (0,0,0,0)),
+ (((0,1),1), (0,0,1,0)),
+ (((1,1),0), (0,0,0,0)),
+ (((1,1),1), (0,0,0,1)))),
+ ("DMUX8WAY",dmux8way,
+ ((((0,0,0),0), (0,0,0,0,0,0,0,0)),
+ (((0,0,0),1), (1,0,0,0,0,0,0,0)),
+ (((1,0,0),0), (0,0,0,0,0,0,0,0)),
+ (((1,0,0),1), (0,1,0,0,0,0,0,0)),
+ (((0,1,0),0), (0,0,0,0,0,0,0,0)),
+ (((0,1,0),1), (0,0,1,0,0,0,0,0)),
+ (((1,1,0),0), (0,0,0,0,0,0,0,0)),
+ (((1,1,0),1), (0,0,0,1,0,0,0,0)),
+ (((0,0,1),0), (0,0,0,0,0,0,0,0)),
+ (((0,0,1),1), (0,0,0,0,1,0,0,0)),
+ (((1,0,1),0), (0,0,0,0,0,0,0,0)),
+ (((1,0,1),1), (0,0,0,0,0,1,0,0)),
+ (((0,1,1),0), (0,0,0,0,0,0,0,0)),
+ (((0,1,1),1), (0,0,0,0,0,0,1,0)),
+ (((1,1,1),0), (0,0,0,0,0,0,0,0)),
+ (((1,1,1),1), (0,0,0,0,0,0,0,1)))),
+ ("HALFADDER",halfadder,
+ (((0,0), (0,0)),
+ ((0,1), (1,0)),
+ ((1,0), (1,0)),
+ ((1,1), (0,1)))),
+ ("FULLADDER",fulladder,
+ (((0,0,0), (0,0)),
+ ((0,0,1), (1,0)),
+ ((0,1,0), (1,0)),
+ ((0,1,1), (0,1)),
+ ((1,0,0), (1,0)),
+ ((1,0,1), (0,1)),
+ ((1,1,0), (0,1)),
+ ((1,1,1), (1,1)))))
+
+for op in OPS:
+ print(op[NOM])
+ for opérandes,résultat in op[OPÉRANDES]:
+ r = op[FONCTION](*opérandes)
+ #print(opérandes, résultat, r)
+ assert r == résultat
diff --git a/Machine/VérifMot.py b/Machine/VérifMot.py
new file mode 100644
index 0000000..b77fbee
--- /dev/null
+++ b/Machine/VérifMot.py
@@ -0,0 +1,56 @@
+from Mot import *
+
+# Vérification partielles des opérateurs de mots
+
+# Triplettes décrivant chaque opération sur quelques exemples
+
+# Remarque: comme les fonctions de Mot ne dépendent pas de la longueur du mot,
+# les exemples sont sur 8 binons seulement.
+
+NOM = 0
+FONCTION = 1
+OPÉRANDES = 2
+
+OPS= (("NOT16",not16,
+ ((((0,0,0,0,0,0,0,0),), (1,1,1,1,1,1,1,1)),
+ (((1,1,1,1,1,1,1,1),), (0,0,0,0,0,0,0,0)),
+ (((0,0,1,1,1,0,0,1),), (1,1,0,0,0,1,1,0)))),
+ ("AND16",and16,
+ ((((0,0,0,0,0,0,0,0),(1,0,0,1,1,1,0,1)), (0,0,0,0,0,0,0,0)),
+ (((1,1,1,1,1,1,1,1),(0,0,1,0,0,1,0,0)), (0,0,1,0,0,1,0,0)),
+ (((0,0,1,1,1,0,0,1),(1,1,1,0,0,0,1,0)), (0,0,1,0,0,0,0,0)))),
+ ("OR16",or16,
+ ((((0,0,0,0,0,0,0,0),(1,0,0,1,1,1,0,1)), (1,0,0,1,1,1,0,1)),
+ (((1,1,1,1,1,1,1,1),(0,0,1,0,0,1,0,0)), (1,1,1,1,1,1,1,1)),
+ (((0,0,1,1,1,0,0,1),(1,1,1,0,0,0,1,0)), (1,1,1,1,1,0,1,1)))),
+ ("OR16WAY",or16way,
+ ((((0,0,0,0,0,0,0,0),), 0),
+ (((1,1,1,1,1,1,1,1),), 1),
+ (((0,0,1,1,1,0,0,1),), 1))),
+ ("MUX16",mux16,
+ (((1,(0,0,0,0,0,0,0,0),(1,0,0,1,1,1,0,1)), (1,0,0,1,1,1,0,1)),
+ ((0,(1,1,1,1,1,1,1,1),(0,0,1,0,0,1,0,0)), (1,1,1,1,1,1,1,1)),
+ ((1,(0,0,1,1,1,0,0,1),(1,1,1,0,0,0,1,0)), (1,1,1,0,0,0,1,0)))),
+ ("MUX4WAY16",mux4way16,
+ ((((1,0),(0,0,0,0,0,0,0,0),(1,0,0,1,1,1,0,1),(0,0,0,1,1,0,0,0),(1,0,0,1,0,1,0,1)), (1,0,0,1,1,1,0,1)),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1,0,0,1)))))
+
+for op in OPS:
+ print(op[NOM])
+ for opérandes,résultat in op[OPÉRANDES]:
+ r = op[FONCTION](*opérandes)
+ #print(opérandes, résultat, r)
+ assert r == résultat
diff --git a/Machine/VérifMém.py b/Machine/VérifMém.py
new file mode 100644
index 0000000..c2e3ad1
--- /dev/null
+++ b/Machine/VérifMém.py
@@ -0,0 +1,89 @@
+import time
+from Mém import *
+
+# Vérification partielles des mémoires sur quelques exemples
+
+# Quadruplettes décrivant quelques opérations sur chaque mémoire
+
+NOM = 0
+TYPE = 1
+TAILLE = 2
+VALEURS = 3
+
+MÉMOIRES= (("binon", binon, None, ((1, 1, None),
+ (1, 0, None),
+ (0, 1, None))),
+ ("registre", registre, None, ((1, (0,0,0,0, 1,1,1,1, 0,0,0,0, 1,1,1,1), None),
+ (1, (0,0,0,0, 1,0,0,1, 0,1,0,0, 1,1,1,0), None),
+ (0, (0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,1), None))),
+ ("mem8", ram, 8, ((1, (0,0,0,0, 1,1,1,1, 0,0,0,0, 1,1,1,1), (0,0,0)),
+ (1, (0,0,0,0, 1,0,0,1, 0,1,0,0, 1,1,1,0), (0,1,0)),
+ (1, (0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,1), (1,1,1)),
+ (0, (0,0,0,0, 1,1,1,1, 1,1,1,1, 1,1,1,1), (0,0,0)))),
+ ("mem64", ram, 64, ((1, (0,0,0,0, 1,1,1,1, 0,0,0,0, 1,1,1,1), (0,0,0, 0,0,0)),
+ (1, (0,0,0,0, 1,0,0,1, 0,1,0,0, 1,1,1,0), (0,1,0, 0,0,1)),
+ (1, (0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,1), (1,1,1, 1,0,1)),
+ (0, (0,0,0,0, 1,1,1,1, 1,1,1,1, 1,1,1,1), (0,0,0, 0,0,0)))),
+ ("mem512", ram, 512, ((1, (0,0,0,0, 1,1,1,1, 0,0,0,0, 1,1,1,1), (0,0,0, 0,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0,0, 0,0,0,0, 0,0,0,1), (1,1,1, 1,1,1, 1,1,0, 0,0,0, 0,0,0)),
+ (0, (0,0,0,0, 1,1,1,1, 1,1,1,1, 1,1,1,1), (0,0,0, 0,0,0, 0,0,0, 0,0,0, 0,0,0)))))
+
+
+for mem in MÉMOIRES:
+ print(mem[NOM])
+ taille = mem[TAILLE]
+ if taille:
+ m = mem[TYPE](taille)
+ else:
+ m = mem[TYPE]()
+ for load,valeur,adresse in mem[VALEURS]:
+ t1 = time.time()
+ if adresse:
+ exvaleur = m.probe(adresse)
+ m.set(load, valeur, adresse)
+ val = m.probe(adresse)
+ else:
+ exvaleur = m.probe()
+ m.set(load, valeur)
+ val = m.probe()
+ if load:
+ assert val == valeur
+ else:
+ assert val == exvaleur
+ exvaleur = valeur
+ t2 = time.time()
+ print(t2-t1)
+
+
+# Vérification du compteur sur quelques exemples
+print("compteur")
+pc = compteur()
+v = (1,0,0,1, 1,1,1,1, 1,0,0,1, 1,1,1,1)
+pc.set(0,1,0,v) # load
+val = pc.probe()
+assert val == v
+pc.set(1,0,0,v) # reset
+val = pc.probe()
+assert val == (0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0)
+pc.set(0,0,1,v) # inc
+val = pc.probe()
+assert val == (1,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0)
+pc.set(0,0,1,v) # inc
+val = pc.probe()
+assert val == (0,1,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0)
+pc.set(1,0,1,v) # reset&inc => reset prioritaire
+val = pc.probe()
+assert val == (0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0)
diff --git a/Machine/VérifOrdi.py b/Machine/VérifOrdi.py
new file mode 100644
index 0000000..325d85a
--- /dev/null
+++ b/Machine/VérifOrdi.py
@@ -0,0 +1,34 @@
+import time
+from Ordi import *
+
+
+
+# Vérification sur un exemple
+print("programme Add2 : RAM[2]=RAM[0]+RAM[1]")
+programme = ((0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0),
+ (0,0,0,0, 1,0,0,0, 0,0,1,1, 1,1,1,1),
+ (1,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0),
+ (0,0,0,0, 1,0,0,1, 0,0,0,0, 1,1,1,1),
+ (0,1,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0),
+ (0,0,0,1, 0,0,0,0, 1,1,0,0, 0,1,1,1),
+ (1,1,1,1, 1,1,1,1, 1,1,1,1, 1,1,1,0),
+ (1,1,1,0, 0,0,0,1, 0,1,0,1, 0,1,1,1))
+données = ((1,1,1,1, 0,0,0,0, 0,0,0,0, 0,0,0,0), (1,0,0,1, 0,0,0,0, 0,0,0,0, 0,0,0,0))
+sortie = " 000F 0009 0018 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000"
+
+for typeordi in (ordinateur, ordinateurIO):
+ print(typeordi.__name__)
+ ordi = typeordi()
+ print(ordi)
+
+ ordi.loadp(programme)
+ print(ordi)
+
+ ordi.loadd(données)
+ print(ordi)
+
+ print("c'est parti")
+ ordi.reset(trace=1,pasàpas=0)
+
+ print(ordi)
+ assert str(ordi).partition("RAM:0000:")[2] == sortie
diff --git a/Machine/VérifProc.py b/Machine/VérifProc.py
new file mode 100644
index 0000000..08ae5de
--- /dev/null
+++ b/Machine/VérifProc.py
@@ -0,0 +1,111 @@
+from Proc import *
+
+NOM = 0
+FONCTION = 1
+OPÉRANDES = 2
+
+# Vérification des commandes de l'ALU sur quelques exemples
+XY= (((0,1,1,0, 1,1,1,0, 0,0,0,0, 1,0,0,1),(0,0,1,0, 1,0,1,0, 1,0,0,1, 1,0,0,0)),
+ ((1,1,1,1, 1,1,1,1, 1,1,1,1, 1,1,1,1),(0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0)),
+ ((1,0,1,0, 1,1,1,1, 0,1,0,1, 0,0,0,0),(0,1,0,1, 0,0,0,0, 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1),
+ ((1,1,1,1, 1,1,1,1, 1,1,1,1, 1,1,1,1),0,1),
+ ((1,1,1,1, 1,1,1,1, 1,1,1,1, 1,1,1,1),0,1))),
+ ("x-y", (0,1,0,0,1,1), (((0,1,0,0, 0,1,0,0, 1,1,1,0, 1,1,1,0),0,0),
+ ((1,1,1,1, 1,1,1,1, 1,1,1,1, 1,1,1,1),0,1),
+ ((1,1,0,1, 0,1,1,1, 1,0,1,0, 1,0,0,0),0,0))),
+ ("y-x", (0,0,0,1,1,1), (((0,1,1,1, 1,0,1,1, 0,0,0,1, 0,0,0,1),0,1),
+ ((1,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0),0,0),
+ ((1,0,1,0, 1,0,0,0, 0,1,0,1, 0,1,1,1),0,1))),
+ ("x&y", (0,0,0,0,0,0), (((0,0,1,0, 1,0,1,0, 0,0,0,0, 1,0,0,0),0,0),
+ ((0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0),1,0),
+ ((0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0),1,0))),
+ ("x|y", (0,1,0,1,0,1), (((0,1,1,0, 1,1,1,0, 1,0,0,1, 1,0,0,1),0,1),
+ ((1,1,1,1, 1,1,1,1, 1,1,1,1, 1,1,1,1),0,1),
+ ((1,1,1,1, 1,1,1,1, 1,1,1,1, 1,1,1,1),0,1))))
+
+
+for cmd in CMDS:
+ print(cmd[NOM])
+ fonc = cmd[FONCTION]
+ opérandes = cmd[OPÉRANDES]
+ for (x,y),résultat in zip(XY,opérandes):
+ r = ALU(x,y,*fonc)
+ #print(x, y, résultat, r)
+ assert r == résultat
+
+
+# Vérification du CPU sur quelques exemples
+print("cpu")
+cpu = CPU()
+print(cpu)
+outM, writeM, addressM, pc = cpu.exec((0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0), (0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0), 1)
+assert pc == (0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0)
+print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0,0, 0,0,0)),
+ (0, (1,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0),(1,1,1, 1,1,1, 1,1,1, 1,1,1, 1,1,1),(1,1,1, 0,0,0, 0,0,0, 0,0,0, 0,0,0)),
+ (0, (0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0),(1,1,1, 1,1,1, 1,1,1, 1,1,1, 1,1,1),(1,1,1, 1,1,1, 1,1,1, 1,1,1, 1,1,1)))
+
+for instruction,sortie in zip(programme,sorties):
+ #print("__________________________")
+ #print("instruction:", instruction)
+ writeM, outM, addressM, pc = cpu.exec(instruction, (1,1,1,1, 0,0,0,0, 0,0,0,0, 0,0,0,0), 0)
+ #print("outM:", outM, "writeM:", writeM, "addressM:", addressM, "PC:", pc)
+ assert (writeM, outM, addressM, pc) == sortie
+ print(cpu)
+ #print(ram)
diff --git a/Machine/diagrammes.pdf b/Machine/diagrammes.pdf
new file mode 100644
index 0000000..aef09a6
--- /dev/null
+++ b/Machine/diagrammes.pdf
Binary files differ
diff --git a/Machine/graphics.py b/Machine/graphics.py
new file mode 100644
index 0000000..44fe248
--- /dev/null
+++ b/Machine/graphics.py
@@ -0,0 +1,1015 @@
+# graphics.py
+"""Simple object oriented graphics library
+
+The library is designed to make it very easy for novice programmers to
+experiment with computer graphics in an object oriented fashion. It is
+written by John Zelle for use with the book "Python Programming: An
+Introduction to Computer Science" (Franklin, Beedle & Associates).
+
+LICENSE: This is open-source software released under the terms of the
+GPL (http://www.gnu.org/licenses/gpl.html).
+
+PLATFORMS: The package is a wrapper around Tkinter and should run on
+any platform where Tkinter is available.
+
+INSTALLATION: Put this file somewhere where Python can see it.
+
+OVERVIEW: There are two kinds of objects in the library. The GraphWin
+class implements a window where drawing can be done and various
+GraphicsObjects are provided that can be drawn into a GraphWin. As a
+simple example, here is a complete program to draw a circle of radius
+10 centered in a 100x100 window:
+
+--------------------------------------------------------------------
+from graphics import *
+
+def main():
+ win = GraphWin("My Circle", 100, 100)
+ c = Circle(Point(50,50), 10)
+ c.draw(win)
+ win.getMouse() # Pause to view result
+ win.close() # Close window when done
+
+main()
+--------------------------------------------------------------------
+GraphWin objects support coordinate transformation through the
+setCoords method and mouse and keyboard interaction methods.
+
+The library provides the following graphical objects:
+ Point
+ Line
+ Circle
+ Oval
+ Rectangle
+ Polygon
+ Text
+ Entry (for text-based input)
+ Image
+
+Various attributes of graphical objects can be set such as
+outline-color, fill-color and line-width. Graphical objects also
+support moving and hiding for animation effects.
+
+The library also provides a very simple class for pixel-based image
+manipulation, Pixmap. A pixmap can be loaded from a file and displayed
+using an Image object. Both getPixel and setPixel methods are provided
+for manipulating the image.
+
+DOCUMENTATION: For complete documentation, see Chapter 4 of "Python
+Programming: An Introduction to Computer Science" by John Zelle,
+published by Franklin, Beedle & Associates. Also see
+http://mcsp.wartburg.edu/zelle/python for a quick reference"""
+
+__version__ = "5.0"
+
+# Version 5 8/26/2016
+# * update at bottom to fix MacOS issue causing askopenfile() to hang
+# * update takes an optional parameter specifying update rate
+# * Entry objects get focus when drawn
+# * __repr_ for all objects
+# * fixed offset problem in window, made canvas borderless
+
+# Version 4.3 4/25/2014
+# * Fixed Image getPixel to work with Python 3.4, TK 8.6 (tuple type handling)
+# * Added interactive keyboard input (getKey and checkKey) to GraphWin
+# * Modified setCoords to cause redraw of current objects, thus
+# changing the view. This supports scrolling around via setCoords.
+#
+# Version 4.2 5/26/2011
+# * Modified Image to allow multiple undraws like other GraphicsObjects
+# Version 4.1 12/29/2009
+# * Merged Pixmap and Image class. Old Pixmap removed, use Image.
+# Version 4.0.1 10/08/2009
+# * Modified the autoflush on GraphWin to default to True
+# * Autoflush check on close, setBackground
+# * Fixed getMouse to flush pending clicks at entry
+# Version 4.0 08/2009
+# * Reverted to non-threaded version. The advantages (robustness,
+# efficiency, ability to use with other Tk code, etc.) outweigh
+# the disadvantage that interactive use with IDLE is slightly more
+# cumbersome.
+# * Modified to run in either Python 2.x or 3.x (same file).
+# * Added Image.getPixmap()
+# * Added update() -- stand alone function to cause any pending
+# graphics changes to display.
+#
+# Version 3.4 10/16/07
+# Fixed GraphicsError to avoid "exploded" error messages.
+# Version 3.3 8/8/06
+# Added checkMouse method to GraphWin
+# Version 3.2.3
+# Fixed error in Polygon init spotted by Andrew Harrington
+# Fixed improper threading in Image constructor
+# Version 3.2.2 5/30/05
+# Cleaned up handling of exceptions in Tk thread. The graphics package
+# now raises an exception if attempt is made to communicate with
+# a dead Tk thread.
+# Version 3.2.1 5/22/05
+# Added shutdown function for tk thread to eliminate race-condition
+# error "chatter" when main thread terminates
+# Renamed various private globals with _
+# Version 3.2 5/4/05
+# Added Pixmap object for simple image manipulation.
+# Version 3.1 4/13/05
+# Improved the Tk thread communication so that most Tk calls
+# do not have to wait for synchonization with the Tk thread.
+# (see _tkCall and _tkExec)
+# Version 3.0 12/30/04
+# Implemented Tk event loop in separate thread. Should now work
+# interactively with IDLE. Undocumented autoflush feature is
+# no longer necessary. Its default is now False (off). It may
+# be removed in a future version.
+# Better handling of errors regarding operations on windows that
+# have been closed.
+# Addition of an isClosed method to GraphWindow class.
+
+# Version 2.2 8/26/04
+# Fixed cloning bug reported by Joseph Oldham.
+# Now implements deep copy of config info.
+# Version 2.1 1/15/04
+# Added autoflush option to GraphWin. When True (default) updates on
+# the window are done after each action. This makes some graphics
+# intensive programs sluggish. Turning off autoflush causes updates
+# to happen during idle periods or when flush is called.
+# Version 2.0
+# Updated Documentation
+# Made Polygon accept a list of Points in constructor
+# Made all drawing functions call TK update for easier animations
+# and to make the overall package work better with
+# Python 2.3 and IDLE 1.0 under Windows (still some issues).
+# Removed vestigial turtle graphics.
+# Added ability to configure font for Entry objects (analogous to Text)
+# Added setTextColor for Text as an alias of setFill
+# Changed to class-style exceptions
+# Fixed cloning of Text objects
+
+# Version 1.6
+# Fixed Entry so StringVar uses _root as master, solves weird
+# interaction with shell in Idle
+# Fixed bug in setCoords. X and Y coordinates can increase in
+# "non-intuitive" direction.
+# Tweaked wm_protocol so window is not resizable and kill box closes.
+
+# Version 1.5
+# Fixed bug in Entry. Can now define entry before creating a
+# GraphWin. All GraphWins are now toplevel windows and share
+# a fixed root (called _root).
+
+# Version 1.4
+# Fixed Garbage collection of Tkinter images bug.
+# Added ability to set text atttributes.
+# Added Entry boxes.
+
+import time, os, sys
+
+try: # import as appropriate for 2.x vs. 3.x
+ import tkinter as tk
+except:
+ import Tkinter as tk
+
+
+##########################################################################
+# Module Exceptions
+
+class GraphicsError(Exception):
+ """Generic error class for graphics module exceptions."""
+ pass
+
+OBJ_ALREADY_DRAWN = "Object currently drawn"
+UNSUPPORTED_METHOD = "Object doesn't support operation"
+BAD_OPTION = "Illegal option value"
+
+##########################################################################
+# global variables and funtions
+
+_root = tk.Tk()
+_root.withdraw()
+
+_update_lasttime = time.time()
+
+def update(rate=None):
+ global _update_lasttime
+ if rate:
+ now = time.time()
+ pauseLength = 1/rate-(now-_update_lasttime)
+ if pauseLength > 0:
+ time.sleep(pauseLength)
+ _update_lasttime = now + pauseLength
+ else:
+ _update_lasttime = now
+
+ _root.update()
+
+############################################################################
+# Graphics classes start here
+
+class GraphWin(tk.Canvas):
+
+ """A GraphWin is a toplevel window for displaying graphics."""
+
+ def __init__(self, title="Graphics Window",
+ width=200, height=200, autoflush=True):
+ assert type(title) == type(""), "Title must be a string"
+ master = tk.Toplevel(_root)
+ master.protocol("WM_DELETE_WINDOW", self.close)
+ tk.Canvas.__init__(self, master, width=width, height=height,
+ highlightthickness=0, bd=0)
+ self.master.title(title)
+ self.pack()
+ master.resizable(0,0)
+ self.foreground = "black"
+ self.items = []
+ self.mouseX = None
+ self.mouseY = None
+ self.bind("<Button-1>", self._onClick)
+ self.bind_all("<Key>", self._onKey)
+ self.height = int(height)
+ self.width = int(width)
+ self.autoflush = autoflush
+ self._mouseCallback = None
+ self.trans = None
+ self.closed = False
+ master.lift()
+ self.lastKey = ""
+ if autoflush: _root.update()
+
+ def __repr__(self):
+ if self.isClosed():
+ return "<Closed GraphWin>"
+ else:
+ return "GraphWin('{}', {}, {})".format(self.master.title(),
+ self.getWidth(),
+ self.getHeight())
+
+ def __str__(self):
+ return repr(self)
+
+ def __checkOpen(self):
+ if self.closed:
+ raise GraphicsError("window is closed")
+
+ def _onKey(self, evnt):
+ self.lastKey = evnt.keysym
+
+
+ def setBackground(self, color):
+ """Set background color of the window"""
+ self.__checkOpen()
+ self.config(bg=color)
+ self.__autoflush()
+
+ def setCoords(self, x1, y1, x2, y2):
+ """Set coordinates of window to run from (x1,y1) in the
+ lower-left corner to (x2,y2) in the upper-right corner."""
+ self.trans = Transform(self.width, self.height, x1, y1, x2, y2)
+ self.redraw()
+
+ def close(self):
+ """Close the window"""
+
+ if self.closed: return
+ self.closed = True
+ self.master.destroy()
+ self.__autoflush()
+
+
+ def isClosed(self):
+ return self.closed
+
+
+ def isOpen(self):
+ return not self.closed
+
+
+ def __autoflush(self):
+ if self.autoflush:
+ _root.update()
+
+
+ def plot(self, x, y, color="black"):
+ """Set pixel (x,y) to the given color"""
+ self.__checkOpen()
+ xs,ys = self.toScreen(x,y)
+ self.create_line(xs,ys,xs+1,ys, fill=color)
+ self.__autoflush()
+
+ def plotPixel(self, x, y, color="black"):
+ """Set pixel raw (independent of window coordinates) pixel
+ (x,y) to color"""
+ self.__checkOpen()
+ self.create_line(x,y,x+1,y, fill=color)
+ self.__autoflush()
+
+ def flush(self):
+ """Update drawing to the window"""
+ self.__checkOpen()
+ self.update_idletasks()
+
+ def getMouse(self):
+ """Wait for mouse click and return Point object representing
+ the click"""
+ self.update() # flush any prior clicks
+ self.mouseX = None
+ self.mouseY = None
+ while self.mouseX == None or self.mouseY == None:
+ self.update()
+ if self.isClosed(): raise GraphicsError("getMouse in closed window")
+ time.sleep(.1) # give up thread
+ x,y = self.toWorld(self.mouseX, self.mouseY)
+ self.mouseX = None
+ self.mouseY = None
+ return Point(x,y)
+
+ def checkMouse(self):
+ """Return last mouse click or None if mouse has
+ not been clicked since last call"""
+ if self.isClosed():
+ raise GraphicsError("checkMouse in closed window")
+ self.update()
+ if self.mouseX != None and self.mouseY != None:
+ x,y = self.toWorld(self.mouseX, self.mouseY)
+ self.mouseX = None
+ self.mouseY = None
+ return Point(x,y)
+ else:
+ return None
+
+ def getKey(self):
+ """Wait for user to press a key and return it as a string."""
+ self.lastKey = ""
+ while self.lastKey == "":
+ self.update()
+ if self.isClosed(): raise GraphicsError("getKey in closed window")
+ time.sleep(.1) # give up thread
+
+ key = self.lastKey
+ self.lastKey = ""
+ return key
+
+ def checkKey(self):
+ """Return last key pressed or None if no key pressed since last call"""
+ if self.isClosed():
+ raise GraphicsError("checkKey in closed window")
+ self.update()
+ key = self.lastKey
+ self.lastKey = ""
+ return key
+
+ def getHeight(self):
+ """Return the height of the window"""
+ return self.height
+
+ def getWidth(self):
+ """Return the width of the window"""
+ return self.width
+
+ def toScreen(self, x, y):
+ trans = self.trans
+ if trans:
+ return self.trans.screen(x,y)
+ else:
+ return x,y
+
+ def toWorld(self, x, y):
+ trans = self.trans
+ if trans:
+ return self.trans.world(x,y)
+ else:
+ return x,y
+
+ def setMouseHandler(self, func):
+ self._mouseCallback = func
+
+ def _onClick(self, e):
+ self.mouseX = e.x
+ self.mouseY = e.y
+ if self._mouseCallback:
+ self._mouseCallback(Point(e.x, e.y))
+
+ def addItem(self, item):
+ self.items.append(item)
+
+ def delItem(self, item):
+ self.items.remove(item)
+
+ def redraw(self):
+ for item in self.items[:]:
+ item.undraw()
+ item.draw(self)
+ self.update()
+
+
+class Transform:
+
+ """Internal class for 2-D coordinate transformations"""
+
+ def __init__(self, w, h, xlow, ylow, xhigh, yhigh):
+ # w, h are width and height of window
+ # (xlow,ylow) coordinates of lower-left [raw (0,h-1)]
+ # (xhigh,yhigh) coordinates of upper-right [raw (w-1,0)]
+ xspan = (xhigh-xlow)
+ yspan = (yhigh-ylow)
+ self.xbase = xlow
+ self.ybase = yhigh
+ self.xscale = xspan/float(w-1)
+ self.yscale = yspan/float(h-1)
+
+ def screen(self,x,y):
+ # Returns x,y in screen (actually window) coordinates
+ xs = (x-self.xbase) / self.xscale
+ ys = (self.ybase-y) / self.yscale
+ return int(xs+0.5),int(ys+0.5)
+
+ def world(self,xs,ys):
+ # Returns xs,ys in world coordinates
+ x = xs*self.xscale + self.xbase
+ y = self.ybase - ys*self.yscale
+ return x,y
+
+
+# Default values for various item configuration options. Only a subset of
+# keys may be present in the configuration dictionary for a given item
+DEFAULT_CONFIG = {"fill":"",
+ "outline":"black",
+ "width":"1",
+ "arrow":"none",
+ "text":"",
+ "justify":"center",
+ "font": ("helvetica", 12, "normal")}
+
+class GraphicsObject:
+
+ """Generic base class for all of the drawable objects"""
+ # A subclass of GraphicsObject should override _draw and
+ # and _move methods.
+
+ def __init__(self, options):
+ # options is a list of strings indicating which options are
+ # legal for this object.
+
+ # When an object is drawn, canvas is set to the GraphWin(canvas)
+ # object where it is drawn and id is the TK identifier of the
+ # drawn shape.
+ self.canvas = None
+ self.id = None
+
+ # config is the dictionary of configuration options for the widget.
+ config = {}
+ for option in options:
+ config[option] = DEFAULT_CONFIG[option]
+ self.config = config
+
+ def setFill(self, color):
+ """Set interior color to color"""
+ self._reconfig("fill", color)
+
+ def setOutline(self, color):
+ """Set outline color to color"""
+ self._reconfig("outline", color)
+
+ def setWidth(self, width):
+ """Set line weight to width"""
+ self._reconfig("width", width)
+
+ def draw(self, graphwin):
+
+ """Draw the object in graphwin, which should be a GraphWin
+ object. A GraphicsObject may only be drawn into one
+ window. Raises an error if attempt made to draw an object that
+ is already visible."""
+
+ if self.canvas and not self.canvas.isClosed(): raise GraphicsError(OBJ_ALREADY_DRAWN)
+ if graphwin.isClosed(): raise GraphicsError("Can't draw to closed window")
+ self.canvas = graphwin
+ self.id = self._draw(graphwin, self.config)
+ graphwin.addItem(self)
+ if graphwin.autoflush:
+ _root.update()
+ return self
+
+
+ def undraw(self):
+
+ """Undraw the object (i.e. hide it). Returns silently if the
+ object is not currently drawn."""
+
+ if not self.canvas: return
+ if not self.canvas.isClosed():
+ self.canvas.delete(self.id)
+ self.canvas.delItem(self)
+ if self.canvas.autoflush:
+ _root.update()
+ self.canvas = None
+ self.id = None
+
+
+ def move(self, dx, dy):
+
+ """move object dx units in x direction and dy units in y
+ direction"""
+
+ self._move(dx,dy)
+ canvas = self.canvas
+ if canvas and not canvas.isClosed():
+ trans = canvas.trans
+ if trans:
+ x = dx/ trans.xscale
+ y = -dy / trans.yscale
+ else:
+ x = dx
+ y = dy
+ self.canvas.move(self.id, x, y)
+ if canvas.autoflush:
+ _root.update()
+
+ def _reconfig(self, option, setting):
+ # Internal method for changing configuration of the object
+ # Raises an error if the option does not exist in the config
+ # dictionary for this object
+ if option not in self.config:
+ raise GraphicsError(UNSUPPORTED_METHOD)
+ options = self.config
+ options[option] = setting
+ if self.canvas and not self.canvas.isClosed():
+ self.canvas.itemconfig(self.id, options)
+ if self.canvas.autoflush:
+ _root.update()
+
+
+ def _draw(self, canvas, options):
+ """draws appropriate figure on canvas with options provided
+ Returns Tk id of item drawn"""
+ pass # must override in subclass
+
+
+ def _move(self, dx, dy):
+ """updates internal state of object to move it dx,dy units"""
+ pass # must override in subclass
+
+
+class Point(GraphicsObject):
+ def __init__(self, x, y):
+ GraphicsObject.__init__(self, ["outline", "fill"])
+ self.setFill = self.setOutline
+ self.x = float(x)
+ self.y = float(y)
+
+ def __repr__(self):
+ return "Point({}, {})".format(self.x, self.y)
+
+ def _draw(self, canvas, options):
+ x,y = canvas.toScreen(self.x,self.y)
+ return canvas.create_rectangle(x,y,x+1,y+1,options)
+
+ def _move(self, dx, dy):
+ self.x = self.x + dx
+ self.y = self.y + dy
+
+ def clone(self):
+ other = Point(self.x,self.y)
+ other.config = self.config.copy()
+ return other
+
+ def getX(self): return self.x
+ def getY(self): return self.y
+
+class _BBox(GraphicsObject):
+ # Internal base class for objects represented by bounding box
+ # (opposite corners) Line segment is a degenerate case.
+
+ def __init__(self, p1, p2, options=["outline","width","fill"]):
+ GraphicsObject.__init__(self, options)
+ self.p1 = p1.clone()
+ self.p2 = p2.clone()
+
+ def _move(self, dx, dy):
+ self.p1.x = self.p1.x + dx
+ self.p1.y = self.p1.y + dy
+ self.p2.x = self.p2.x + dx
+ self.p2.y = self.p2.y + dy
+
+ def getP1(self): return self.p1.clone()
+
+ def getP2(self): return self.p2.clone()
+
+ def getCenter(self):
+ p1 = self.p1
+ p2 = self.p2
+ return Point((p1.x+p2.x)/2.0, (p1.y+p2.y)/2.0)
+
+
+class Rectangle(_BBox):
+
+ def __init__(self, p1, p2):
+ _BBox.__init__(self, p1, p2)
+
+ def __repr__(self):
+ return "Rectangle({}, {})".format(str(self.p1), str(self.p2))
+
+ def _draw(self, canvas, options):
+ p1 = self.p1
+ p2 = self.p2
+ x1,y1 = canvas.toScreen(p1.x,p1.y)
+ x2,y2 = canvas.toScreen(p2.x,p2.y)
+ return canvas.create_rectangle(x1,y1,x2,y2,options)
+
+ def clone(self):
+ other = Rectangle(self.p1, self.p2)
+ other.config = self.config.copy()
+ return other
+
+
+class Oval(_BBox):
+
+ def __init__(self, p1, p2):
+ _BBox.__init__(self, p1, p2)
+
+ def __repr__(self):
+ return "Oval({}, {})".format(str(self.p1), str(self.p2))
+
+
+ def clone(self):
+ other = Oval(self.p1, self.p2)
+ other.config = self.config.copy()
+ return other
+
+ def _draw(self, canvas, options):
+ p1 = self.p1
+ p2 = self.p2
+ x1,y1 = canvas.toScreen(p1.x,p1.y)
+ x2,y2 = canvas.toScreen(p2.x,p2.y)
+ return canvas.create_oval(x1,y1,x2,y2,options)
+
+class Circle(Oval):
+
+ def __init__(self, center, radius):
+ p1 = Point(center.x-radius, center.y-radius)
+ p2 = Point(center.x+radius, center.y+radius)
+ Oval.__init__(self, p1, p2)
+ self.radius = radius
+
+ def __repr__(self):
+ return "Circle({}, {})".format(str(self.getCenter()), str(self.radius))
+
+ def clone(self):
+ other = Circle(self.getCenter(), self.radius)
+ other.config = self.config.copy()
+ return other
+
+ def getRadius(self):
+ return self.radius
+
+
+class Line(_BBox):
+
+ def __init__(self, p1, p2):
+ _BBox.__init__(self, p1, p2, ["arrow","fill","width"])
+ self.setFill(DEFAULT_CONFIG['outline'])
+ self.setOutline = self.setFill
+
+ def __repr__(self):
+ return "Line({}, {})".format(str(self.p1), str(self.p2))
+
+ def clone(self):
+ other = Line(self.p1, self.p2)
+ other.config = self.config.copy()
+ return other
+
+ def _draw(self, canvas, options):
+ p1 = self.p1
+ p2 = self.p2
+ x1,y1 = canvas.toScreen(p1.x,p1.y)
+ x2,y2 = canvas.toScreen(p2.x,p2.y)
+ return canvas.create_line(x1,y1,x2,y2,options)
+
+ def setArrow(self, option):
+ if not option in ["first","last","both","none"]:
+ raise GraphicsError(BAD_OPTION)
+ self._reconfig("arrow", option)
+
+
+class Polygon(GraphicsObject):
+
+ def __init__(self, *points):
+ # if points passed as a list, extract it
+ if len(points) == 1 and type(points[0]) == type([]):
+ points = points[0]
+ self.points = list(map(Point.clone, points))
+ GraphicsObject.__init__(self, ["outline", "width", "fill"])
+
+ def __repr__(self):
+ return "Polygon"+str(tuple(p for p in self.points))
+
+ def clone(self):
+ other = Polygon(*self.points)
+ other.config = self.config.copy()
+ return other
+
+ def getPoints(self):
+ return list(map(Point.clone, self.points))
+
+ def _move(self, dx, dy):
+ for p in self.points:
+ p.move(dx,dy)
+
+ def _draw(self, canvas, options):
+ args = [canvas]
+ for p in self.points:
+ x,y = canvas.toScreen(p.x,p.y)
+ args.append(x)
+ args.append(y)
+ args.append(options)
+ return GraphWin.create_polygon(*args)
+
+class Text(GraphicsObject):
+
+ def __init__(self, p, text):
+ GraphicsObject.__init__(self, ["justify","fill","text","font"])
+ self.setText(text)
+ self.anchor = p.clone()
+ self.setFill(DEFAULT_CONFIG['outline'])
+ self.setOutline = self.setFill
+
+ def __repr__(self):
+ return "Text({}, '{}')".format(self.anchor, self.getText())
+
+ def _draw(self, canvas, options):
+ p = self.anchor
+ x,y = canvas.toScreen(p.x,p.y)
+ return canvas.create_text(x,y,options)
+
+ def _move(self, dx, dy):
+ self.anchor.move(dx,dy)
+
+ def clone(self):
+ other = Text(self.anchor, self.config['text'])
+ other.config = self.config.copy()
+ return other
+
+ def setText(self,text):
+ self._reconfig("text", text)
+
+ def getText(self):
+ return self.config["text"]
+
+ def getAnchor(self):
+ return self.anchor.clone()
+
+ def setFace(self, face):
+ if face in ['helvetica','arial','courier','times roman']:
+ f,s,b = self.config['font']
+ self._reconfig("font",(face,s,b))
+ else:
+ raise GraphicsError(BAD_OPTION)
+
+ def setSize(self, size):
+ if 5 <= size <= 36:
+ f,s,b = self.config['font']
+ self._reconfig("font", (f,size,b))
+ else:
+ raise GraphicsError(BAD_OPTION)
+
+ def setStyle(self, style):
+ if style in ['bold','normal','italic', 'bold italic']:
+ f,s,b = self.config['font']
+ self._reconfig("font", (f,s,style))
+ else:
+ raise GraphicsError(BAD_OPTION)
+
+ def setTextColor(self, color):
+ self.setFill(color)
+
+
+class Entry(GraphicsObject):
+
+ def __init__(self, p, width):
+ GraphicsObject.__init__(self, [])
+ self.anchor = p.clone()
+ #print self.anchor
+ self.width = width
+ self.text = tk.StringVar(_root)
+ self.text.set("")
+ self.fill = "gray"
+ self.color = "black"
+ self.font = DEFAULT_CONFIG['font']
+ self.entry = None
+
+ def __repr__(self):
+ return "Entry({}, {})".format(self.anchor, self.width)
+
+ def _draw(self, canvas, options):
+ p = self.anchor
+ x,y = canvas.toScreen(p.x,p.y)
+ frm = tk.Frame(canvas.master)
+ self.entry = tk.Entry(frm,
+ width=self.width,
+ textvariable=self.text,
+ bg = self.fill,
+ fg = self.color,
+ font=self.font)
+ self.entry.pack()
+ #self.setFill(self.fill)
+ self.entry.focus_set()
+ return canvas.create_window(x,y,window=frm)
+
+ def getText(self):
+ return self.text.get()
+
+ def _move(self, dx, dy):
+ self.anchor.move(dx,dy)
+
+ def getAnchor(self):
+ return self.anchor.clone()
+
+ def clone(self):
+ other = Entry(self.anchor, self.width)
+ other.config = self.config.copy()
+ other.text = tk.StringVar()
+ other.text.set(self.text.get())
+ other.fill = self.fill
+ return other
+
+ def setText(self, t):
+ self.text.set(t)
+
+
+ def setFill(self, color):
+ self.fill = color
+ if self.entry:
+ self.entry.config(bg=color)
+
+
+ def _setFontComponent(self, which, value):
+ font = list(self.font)
+ font[which] = value
+ self.font = tuple(font)
+ if self.entry:
+ self.entry.config(font=self.font)
+
+
+ def setFace(self, face):
+ if face in ['helvetica','arial','courier','times roman']:
+ self._setFontComponent(0, face)
+ else:
+ raise GraphicsError(BAD_OPTION)
+
+ def setSize(self, size):
+ if 5 <= size <= 36:
+ self._setFontComponent(1,size)
+ else:
+ raise GraphicsError(BAD_OPTION)
+
+ def setStyle(self, style):
+ if style in ['bold','normal','italic', 'bold italic']:
+ self._setFontComponent(2,style)
+ else:
+ raise GraphicsError(BAD_OPTION)
+
+ def setTextColor(self, color):
+ self.color=color
+ if self.entry:
+ self.entry.config(fg=color)
+
+
+class Image(GraphicsObject):
+
+ idCount = 0
+ imageCache = {} # tk photoimages go here to avoid GC while drawn
+
+ def __init__(self, p, *pixmap):
+ GraphicsObject.__init__(self, [])
+ self.anchor = p.clone()
+ self.imageId = Image.idCount
+ Image.idCount = Image.idCount + 1
+ if len(pixmap) == 1: # file name provided
+ self.img = tk.PhotoImage(file=pixmap[0], master=_root)
+ else: # width and height provided
+ width, height = pixmap
+ self.img = tk.PhotoImage(master=_root, width=width, height=height)
+
+ def __repr__(self):
+ return "Image({}, {}, {})".format(self.anchor, self.getWidth(), self.getHeight())
+
+ def _draw(self, canvas, options):
+ p = self.anchor
+ x,y = canvas.toScreen(p.x,p.y)
+ self.imageCache[self.imageId] = self.img # save a reference
+ return canvas.create_image(x,y,image=self.img)
+
+ def _move(self, dx, dy):
+ self.anchor.move(dx,dy)
+
+ def undraw(self):
+ try:
+ del self.imageCache[self.imageId] # allow gc of tk photoimage
+ except KeyError:
+ pass
+ GraphicsObject.undraw(self)
+
+ def getAnchor(self):
+ return self.anchor.clone()
+
+ def clone(self):
+ other = Image(Point(0,0), 0, 0)
+ other.img = self.img.copy()
+ other.anchor = self.anchor.clone()
+ other.config = self.config.copy()
+ return other
+
+ def getWidth(self):
+ """Returns the width of the image in pixels"""
+ return self.img.width()
+
+ def getHeight(self):
+ """Returns the height of the image in pixels"""
+ return self.img.height()
+
+ def getPixel(self, x, y):
+ """Returns a list [r,g,b] with the RGB color values for pixel (x,y)
+ r,g,b are in range(256)
+
+ """
+
+ value = self.img.get(x,y)
+ if type(value) == type(0):
+ return [value, value, value]
+ elif type(value) == type((0,0,0)):
+ return list(value)
+ else:
+ return list(map(int, value.split()))
+
+ def setPixel(self, x, y, color):
+ """Sets pixel (x,y) to the given color
+
+ """
+ self.img.put("{" + color +"}", (x, y))
+
+
+ def save(self, filename):
+ """Saves the pixmap image to filename.
+ The format for the save image is determined from the filname extension.
+
+ """
+
+ path, name = os.path.split(filename)
+ ext = name.split(".")[-1]
+ self.img.write( filename, format=ext)
+
+
+def color_rgb(r,g,b):
+ """r,g,b are intensities of red, green, and blue in range(256)
+ Returns color specifier string for the resulting color"""
+ return "#%02x%02x%02x" % (r,g,b)
+
+def test():
+ win = GraphWin()
+ win.setCoords(0,0,10,10)
+ t = Text(Point(5,5), "Centered Text")
+ t.draw(win)
+ p = Polygon(Point(1,1), Point(5,3), Point(2,7))
+ p.draw(win)
+ e = Entry(Point(5,6), 10)
+ e.draw(win)
+ win.getMouse()
+ p.setFill("red")
+ p.setOutline("blue")
+ p.setWidth(2)
+ s = ""
+ for pt in p.getPoints():
+ s = s + "(%0.1f,%0.1f) " % (pt.getX(), pt.getY())
+ t.setText(e.getText())
+ e.setFill("green")
+ e.setText("Spam!")
+ e.move(2,0)
+ win.getMouse()
+ p.move(2,3)
+ s = ""
+ for pt in p.getPoints():
+ s = s + "(%0.1f,%0.1f) " % (pt.getX(), pt.getY())
+ t.setText(s)
+ win.getMouse()
+ p.undraw()
+ e.undraw()
+ t.setStyle("bold")
+ win.getMouse()
+ t.setStyle("normal")
+ win.getMouse()
+ t.setStyle("italic")
+ win.getMouse()
+ t.setStyle("bold italic")
+ win.getMouse()
+ t.setSize(14)
+ win.getMouse()
+ t.setFace("arial")
+ t.setSize(20)
+ win.getMouse()
+ win.close()
+
+#MacOS fix 2
+#tk.Toplevel(_root).destroy()
+
+# MacOS fix 1
+update()
+
+if __name__ == "__main__":
+ test()
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..abca9bf
--- /dev/null
+++ b/README.md
@@ -0,0 +1 @@
+# Nand2tetris \ No newline at end of file