class EnigmaKey(GCompound): def __init__(self, letter): GCompound.__init__(self) key = GOval(KEY_RADIUS * 2, KEY_RADIUS * 2) key.setLineWidth(KEY_BORDER) key.setColor(KEY_BORDER_COLOR) key.setFillColor(KEY_BGCOLOR) self.add(key, -KEY_RADIUS, -KEY_RADIUS) # create design for keys self.ch = GLabel(letter) self.ch.setColor(KEY_UP_COLOR) self.ch.setFont(KEY_FONT) self.add(self.ch, -self.ch.getWidth() / 2, KEY_LABEL_DY) def setLetterColor(self, color): # change letter color if needed self.ch.setColor(color) def mousedownAction(self, enigma): # define mousedownAction self.setLetterColor(KEY_DOWN_COLOR) enigma.keyPressed(self) def mouseupAction(self, enigma): # define mouseupAction self.setLetterColor(KEY_UP_COLOR) enigma.keyReleased(self)
def letterFound(ch): """ Checks if the letter clicked is in the word and replaces dashes with the letter everywhere it appears """ nonlocal full_word, mystery_word, word_display, game_over s = 0 if full_word.find(ch) != -1: while s <= len(full_word): if full_word.find(ch, s) != -1: letter = full_word.find(ch, s) mystery_word = mystery_word[:letter] + ch + mystery_word[ letter + 1:] s += letter + 1 else: s = len(full_word) + 1 gw.remove(word_display) word_display = GLabel(mystery_word) word_display.setFont(WORD_FONT) gw.add(word_display, (GWINDOW_WIDTH - word_display.getWidth()) / 2, GWINDOW_HEIGHT - WORD_BASE) if mystery_word == full_word: message = gw.getElementAt(GWINDOW_WIDTH / 2, GWINDOW_HEIGHT - MESSAGE_BASE) gw.remove(message) message = GLabel('YOU WIN!') message.setFont(MESSAGE_FONT) message.setColor(CORRECT_COLOR) gw.add(message, (GWINDOW_WIDTH - message.getWidth()) / 2, GWINDOW_HEIGHT - MESSAGE_BASE) game_over = True animateMelting() return True
def createButton(s):# makes a button with the string s button=GCompound() buttonSize=75 label=GLabel(s) label.setColor("white") label.setFont("8px 'Sans-Serif'") c=GOval(-(label.getWidth()+20)//2,-buttonSize//2,label.getWidth()+20,buttonSize) c.setFillColor("black") c.setFilled(True) button.add(c) button.add(label,-label.getWidth()//2,0) return button
class SudokuDigitSelectorSubcell(GCompound): def __init__(self, digit): GCompound.__init__(self) self.digit = str(digit) cell = GRect(0, 0, SUBCELL_WIDTH, SUBCELL_WIDTH) cell.setColor(CELL_BORDER_COLOR) cell.setFillColor(SUBCELL_FILL_COLOR) cell.setFilled(True) self.add(cell, 0, 0) self.label = GLabel(digit) self.label.setFont(SUBCELL_FONT) self.label.setColor(SUBCELL_TEXT_COLOR) self.add(self.label, SUBCELL_WIDTH//2 - self.label.getWidth()//2, SUBCELL_WIDTH//2 + self.label.getAscent()//2 - 3)
def __init__(self, letter): ''' The constructor initalizes the key for a given letter. ''' GCompound.__init__(self) button = createFilledCircle(0, 0, KEY_RADIUS, fill=KEY_BGCOLOR, border=KEY_BORDER_COLOR) button.setLineWidth(KEY_BORDER) key = GLabel(letter) key.setFont(KEY_FONT) self.key = key key.setColor(KEY_UP_COLOR) self.add(button) self.add(key, -key.getWidth() / 2, KEY_LABEL_DY)
def __init__(self): ''' The constructor creates a return button on the enigma. ''' GCompound.__init__(self) button = createFilledRect(-RETURN_WIDTH / 2, -RETURN_HEIGHT / 2, RETURN_WIDTH, RETURN_HEIGHT, fill=RETURN_BGCOLOR, border=RETURN_BORDER_COLOR) button.setLineWidth(RETURN_BORDER) label = GLabel('RETURN') label.setFont(RETURN_FONT) label.setColor(RETURN_COLOR) self.add(button) self.add(label, -label.getWidth() / 2, RETURN_LABEL_DY)
def displayWordsList(puzzle): puzzle = puzzle.lower() legalWords = [] # Create blank list of words points = 0 x = WORDLIST_X i = 0 for word in ENGLISH_WORDS: if isLegalEntry(word, puzzle): legalWords.append(word) # Add leagal words to legalWords def isPangram(word): # Check to see if Pangram letters = 0 for ch in puzzle: if ch in word: letters += 1 if letters == len(puzzle): return True else: return False for word in legalWords: points += len(word) - 3 # Number of points per word if isPangram(word): # Make changes if pangram points += 7 line = GLabel(word) line.setColor(PANGRAM_COLOR) line.setFont(WORDLIST_FONT) else: line = GLabel(word) line.setFont(WORDLIST_FONT) y = WORDLIST_Y + WORDLIST_DY * i gw.add(line, x, y) # Add words to window i += 1 if y >= GWINDOW_HEIGHT - (SCORE_BASELINE + SCORE_WORDLIST_SEP + line.getAscent()): x += WORDLIST_DX i = 0 score = GLabel( str(len(legalWords)) + " words; " + str(points) + " points") # Add score to window score.setFont(WORDLIST_FONT) gw.add(score, WORDLIST_X, GWINDOW_HEIGHT - SCORE_BASELINE)
def step(): nonlocal vx, vy, ball, bricks_hit, balls_left, x_text, y_text collider = getCollidingObject() if ball.getX() < 0 or ball.getX() > GWINDOW_WIDTH - BALL_SIZE: vx *= -1 elif ball.getY() < 0: vy *= -1 elif ball.getY() > GWINDOW_HEIGHT - BALL_SIZE: timer.stop() gw.remove(ball) balls_left -= 1 if balls_left > 0: ball = GOval((GWINDOW_WIDTH - BALL_SIZE) / 2, (GWINDOW_HEIGHT - BALL_SIZE) / 2, BALL_SIZE, BALL_SIZE) ball.setFilled(True) gw.add(ball) gw.add(instruct) else: msg = GLabel('You Lose.') msg.setColor('red') msg.setFont('bold 36px sans-serif') x = (GWINDOW_WIDTH - msg.getWidth()) / 2 y = (GWINDOW_HEIGHT - msg.getHeight()) / 2 gw.add(msg, x, y) if collider == paddle: vy *= -1 elif not (collider == paddle or collider == gw.getElementAt( x_text, y_text)) and collider is not None: vy *= -1 gw.remove(collider) bricks_hit += 1 if bricks_hit == N_COLS * N_ROWS: timer.stop() msg = GLabel('You Win!') msg.setColor('green') msg.setFont('bold 36px sans-serif') x = (GWINDOW_WIDTH - msg.getWidth()) / 2 y = (GWINDOW_HEIGHT - msg.getHeight()) / 2 gw.add(msg, x, y) ball.move(vx, vy) gw.remove(gw.getElementAt(x_text, y_text)) lives = GLabel('Lives: ' + str(balls_left)) gw.add(lives, x_text, y_text)
def __init__(self, letter): ''' The constructor creates a lamp for a given letter. ''' GCompound.__init__(self) self.letter = letter lamp = createFilledCircle(0, 0, LAMP_RADIUS, fill=LAMP_BGCOLOR, border=LAMP_BORDER_COLOR) lamp = GLabel(letter) lamp.setFont(LAMP_FONT) self.lamp = lamp self.state = False lamp.setColor(LAMP_OFF_COLOR) self.add(lamp) self.add(lamp, -lamp.getWidth() / 2, LAMP_LABEL_DY)
class TextBox(GCompound): def __init__(self, msg, font="Helvetica", font_size=12, font_color="#000000"): super().__init__() self.label = GLabel(msg) self.label.setFont("{}px '{}'".format(font_size, font)) self.label.setColor(font_color) self.add(self.label, -self.get_width() // 2, (self.label.getAscent() - self.label.getDescent()) // 2) def get_height(self): return self.label.getAscent() + self.label.getDescent() def get_width(self): return self.label.getBounds().getWidth()
def step(): nonlocal snowman, dx, dy, full_word if snowman.getX() > (GWINDOW_WIDTH - BASE_SIZE) or snowman.getX() < BASE_SIZE: dx *= -1 gw.remove( gw.getElementAt(GWINDOW_WIDTH / 2, GWINDOW_HEIGHT - WORD_BASE)) word_display = GLabel(full_word) word_display.setFont(WORD_FONT) word_display.setColor(INCORRECT_COLOR) gw.add(word_display, (GWINDOW_WIDTH - word_display.getWidth()) / 2, GWINDOW_HEIGHT - WORD_BASE) elif snowman.getY() < (GWINDOW_HEIGHT - BASE_SIZE - BODY_SIZE - HEAD_SIZE) or snowman.getY() > SNOWMAN_BASE: dy *= -1 snowman.move(dx, dy)
def __init__(self, permuation): ''' The constructor initalizes the rotor in the base setting. ''' GCompound.__init__(self) self.permuation = permuation self.inversion = invertKey(permuation) self.offset = 0 rotor = createFilledRect(-ROTOR_WIDTH / 2, -ROTOR_HEIGHT / 2, ROTOR_WIDTH, ROTOR_HEIGHT, fill=ROTOR_BGCOLOR) setting = GLabel(ALPHABET[self.offset]) setting.setColor(ROTOR_COLOR) setting.setFont(ROTOR_FONT) self.setting = setting self.add(rotor) self.add(setting, -setting.getWidth() / 2, ROTOR_LABEL_DY)
class MenuBar(GCompound): def __init__(self): GCompound.__init__(self) bar = GRect(GWINDOW_WIDTH, MENU_BAR_HEIGHT) bar.setFilled(True) bar.setColor(CELL_BORDER_COLOR) bar.setFillColor(MENU_BAR_BGCOLOR) self.add(bar, 0, 0) self.label = GLabel("Y O U D O K U") self.label.setFont(MENU_TITLE_FONT) self.label.setColor(MENU_TITLE_COLOR) self.add(self.label, GWINDOW_WIDTH//2 - self.label.getWidth()//2, MENU_BAR_HEIGHT//2 + self.label.getAscent()//2 - 5) def mousedown(self, x, y): pass def mouseup(self, x, y): pass
def __init__(self, rotor): ''' The constructor initalizes the selector in the standard setting in the three rotor model. ''' GCompound.__init__(self) self.offset = rotor self.rotor = rotor button = createFilledRect(-SELECTOR_WIDTH / 2, -SELECTOR_HEIGHT / 2, SELECTOR_WIDTH, SELECTOR_HEIGHT, fill=SELECTOR_BGCOLOR, border=SELECTOR_COLOR) button.setLineWidth(3) setting = GLabel(str(self.offset)) setting.setFont(SELECTOR_FONT) setting.setColor(SELECTOR_COLOR) self.setting = setting self.add(button) self.add(setting, -setting.getWidth() / 2, SELECTOR_LABEL_DY)
class EnigmaLamp(GCompound): def __init__(self, letter): GCompound.__init__(self) lamp = GOval(LAMP_RADIUS * 2, LAMP_RADIUS * 2) lamp.setColor(LAMP_BORDER_COLOR) lamp.setFillColor(LAMP_BGCOLOR) self.add(lamp, -LAMP_RADIUS, -LAMP_RADIUS) # create design for lamps self.ch = GLabel(letter) self.ch.setColor(LAMP_OFF_COLOR) self.ch.setFont(LAMP_FONT) self.add(self.ch, -self.ch.getWidth() / 2, LAMP_LABEL_DY) def setState(self, state): # set state of lamp to be on or off if state: self.ch.setColor(LAMP_ON_COLOR) else: self.ch.setColor(LAMP_OFF_COLOR) def getState(self): # get state of lamp )(n or off) if self.ch.getColor() == LAMP_ON_COLOR: return True else: return False
class EnigmaRotor(GCompound): def __init__(self, letter, perm, inverse): GCompound.__init__(self) rotor = GRect(ROTOR_WIDTH, ROTOR_HEIGHT) rotor.setColor(ROTOR_BGCOLOR) rotor.setFilled(True) self.add(rotor, -ROTOR_WIDTH / 2, -ROTOR_HEIGHT / 2) # create design for rotors self.ch = GLabel(letter) self.ch.setColor(ROTOR_COLOR) self.ch.setFont(ROTOR_FONT) self.add(self.ch, -self.ch.getWidth() / 2, ROTOR_LABEL_DY) self.perm = perm self.inverse = inverse self.offset = 0 self.rotor = rotor def clickAction(self, enigma): # advance on click action of rotors self.advance() def advance(self): # define advance self.offset += 1 if self.offset == 26: self.offset = 0 r = True # tells that the rotor should carry else: r = False # tells that the rotor should not carry self.ch.setLabel(ALPHABET[self.offset]) return r
def ImageShop(classifier_file): def addButton(label, action): """ Adds a button to the region on the left side of the window """ nonlocal nextButtonY x = BUTTON_MARGIN y = nextButtonY button = GButton(label, action) button.setSize(BUTTON_WIDTH, BUTTON_HEIGHT) gw.add(button, x, y) nextButtonY += BUTTON_HEIGHT + BUTTON_MARGIN def setImage(image): """ Sets image as the current image after removing the old one. """ nonlocal currentImage if currentImage is not None: gw.remove(currentImage) currentImage = image x = BUTTON_AREA_WIDTH + (IMAGE_AREA_WIDTH - image.getWidth() * image.sf) / 2 y = (gw.getHeight() - image.getHeight() * image.sf) / 2 gw.add(image, x, y) def setThermometer(percentage): if percentage > 0.50: showYes() else: showNo() likelihood.setSize(BUTTON_AREA_WIDTH-10, percentage * (GWINDOW_HEIGHT-nextButtonY-5)) def loadButtonAction(): """Callback function for the Load button""" nonlocal currentFile filename = chooseInputFile() currentFile = filename if filename != "": img = GImage(filename) width = len(img.getPixelArray()) height = len(img.getPixelArray()[0]) max_dim = max(width, height) sf = 750 / max_dim if max_dim > 750: img.scale(sf) setImage(img) clearMessage() def flipVerticalAction(): """Callback function for the FlipVertical button""" if currentImage is not None: setImage(flipVertical(currentImage)) def flipHorizontalAction(): """Callback function for the FlipHorizontal button""" if currentImage is not None: setImage(flipHorizontal(currentImage)) def rotateLeftAction(): """Callback function for the RotateLeft button""" if currentImage is not None: setImage(rotateLeft(currentImage)) def rotateRightAction(): """Callback function for the RotateRight button""" if currentImage is not None: setImage(rotateRight(currentImage)) def isZebraAction(): """Callback function for the Is It a Zebra? button""" if currentFile is not None: zebra_prob = classifier(currentFile)['zebra'] setThermometer(zebra_prob) def showYes(): clearMessage() gw.add(yes, BUTTON_AREA_WIDTH//2-30, GWINDOW_HEIGHT-nextButtonY//2-150) def showNo(): clearMessage() gw.add(no, BUTTON_AREA_WIDTH//2-20, GWINDOW_HEIGHT-nextButtonY//2-150) def clearMessage(): gw.remove(yes) gw.remove(no) gw = GWindow(GWINDOW_WIDTH, GWINDOW_HEIGHT) buttonArea = GRect(0, 0, BUTTON_AREA_WIDTH, GWINDOW_HEIGHT) buttonArea.setFilled(True) buttonArea.setColor(BUTTON_BACKGROUND) gw.add(buttonArea) nextButtonY = BUTTON_MARGIN currentImage = None currentFile = None addButton("Load", loadButtonAction) addButton("Flip Vertical", flipVerticalAction) addButton("Flip Horizontal", flipHorizontalAction) addButton("Rotate Left", rotateLeftAction) addButton("Rotate Right", rotateRightAction) addButton("Is It a Zebra?", isZebraAction) thermometer = GRect(5, nextButtonY, BUTTON_AREA_WIDTH-10, GWINDOW_HEIGHT-nextButtonY-5) thermometer.setFilled(True) thermometer.setColor("red") likelihood = GRect(5, nextButtonY, BUTTON_AREA_WIDTH-10, 0) likelihood.setFilled(True) likelihood.setColor("green") gw.add(thermometer) gw.add(likelihood) yes = GLabel("YES") yes.setColor("white") yes.setFont("bold 36px 'Monaco','Monospaced'") no = GLabel("NO") no.setColor("white") no.setFont("bold 36px 'Monaco','Monospaced'") from cnn import Classifier classifier = Classifier.load(classifier_file)
def clickAction(e): """ Checks if there is a letter where was clicked and identifies the letter. Counts incorrect guesses and implements game over and resets the screen. """ nonlocal incorrect_guesses, snowman, mystery_word, full_word, word_display, game_over, letters_chosen, timer if e.getY() > GWINDOW_HEIGHT - WORD_BASE and not game_over: pick = gw.getElementAt(e.getX(), e.getY()) if pick is not None: letter = pick.getLabel() if letter in letters_chosen: gw.remove( gw.getElementAt(GWINDOW_WIDTH / 2, GWINDOW_HEIGHT - MESSAGE_BASE)) message = GLabel('You already picked that letter!') message.setFont(MESSAGE_FONT) gw.add(message, (GWINDOW_WIDTH - message.getWidth()) / 2, GWINDOW_HEIGHT - MESSAGE_BASE) else: letters_chosen.append(letter) gw.remove( gw.getElementAt(GWINDOW_WIDTH / 2, GWINDOW_HEIGHT - MESSAGE_BASE)) if letterFound(letter): pick.setColor(CORRECT_COLOR) else: pick.setColor(INCORRECT_COLOR) incorrect_guesses += 1 addSnowmanPart(snowman, incorrect_guesses) else: gw.remove( gw.getElementAt(GWINDOW_WIDTH / 2, GWINDOW_HEIGHT - MESSAGE_BASE)) message = GLabel('Click a letter!') message.setFont(MESSAGE_FONT) gw.add(message, (GWINDOW_WIDTH - message.getWidth()) / 2, GWINDOW_HEIGHT - MESSAGE_BASE) if incorrect_guesses == 8: game_over = True gw.remove( gw.getElementAt(GWINDOW_WIDTH / 2, GWINDOW_HEIGHT - MESSAGE_BASE)) message = GLabel('YOU LOSE!') message.setFont(MESSAGE_FONT) message.setColor(INCORRECT_COLOR) gw.add(message, (GWINDOW_WIDTH - message.getWidth()) / 2, GWINDOW_HEIGHT - MESSAGE_BASE) animateSnowman() elif not game_over: gw.remove( gw.getElementAt(GWINDOW_WIDTH / 2, GWINDOW_HEIGHT - MESSAGE_BASE)) message = GLabel('Click a letter!') message.setFont(MESSAGE_FONT) gw.add(message, (GWINDOW_WIDTH - message.getWidth()) / 2, GWINDOW_HEIGHT - MESSAGE_BASE) elif game_over: timer.stop() gw.clear() full_word = random.choice(SNOWMAN_WORDS) mystery_word = '-' * len(full_word) word_display = GLabel(mystery_word) word_display.setFont(WORD_FONT) gw.add(word_display, (GWINDOW_WIDTH - word_display.getWidth()) / 2, GWINDOW_HEIGHT - WORD_BASE) alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' for i in range(len(alphabet)): letter = GLabel(alphabet[i]) letter.setFont(LETTER_FONT) x = ((GWINDOW_WIDTH - len(alphabet) * letter.getWidth()) / (len(alphabet) + 1)) * (1 + i) + i * letter.getWidth() gw.add(letter, x, GWINDOW_HEIGHT - LETTER_BASE) incorrect_guesses = 0 snowman = createEmptySnowman(gw) game_over = False letters_chosen = []
def displayPuzzleWordList(gw, wordlist, Puzzle): NumberOfWords = 0 NumberOfPoints = 0 NumberOfPangram = 0 mainlist = wordlist MaxNumberOfRows = ( (gw.getHeight() - WORDLIST_Y - SCORE_BASELINE - SCORE_WORDLIST_SEP) // WORDLIST_DY) + 1 #Rounding up while len(mainlist) % MaxNumberOfRows != 0: mainlist.append("") NumberOfWords -= 1 #Every empty entry should be worth zero words NumberOfPoints += 3 #Every empty entry should be worth a net of zero points #print("NumberOfWords for empty is " + str(NumberOfWords)) #print("NumberOfPoints for empty is " + str(NumberOfPoints)) MaxNumberOfColumns = (len(mainlist) // MaxNumberOfRows ) + 1 #Floating fraction will be rounded up for c in range(MaxNumberOfColumns): for r in range(MaxNumberOfRows): if c == MaxNumberOfColumns - 1 and r >= len(mainlist) - len( wordlist): break xCoordinate = WORDLIST_X + c * WORDLIST_DX yCoordinate = WORDLIST_Y + r * WORDLIST_DY elementList = mainlist[ c * MaxNumberOfRows:(c + 1) * MaxNumberOfRows] #Getting elements in a column if c == MaxNumberOfColumns - 1 and r >= len(mainlist) - len( wordlist): #To not go beyond the index of the list break element = elementList[ r] #From the column elementList, choosing the r'th entry label = GLabel(element, xCoordinate, yCoordinate) label.setFont(WORDLIST_FONT) NumberOfWords += 1 if len(element) >= 7: #From here, the code to assign points starts check = True NumberOfPoints += len(element) - 3 for i in range(7): if list(Puzzle.lower())[i] not in list(element): check = False if check: label.setColor(PANGRAM_COLOR) NumberOfPoints += 7 NumberOfPangram += 1 #Here's the code for bonus pangram points else: NumberOfPoints += len( element ) - 3 #Code to assign points to less than 7 lettered words #The two lines below were part of the debugging process # print("NumberOfWords for this step is " + str(NumberOfWords)) # print("NumberOfPoints for this step is " + str(NumberOfPoints)) #By printing out the values for these variables, I was able to see the problem in previous code gw.add(label) print("Number of Pangrams are: " + str(NumberOfPangram)) WordsAndPoints = str(NumberOfWords) + " words; " + str( NumberOfPoints) + " points" labelWordsAndPoints = GLabel(WordsAndPoints, WORDLIST_X, gw.getHeight() - SCORE_BASELINE) labelWordsAndPoints.setFont(WORDLIST_FONT) gw.add(labelWordsAndPoints)
class SudokuCell(GCompound): def __init__(self, digit): GCompound.__init__(self) if digit != 0: self.digit = str(digit) else: self.digit = None self.cell = GRect(0, 0, CELL_WIDTH, CELL_WIDTH) self.cell.setColor(CELL_BORDER_COLOR) self.cell.setFillColor(CELL_GOOD_COLOR) self.cell.setFilled(True) self.add(self.cell, 0, 0) self.label = None self.only_a_suggestion = True self.render_label() self.selector = None def get_digit(self): if self.digit == None or self.digit == '' or self.only_a_suggestion: return 0 else: return int(self.digit) def set_background_color(self, color): self.cell.setFillColor(color) def suggest_solution(self, digit): if self.only_a_suggestion: self.digit = str(digit) self.render_label() def render_label(self): if self.label is not None: self.remove(self.label) if self.digit is not None and self.digit != "0": self.label = GLabel(self.digit) else: self.label = GLabel("") self.label.setFont(CELL_FONT) if self.only_a_suggestion: self.label.setColor(SUGGESTION_TEXT_COLOR) else: self.label.setColor(CELL_TEXT_COLOR) self.add(self.label, CELL_WIDTH//2 - self.label.getWidth()//2, CELL_WIDTH//2 + self.label.getAscent()//2 - 7) def mousedown(self): self.selector = SudokuDigitSelector() self.add(self.selector, 0, 0) def mouseup(self, x, y): if self.selector is not None: digit = self.selector.mouseup(x, y) if digit is not None: self.digit = digit if str(self.digit) == "0" or self.digit == "": self.digit = "" self.only_a_suggestion = True elif self.digit != "": self.only_a_suggestion = False self.render_label() self.remove(self.selector) self.selector = None