Create the logic game Mastermind using a GUI Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Announcing the arrival of Valued Associate #679: Cesar Manara Unicorn Meta Zoo #1: Why another podcast?Simple Mastermind gameGame of Life, separation of logic / GUISmall building game logicMastermind: Evaluating the guessA simple Mastermind game in CMastermind game - Evaluating the guess in RubyWorded Mastermind game in PythonGUI Calculator using tkinterMemory Game using Tkinter/PygameTkinter GUI Python implementation using classes

Where and when has Thucydides been studied?

How does the body cool itself in a stillsuit?

Does a random sequence of vectors span a Hilbert space?

First paper to introduce the "principal-agent problem"

3D Masyu - A Die

Centre cell contents vertically

The Nth Gryphon Number

Does the main washing effect of soap come from foam?

Can haste grant me and my beast master companion extra attacks?

Did John Wesley plagiarize Matthew Henry...?

Pointing to problems without suggesting solutions

Putting class ranking in CV, but against dept guidelines

Random body shuffle every night—can we still function?

How can I prevent/balance waiting and turtling as a response to cooldown mechanics

Is there a verb for listening stealthily?

"Destructive power" carried by a B-52?

malloc in main() or malloc in another function: allocating memory for a struct and its members

Why is a lens darker than other ones when applying the same settings?

What does 丫 mean? 丫是什么意思?

Is a copyright notice with a non-existent name be invalid?

Should man-made satellites feature an intelligent inverted "cow catcher"?

How much damage would a cupful of neutron star matter do to the Earth?

By what mechanism was the 2017 UK General Election called?

Short story about astronauts fertilizing soil with their own bodies



Create the logic game Mastermind using a GUI



Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)
Announcing the arrival of Valued Associate #679: Cesar Manara
Unicorn Meta Zoo #1: Why another podcast?Simple Mastermind gameGame of Life, separation of logic / GUISmall building game logicMastermind: Evaluating the guessA simple Mastermind game in CMastermind game - Evaluating the guess in RubyWorded Mastermind game in PythonGUI Calculator using tkinterMemory Game using Tkinter/PygameTkinter GUI Python implementation using classes



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








0












$begingroup$


This code uses a single Mastermind class to hold everything needed as a tkinter widget that inherits from tk.Frame. Is this the best way of organising something like this or would it be better to use two classes - one for the game logic and one for the GUI?



The code itself seems messy, although I have no experince with tkinter applications larger than a Hello World script, so ways to clean it up aand/or reorganise it would be greatly appreciated.



import tkinter as tk
from random import choices
import itertools as it


class Mastermind(tk.Frame):

def __init__(self, master, holes=5, colours=8, guesses=12, bg="white", fg="black", **kwargs):
self.numberOfHoles = holes
self.numberOfColours = colours
self.numberOfGuesses = guesses
self.bg = bg
self.fg = fg
self.master = master
self.colours = ["#9E5D00", "#FF0000", "#FF7F00", "#FFFF00", "#00FF00",
"#0000FF", "#FF00FF", "#8C44FF", "#FFFFFF", "#000000"][:self.numberOfColours]
self.reset_cycles()
self.answer = choices(self.colours, k=self.numberOfHoles)
super().__init__(self.master, bg=self.bg, **kwargs)
print(self.answer)
self.create_gui()


def create_gui(self):
self.allGuesses = [tk.Frame(self, bg=self.bg) for _ in range(self.numberOfGuesses)]
self.allMarks = [tk.Frame(self, bg=self.bg) for _ in range(self.numberOfGuesses)]
self.answerFrame = tk.Frame(self, bg=self.bg)
self.answerCover = tk.Frame(self, bg=self.fg, relief=tk.RAISED)
self.allGuessPins = [[tk.Label(self.allGuesses[i], width=2, height=1, bg="grey", relief=tk.SUNKEN)
for _ in range(self.numberOfHoles)]
for i in range(self.numberOfGuesses)]
self.allMarkPins = [[tk.Label(self.allMarks[i], width=1, height=1, bg="lightgrey", relief=tk.SUNKEN)
for _ in range(self.numberOfHoles)]
for i in range(self.numberOfGuesses)]
self.answerPins = [tk.Label(self.answerFrame, width=2, height=1, bg=colour, relief=tk.RAISED) for colour in self.answer]
self.guessBtn = tk.Button(self, text="Guess", command=self.next_guess, bg=self.bg, fg=self.fg)
self.activeGuess = 0

for rowIndex in range(self.numberOfGuesses):
for holeIndex in range(self.numberOfHoles):
self.allGuessPins[rowIndex][holeIndex].grid(row=0, column=holeIndex, padx=1, pady=4)
self.allMarkPins[rowIndex][holeIndex].grid(row=0, column=holeIndex, padx=1, pady=4)
tk.Label(self, text=str(rowIndex+1), bg=self.bg, fg=self.fg).grid(row=self.numberOfGuesses-rowIndex, column=0)
self.allGuesses[rowIndex].grid(row=rowIndex+1, column=1)
self.allMarks[rowIndex].grid(row=rowIndex+1, column=3)

for i, a in enumerate(self.answerPins):
a.grid(row=0, column=i, padx=1)

tk.Label(self, text=" ", bg=self.bg).grid(row=0, column=2)
tk.Label(self, text=" ", bg=self.bg).grid(row=0, column=4)
for a in [tk.Label(self.answerCover, width=2, height=1, bg=self.fg) for _ in range(self.numberOfHoles)]:
a.pack(side=tk.LEFT, padx=1)

self.answerCover.grid(row=0, column=1, pady=15)
self.guessBtn.grid(column=1, row=999, pady=10)
self.next_guess(start=True)


def next_guess(self, start=False):
# Check there are no blanks
for colour in self.get_pin_colours():
if colour == "grey" and not start:
return None

# Stop responding to mouse button and remove highlighting
self.reset_cycles()
self.allGuesses[self.activeGuess].config(bg=self.bg)
for pin in self.allGuessPins[self.activeGuess]:
pin.unbind("<1>")
pin["cursor"] = ""

# Add the mark pins for the guess
score = self.score_guess(self.get_pin_colours(), self.answer)
if not start and len(score) != 0:
score = self.score_guess(self.get_pin_colours(), self.answer)
for i, pin in enumerate(self.allMarkPins[self.activeGuess]):
if i > len(score)-1:
break
pin.config(bg=score[i], relief=tk.RAISED)

# Check for a win
if score == ["Black" for _ in range(self.numberOfHoles)]:
self.answerCover.grid_forget()
self.answerFrame.grid(row=0, column=1, pady=15)
self.guessBtn["command"] = None
return None

# Move the guess up 1, bind mouse button and highlight row
try:
self.activeGuess -= 1
self.allGuesses[self.activeGuess].config(bg=self.fg)
for i, pin in enumerate(self.allGuessPins[self.activeGuess]):
pin.bind("<1>", lambda event, i=i: self.change_pin_colour(event, i))
pin["cursor"] = "hand"
except IndexError:
raise NotImplementedError()
# add lose condition


@staticmethod
def score_guess(guess, answer):
answer = answer.copy()
blacks = ["Black" for secret, guess_item in zip(answer, guess) if secret == guess_item]
whites = []
for guess_item in guess:
if guess_item in answer:
answer[answer.index(guess_item)] = None
whites.append("White")
return blacks + whites[:-len(blacks)]


def get_pin_colours(self):
return [pin["bg"] for pin in self.allGuessPins[self.activeGuess]]

def change_pin_colour(self, event, i):
event.widget.config(bg=next(self.colourCycles[i]), relief=tk.RAISED)

def reset_cycles(self):
self.colourCycles = it.tee(it.cycle(self.colours), self.numberOfHoles)


if __name__ == "__main__":
root = tk.Tk()
root.title("Mastermind")
x = Mastermind(root)
x.pack()
root.mainloop()









share|improve this question







New contributor




SImon is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







$endgroup$


















    0












    $begingroup$


    This code uses a single Mastermind class to hold everything needed as a tkinter widget that inherits from tk.Frame. Is this the best way of organising something like this or would it be better to use two classes - one for the game logic and one for the GUI?



    The code itself seems messy, although I have no experince with tkinter applications larger than a Hello World script, so ways to clean it up aand/or reorganise it would be greatly appreciated.



    import tkinter as tk
    from random import choices
    import itertools as it


    class Mastermind(tk.Frame):

    def __init__(self, master, holes=5, colours=8, guesses=12, bg="white", fg="black", **kwargs):
    self.numberOfHoles = holes
    self.numberOfColours = colours
    self.numberOfGuesses = guesses
    self.bg = bg
    self.fg = fg
    self.master = master
    self.colours = ["#9E5D00", "#FF0000", "#FF7F00", "#FFFF00", "#00FF00",
    "#0000FF", "#FF00FF", "#8C44FF", "#FFFFFF", "#000000"][:self.numberOfColours]
    self.reset_cycles()
    self.answer = choices(self.colours, k=self.numberOfHoles)
    super().__init__(self.master, bg=self.bg, **kwargs)
    print(self.answer)
    self.create_gui()


    def create_gui(self):
    self.allGuesses = [tk.Frame(self, bg=self.bg) for _ in range(self.numberOfGuesses)]
    self.allMarks = [tk.Frame(self, bg=self.bg) for _ in range(self.numberOfGuesses)]
    self.answerFrame = tk.Frame(self, bg=self.bg)
    self.answerCover = tk.Frame(self, bg=self.fg, relief=tk.RAISED)
    self.allGuessPins = [[tk.Label(self.allGuesses[i], width=2, height=1, bg="grey", relief=tk.SUNKEN)
    for _ in range(self.numberOfHoles)]
    for i in range(self.numberOfGuesses)]
    self.allMarkPins = [[tk.Label(self.allMarks[i], width=1, height=1, bg="lightgrey", relief=tk.SUNKEN)
    for _ in range(self.numberOfHoles)]
    for i in range(self.numberOfGuesses)]
    self.answerPins = [tk.Label(self.answerFrame, width=2, height=1, bg=colour, relief=tk.RAISED) for colour in self.answer]
    self.guessBtn = tk.Button(self, text="Guess", command=self.next_guess, bg=self.bg, fg=self.fg)
    self.activeGuess = 0

    for rowIndex in range(self.numberOfGuesses):
    for holeIndex in range(self.numberOfHoles):
    self.allGuessPins[rowIndex][holeIndex].grid(row=0, column=holeIndex, padx=1, pady=4)
    self.allMarkPins[rowIndex][holeIndex].grid(row=0, column=holeIndex, padx=1, pady=4)
    tk.Label(self, text=str(rowIndex+1), bg=self.bg, fg=self.fg).grid(row=self.numberOfGuesses-rowIndex, column=0)
    self.allGuesses[rowIndex].grid(row=rowIndex+1, column=1)
    self.allMarks[rowIndex].grid(row=rowIndex+1, column=3)

    for i, a in enumerate(self.answerPins):
    a.grid(row=0, column=i, padx=1)

    tk.Label(self, text=" ", bg=self.bg).grid(row=0, column=2)
    tk.Label(self, text=" ", bg=self.bg).grid(row=0, column=4)
    for a in [tk.Label(self.answerCover, width=2, height=1, bg=self.fg) for _ in range(self.numberOfHoles)]:
    a.pack(side=tk.LEFT, padx=1)

    self.answerCover.grid(row=0, column=1, pady=15)
    self.guessBtn.grid(column=1, row=999, pady=10)
    self.next_guess(start=True)


    def next_guess(self, start=False):
    # Check there are no blanks
    for colour in self.get_pin_colours():
    if colour == "grey" and not start:
    return None

    # Stop responding to mouse button and remove highlighting
    self.reset_cycles()
    self.allGuesses[self.activeGuess].config(bg=self.bg)
    for pin in self.allGuessPins[self.activeGuess]:
    pin.unbind("<1>")
    pin["cursor"] = ""

    # Add the mark pins for the guess
    score = self.score_guess(self.get_pin_colours(), self.answer)
    if not start and len(score) != 0:
    score = self.score_guess(self.get_pin_colours(), self.answer)
    for i, pin in enumerate(self.allMarkPins[self.activeGuess]):
    if i > len(score)-1:
    break
    pin.config(bg=score[i], relief=tk.RAISED)

    # Check for a win
    if score == ["Black" for _ in range(self.numberOfHoles)]:
    self.answerCover.grid_forget()
    self.answerFrame.grid(row=0, column=1, pady=15)
    self.guessBtn["command"] = None
    return None

    # Move the guess up 1, bind mouse button and highlight row
    try:
    self.activeGuess -= 1
    self.allGuesses[self.activeGuess].config(bg=self.fg)
    for i, pin in enumerate(self.allGuessPins[self.activeGuess]):
    pin.bind("<1>", lambda event, i=i: self.change_pin_colour(event, i))
    pin["cursor"] = "hand"
    except IndexError:
    raise NotImplementedError()
    # add lose condition


    @staticmethod
    def score_guess(guess, answer):
    answer = answer.copy()
    blacks = ["Black" for secret, guess_item in zip(answer, guess) if secret == guess_item]
    whites = []
    for guess_item in guess:
    if guess_item in answer:
    answer[answer.index(guess_item)] = None
    whites.append("White")
    return blacks + whites[:-len(blacks)]


    def get_pin_colours(self):
    return [pin["bg"] for pin in self.allGuessPins[self.activeGuess]]

    def change_pin_colour(self, event, i):
    event.widget.config(bg=next(self.colourCycles[i]), relief=tk.RAISED)

    def reset_cycles(self):
    self.colourCycles = it.tee(it.cycle(self.colours), self.numberOfHoles)


    if __name__ == "__main__":
    root = tk.Tk()
    root.title("Mastermind")
    x = Mastermind(root)
    x.pack()
    root.mainloop()









    share|improve this question







    New contributor




    SImon is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.







    $endgroup$














      0












      0








      0





      $begingroup$


      This code uses a single Mastermind class to hold everything needed as a tkinter widget that inherits from tk.Frame. Is this the best way of organising something like this or would it be better to use two classes - one for the game logic and one for the GUI?



      The code itself seems messy, although I have no experince with tkinter applications larger than a Hello World script, so ways to clean it up aand/or reorganise it would be greatly appreciated.



      import tkinter as tk
      from random import choices
      import itertools as it


      class Mastermind(tk.Frame):

      def __init__(self, master, holes=5, colours=8, guesses=12, bg="white", fg="black", **kwargs):
      self.numberOfHoles = holes
      self.numberOfColours = colours
      self.numberOfGuesses = guesses
      self.bg = bg
      self.fg = fg
      self.master = master
      self.colours = ["#9E5D00", "#FF0000", "#FF7F00", "#FFFF00", "#00FF00",
      "#0000FF", "#FF00FF", "#8C44FF", "#FFFFFF", "#000000"][:self.numberOfColours]
      self.reset_cycles()
      self.answer = choices(self.colours, k=self.numberOfHoles)
      super().__init__(self.master, bg=self.bg, **kwargs)
      print(self.answer)
      self.create_gui()


      def create_gui(self):
      self.allGuesses = [tk.Frame(self, bg=self.bg) for _ in range(self.numberOfGuesses)]
      self.allMarks = [tk.Frame(self, bg=self.bg) for _ in range(self.numberOfGuesses)]
      self.answerFrame = tk.Frame(self, bg=self.bg)
      self.answerCover = tk.Frame(self, bg=self.fg, relief=tk.RAISED)
      self.allGuessPins = [[tk.Label(self.allGuesses[i], width=2, height=1, bg="grey", relief=tk.SUNKEN)
      for _ in range(self.numberOfHoles)]
      for i in range(self.numberOfGuesses)]
      self.allMarkPins = [[tk.Label(self.allMarks[i], width=1, height=1, bg="lightgrey", relief=tk.SUNKEN)
      for _ in range(self.numberOfHoles)]
      for i in range(self.numberOfGuesses)]
      self.answerPins = [tk.Label(self.answerFrame, width=2, height=1, bg=colour, relief=tk.RAISED) for colour in self.answer]
      self.guessBtn = tk.Button(self, text="Guess", command=self.next_guess, bg=self.bg, fg=self.fg)
      self.activeGuess = 0

      for rowIndex in range(self.numberOfGuesses):
      for holeIndex in range(self.numberOfHoles):
      self.allGuessPins[rowIndex][holeIndex].grid(row=0, column=holeIndex, padx=1, pady=4)
      self.allMarkPins[rowIndex][holeIndex].grid(row=0, column=holeIndex, padx=1, pady=4)
      tk.Label(self, text=str(rowIndex+1), bg=self.bg, fg=self.fg).grid(row=self.numberOfGuesses-rowIndex, column=0)
      self.allGuesses[rowIndex].grid(row=rowIndex+1, column=1)
      self.allMarks[rowIndex].grid(row=rowIndex+1, column=3)

      for i, a in enumerate(self.answerPins):
      a.grid(row=0, column=i, padx=1)

      tk.Label(self, text=" ", bg=self.bg).grid(row=0, column=2)
      tk.Label(self, text=" ", bg=self.bg).grid(row=0, column=4)
      for a in [tk.Label(self.answerCover, width=2, height=1, bg=self.fg) for _ in range(self.numberOfHoles)]:
      a.pack(side=tk.LEFT, padx=1)

      self.answerCover.grid(row=0, column=1, pady=15)
      self.guessBtn.grid(column=1, row=999, pady=10)
      self.next_guess(start=True)


      def next_guess(self, start=False):
      # Check there are no blanks
      for colour in self.get_pin_colours():
      if colour == "grey" and not start:
      return None

      # Stop responding to mouse button and remove highlighting
      self.reset_cycles()
      self.allGuesses[self.activeGuess].config(bg=self.bg)
      for pin in self.allGuessPins[self.activeGuess]:
      pin.unbind("<1>")
      pin["cursor"] = ""

      # Add the mark pins for the guess
      score = self.score_guess(self.get_pin_colours(), self.answer)
      if not start and len(score) != 0:
      score = self.score_guess(self.get_pin_colours(), self.answer)
      for i, pin in enumerate(self.allMarkPins[self.activeGuess]):
      if i > len(score)-1:
      break
      pin.config(bg=score[i], relief=tk.RAISED)

      # Check for a win
      if score == ["Black" for _ in range(self.numberOfHoles)]:
      self.answerCover.grid_forget()
      self.answerFrame.grid(row=0, column=1, pady=15)
      self.guessBtn["command"] = None
      return None

      # Move the guess up 1, bind mouse button and highlight row
      try:
      self.activeGuess -= 1
      self.allGuesses[self.activeGuess].config(bg=self.fg)
      for i, pin in enumerate(self.allGuessPins[self.activeGuess]):
      pin.bind("<1>", lambda event, i=i: self.change_pin_colour(event, i))
      pin["cursor"] = "hand"
      except IndexError:
      raise NotImplementedError()
      # add lose condition


      @staticmethod
      def score_guess(guess, answer):
      answer = answer.copy()
      blacks = ["Black" for secret, guess_item in zip(answer, guess) if secret == guess_item]
      whites = []
      for guess_item in guess:
      if guess_item in answer:
      answer[answer.index(guess_item)] = None
      whites.append("White")
      return blacks + whites[:-len(blacks)]


      def get_pin_colours(self):
      return [pin["bg"] for pin in self.allGuessPins[self.activeGuess]]

      def change_pin_colour(self, event, i):
      event.widget.config(bg=next(self.colourCycles[i]), relief=tk.RAISED)

      def reset_cycles(self):
      self.colourCycles = it.tee(it.cycle(self.colours), self.numberOfHoles)


      if __name__ == "__main__":
      root = tk.Tk()
      root.title("Mastermind")
      x = Mastermind(root)
      x.pack()
      root.mainloop()









      share|improve this question







      New contributor




      SImon is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.







      $endgroup$




      This code uses a single Mastermind class to hold everything needed as a tkinter widget that inherits from tk.Frame. Is this the best way of organising something like this or would it be better to use two classes - one for the game logic and one for the GUI?



      The code itself seems messy, although I have no experince with tkinter applications larger than a Hello World script, so ways to clean it up aand/or reorganise it would be greatly appreciated.



      import tkinter as tk
      from random import choices
      import itertools as it


      class Mastermind(tk.Frame):

      def __init__(self, master, holes=5, colours=8, guesses=12, bg="white", fg="black", **kwargs):
      self.numberOfHoles = holes
      self.numberOfColours = colours
      self.numberOfGuesses = guesses
      self.bg = bg
      self.fg = fg
      self.master = master
      self.colours = ["#9E5D00", "#FF0000", "#FF7F00", "#FFFF00", "#00FF00",
      "#0000FF", "#FF00FF", "#8C44FF", "#FFFFFF", "#000000"][:self.numberOfColours]
      self.reset_cycles()
      self.answer = choices(self.colours, k=self.numberOfHoles)
      super().__init__(self.master, bg=self.bg, **kwargs)
      print(self.answer)
      self.create_gui()


      def create_gui(self):
      self.allGuesses = [tk.Frame(self, bg=self.bg) for _ in range(self.numberOfGuesses)]
      self.allMarks = [tk.Frame(self, bg=self.bg) for _ in range(self.numberOfGuesses)]
      self.answerFrame = tk.Frame(self, bg=self.bg)
      self.answerCover = tk.Frame(self, bg=self.fg, relief=tk.RAISED)
      self.allGuessPins = [[tk.Label(self.allGuesses[i], width=2, height=1, bg="grey", relief=tk.SUNKEN)
      for _ in range(self.numberOfHoles)]
      for i in range(self.numberOfGuesses)]
      self.allMarkPins = [[tk.Label(self.allMarks[i], width=1, height=1, bg="lightgrey", relief=tk.SUNKEN)
      for _ in range(self.numberOfHoles)]
      for i in range(self.numberOfGuesses)]
      self.answerPins = [tk.Label(self.answerFrame, width=2, height=1, bg=colour, relief=tk.RAISED) for colour in self.answer]
      self.guessBtn = tk.Button(self, text="Guess", command=self.next_guess, bg=self.bg, fg=self.fg)
      self.activeGuess = 0

      for rowIndex in range(self.numberOfGuesses):
      for holeIndex in range(self.numberOfHoles):
      self.allGuessPins[rowIndex][holeIndex].grid(row=0, column=holeIndex, padx=1, pady=4)
      self.allMarkPins[rowIndex][holeIndex].grid(row=0, column=holeIndex, padx=1, pady=4)
      tk.Label(self, text=str(rowIndex+1), bg=self.bg, fg=self.fg).grid(row=self.numberOfGuesses-rowIndex, column=0)
      self.allGuesses[rowIndex].grid(row=rowIndex+1, column=1)
      self.allMarks[rowIndex].grid(row=rowIndex+1, column=3)

      for i, a in enumerate(self.answerPins):
      a.grid(row=0, column=i, padx=1)

      tk.Label(self, text=" ", bg=self.bg).grid(row=0, column=2)
      tk.Label(self, text=" ", bg=self.bg).grid(row=0, column=4)
      for a in [tk.Label(self.answerCover, width=2, height=1, bg=self.fg) for _ in range(self.numberOfHoles)]:
      a.pack(side=tk.LEFT, padx=1)

      self.answerCover.grid(row=0, column=1, pady=15)
      self.guessBtn.grid(column=1, row=999, pady=10)
      self.next_guess(start=True)


      def next_guess(self, start=False):
      # Check there are no blanks
      for colour in self.get_pin_colours():
      if colour == "grey" and not start:
      return None

      # Stop responding to mouse button and remove highlighting
      self.reset_cycles()
      self.allGuesses[self.activeGuess].config(bg=self.bg)
      for pin in self.allGuessPins[self.activeGuess]:
      pin.unbind("<1>")
      pin["cursor"] = ""

      # Add the mark pins for the guess
      score = self.score_guess(self.get_pin_colours(), self.answer)
      if not start and len(score) != 0:
      score = self.score_guess(self.get_pin_colours(), self.answer)
      for i, pin in enumerate(self.allMarkPins[self.activeGuess]):
      if i > len(score)-1:
      break
      pin.config(bg=score[i], relief=tk.RAISED)

      # Check for a win
      if score == ["Black" for _ in range(self.numberOfHoles)]:
      self.answerCover.grid_forget()
      self.answerFrame.grid(row=0, column=1, pady=15)
      self.guessBtn["command"] = None
      return None

      # Move the guess up 1, bind mouse button and highlight row
      try:
      self.activeGuess -= 1
      self.allGuesses[self.activeGuess].config(bg=self.fg)
      for i, pin in enumerate(self.allGuessPins[self.activeGuess]):
      pin.bind("<1>", lambda event, i=i: self.change_pin_colour(event, i))
      pin["cursor"] = "hand"
      except IndexError:
      raise NotImplementedError()
      # add lose condition


      @staticmethod
      def score_guess(guess, answer):
      answer = answer.copy()
      blacks = ["Black" for secret, guess_item in zip(answer, guess) if secret == guess_item]
      whites = []
      for guess_item in guess:
      if guess_item in answer:
      answer[answer.index(guess_item)] = None
      whites.append("White")
      return blacks + whites[:-len(blacks)]


      def get_pin_colours(self):
      return [pin["bg"] for pin in self.allGuessPins[self.activeGuess]]

      def change_pin_colour(self, event, i):
      event.widget.config(bg=next(self.colourCycles[i]), relief=tk.RAISED)

      def reset_cycles(self):
      self.colourCycles = it.tee(it.cycle(self.colours), self.numberOfHoles)


      if __name__ == "__main__":
      root = tk.Tk()
      root.title("Mastermind")
      x = Mastermind(root)
      x.pack()
      root.mainloop()






      python-3.x game tkinter






      share|improve this question







      New contributor




      SImon is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.











      share|improve this question







      New contributor




      SImon is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      share|improve this question




      share|improve this question






      New contributor




      SImon is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      asked 10 mins ago









      SImonSImon

      1




      1




      New contributor




      SImon is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.





      New contributor





      SImon is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






      SImon is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.




















          0






          active

          oldest

          votes












          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "196"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );






          SImon is a new contributor. Be nice, and check out our Code of Conduct.









          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f217856%2fcreate-the-logic-game-mastermind-using-a-gui%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          SImon is a new contributor. Be nice, and check out our Code of Conduct.









          draft saved

          draft discarded


















          SImon is a new contributor. Be nice, and check out our Code of Conduct.












          SImon is a new contributor. Be nice, and check out our Code of Conduct.











          SImon is a new contributor. Be nice, and check out our Code of Conduct.














          Thanks for contributing an answer to Code Review Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          Use MathJax to format equations. MathJax reference.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f217856%2fcreate-the-logic-game-mastermind-using-a-gui%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          名間水力發電廠 目录 沿革 設施 鄰近設施 註釋 外部連結 导航菜单23°50′10″N 120°42′41″E / 23.83611°N 120.71139°E / 23.83611; 120.7113923°50′10″N 120°42′41″E / 23.83611°N 120.71139°E / 23.83611; 120.71139計畫概要原始内容臺灣第一座BOT 模式開發的水力發電廠-名間水力電廠名間水力發電廠 水利署首件BOT案原始内容《小檔案》名間電廠 首座BOT水力發電廠原始内容名間電廠BOT - 經濟部水利署中區水資源局

          格濟夫卡 參考資料 导航菜单51°3′40″N 34°2′21″E / 51.06111°N 34.03917°E / 51.06111; 34.03917ГезівкаПогода в селі 编辑或修订