Exemple #1
0
class App:
    def __init__(self):
        self.win = tk.Tk()
        self.win.geometry("640x400")
        self.canvas = Canvas()
        self.canvas.pack()
        self.scr = TurtleScreen(self.canvas)

        self.t = RawTurtle(self.scr)
        self.btn = Button(self.win, text="Press me!", command=self.do_action())
        self.btn.pack()

    def do_action(self):
        self.t.pensize(3)
        self.t.pencolor(random.choice(colors))
        self.t.speed(0)

        self.length = 5
        while self.length < 500:
            self.t.left(89)
            self.t.forward(self.length)
            self.t.right(-105)
            self.t.forward(self.length)
            self.length += 3

    def run(self):
        self.win.mainloop()
Exemple #2
0
    def __init__(self):
        self.win = tk.Tk()
        self.win.geometry("640x400")
        self.canvas = Canvas()
        self.canvas.pack()
        self.scr = TurtleScreen(self.canvas)

        self.t = RawTurtle(self.scr)
        self.btn = Button(self.win, text="Press me!", command=self.do_action())
        self.btn.pack()
Exemple #3
0
def some_view(request, report_no):
    # Create the HttpResponse object with the appropriate PDF headers.
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="somefilename.pdf"'

    report = IncidentReport.objects.get(report_no=report_no)

    styles = getSampleStyleSheet()
    styleN = styles['Normal']
    styleH = styles['Heading1']
    story = []
    # add some flowables
    story.append(Paragraph("Fraud Report", styleH))
    story.append(Paragraph("Report No :  " + report.report_no, styleN))
    story.append(
        Paragraph("Date of Incident :  " + str(report.date_of_incident),
                  styleN))
    story.append(
        Paragraph("Time of incident : " + str(report.time_of_incident),
                  styleN))
    story.append(Paragraph("Station  : " + report.station, styleN))
    story.append(
        Paragraph("Specific location  : " + report.specific_location, styleN))
    # ------------Parties-involved---------------------#
    story.append(Paragraph("Parties Involved", styleH))
    story.append(
        Paragraph(
            "Name of party involved      :" + report.name_of_party_involved,
            styleN))
    story.append(Paragraph("organisation    : " + report.organisation, styleN))
    story.append(Paragraph("gender    : " + report.gender, styleN))
    story.append(Paragraph("Role     : " + report.role, styleN))
    # ---------------------------Incident--Detail---------------------------------------------------#
    story.append(Paragraph("Incident Detail", styleH))
    story.append(
        Paragraph("Incident of detail :  " + report.incident_detail, styleN))
    # ----------------------------contact--details--------------------------------------------------#
    story.append(Paragraph("Contact Details", styleH))
    story.append(Paragraph("Name :  " + report.Full_Name, styleN))
    story.append(
        Paragraph("Position Title :  " + report.Position_Title, styleN))
    story.append(Paragraph("Phone Number:  " + report.Phone_no, styleN))
    story.append(Paragraph("Email:  " + report.email, styleN))

    c = Canvas(response)
    f = Frame(
        inch,
        inch,
        7 * inch,
        10 * inch,
    )
    f.addFromList(story, c)
    c.save()

    return response
Exemple #4
0
def ex64():
    canvas = Canvas(width=400, height=600, bg='white')
    left, right, top, num = 20, 50, 50, 15
    for i in range(num):
        canvas.create_oval(250 - right, 250 - left, 250 + right, 250 + left)
        canvas.create_oval(250 - 20, 250 - top, 250 + 20, 250 + top)
        canvas.create_rectangle(20 - 2 * i, 20 - 2 * i, 10 * (i + 2), 10 * (i + 2))
        right += 5
        left += 5
        top += 10
    canvas.pack()
    mainloop()
def start():
    window = Tk()
    window.title("SYSC 3310 Final Project: State toggling")
    window.geometry('325x150')

    # Creates the buttons
    backwards = Button(window,
                       text="Move Backwards",
                       command=lambda: sendCommand('1'))
    forwards = Button(window,
                      text="Move Forwards",
                      command=lambda: sendCommand('2'))
    reset = Button(window,
                   text="Reset Board",
                   command=lambda: sendCommand('0'))

    backwards.grid(column=0, row=0, padx=5, pady=2)
    forwards.grid(column=1, row=0, padx=5, pady=2)
    reset.grid(column=2, row=0, padx=5, pady=2)

    # Creates the boxes to display the current state
    global lbl
    lbl = Label(window, text="Just initialized")
    currState = Label(window, text="Current State: ")

    lbl.grid(column=1, row=1)
    currState.grid(column=0, row=1)

    # Creates the canvas, rectangle used for the UI display
    global canvas
    canvas = Canvas(window)
    canvas = Canvas(width=75, height=100)
    canvas.grid(column=0, row=4)

    global rectangle1
    global rectangle2
    rectangle1 = canvas.create_rectangle(5, 25, 25, 45, fill='black')
    rectangle2 = canvas.create_rectangle(30, 25, 50, 45, fill='black')

    canvas.create_text(15, 10, fill="black", font="Times 8 bold", text="P1.0")
    canvas.create_text(40, 10, fill="black", font="Times 8 bold", text="P2.0")

    # Sets up the receive thread
    receiveThread = threading.Thread(target=receiveState)
    receiveThread.daemon = True
    receiveThread.start()

    # Returns the board to its base state (state 1)
    # Optional
    sendCommand(INITIAL_STATE)

    window.mainloop()
    def __init__(self, title="Hangman"):
        super().__init__()
        self.title(title)
        self.geometry("720x600")
        self.configurationFile = "level.conf"
        self.dataFile = "hangman.dat"
        self.dataPath = "data/"
        self.__hp = HP.THangman(self)
        if os.path.exists(self.dataPath + self.dataFile):
            self.deserialize()
        self.output = tk.StringVar()
        self.output.set(self.__hp.getLetters)
        self.info = tk.StringVar()
        alphabets = 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', \
                    'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'Å', 'Ä', 'Ö', '-'
        self.Buttons = ButtonsBlock(self, alphabets, 15)
        self.Buttons.grid(row=0, column=0, columnspan=3, padx=10, pady=5)

        self.frame2 = tk.Frame(self).grid(row=2)
        tk.Label(self.frame2, textvariable=self.output).grid(pady=10,
                                                             columnspan=5)

        self.frame3 = tk.Frame(self).grid(row=3)
        tk.Label(self.frame3, textvariable=self.info).grid(padx=10,
                                                           pady=10,
                                                           columnspan=5,
                                                           sticky=tk.W + tk.E)

        tk.Button(self, text="Guess a new word",
                  command=self.new).grid(row=5,
                                         padx=30,
                                         pady=5,
                                         sticky=tk.E + tk.W,
                                         columnspan=5)
        self.canvas = Canvas(self, width=500, height=350)
        self.canvas.grid(row=8,
                         column=0,
                         columnspan=5,
                         padx=10,
                         sticky=tk.W + tk.E + tk.S + tk.N)
        self.turtle_screen = TurtleScreen(self.canvas)
        self.raw_turtle = RawTurtle(self.canvas)
        self.raw_turtle.hideturtle()
        self.raw_turtle.speed(0)

        self.restoreGUI()

        message = "You are currently playing in " + levels[
            self.__hp.level] + " level"
        messagebox.showinfo("Level of difficulty", message)

        self.protocol("WM_DELETE_WINDOW", self.close)
Exemple #7
0
def ex65():
    screenx = 400
    screeny = 400
    canvas = Canvas(width=screenx, height=screeny, bg='white')

    AspectRatio = 0.85
    MAXPTS = 15
    h = screeny
    w = screenx
    xcenter = w / 2
    ycenter = h / 2
    radius = (h - 30) / (AspectRatio * 2) - 20
    step = 360 / MAXPTS
    angle = 0.0
    for i in range(MAXPTS):
        rads = angle * math.pi / 180.0
        p = PTS()
        p.x = xcenter + int(math.cos(rads) * radius)
        p.y = ycenter - int(math.sin(rads) * radius * AspectRatio)
        angle += step
        points.append(p)
    canvas.create_oval(xcenter - radius, ycenter - radius,
                       xcenter + radius, ycenter + radius)
    for i in range(MAXPTS):
        for j in range(i, MAXPTS):
            canvas.create_line(points[i].x, points[i].y, points[j].x, points[j].y)

    canvas.pack()
    mainloop()
Exemple #8
0
def some_view(request, report_no):
        # Create the HttpResponse object with the appropriate PDF headers.
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="somefilename.pdf"'

    report = IncidentReport.objects.get(report_no=report_no)

    styles = getSampleStyleSheet()
    styleN = styles['Normal']
    styleH = styles['Heading1']
    story = []
        # add some flowables
    story.append(Paragraph("Fraud Report", styleH))
    story.append(Paragraph("Report No :  " + report.report_no, styleN))
    story.append(Paragraph("Date of Incident :  " + str(report.date_of_incident), styleN))
    story.append(Paragraph("Time of incident : " + str(report.time_of_incident), styleN))
    story.append(Paragraph("Station  : " + report.station, styleN))
    story.append(Paragraph("Specific location  : " + report.specific_location, styleN))
        # ------------Parties-involved---------------------#
    story.append(Paragraph("Parties Involved", styleH))
    story.append(Paragraph("Name of party involved      :" + report.name_of_party_involved, styleN))
    story.append(Paragraph("organisation    : " + report.organisation, styleN))
    story.append(Paragraph("gender    : " + report.gender, styleN))
    story.append(Paragraph("Role     : " + report.role, styleN))
        # ---------------------------Incident--Detail---------------------------------------------------#
    story.append(Paragraph("Incident Detail", styleH))
    story.append(Paragraph("Incident of detail :  " + report.incident_detail, styleN))
        # ----------------------------contact--details--------------------------------------------------#
    story.append(Paragraph("Contact Details", styleH))
    story.append(Paragraph("Name :  " + report.Full_Name, styleN))
    story.append(Paragraph("Position Title :  " + report.Position_Title, styleN))
    story.append(Paragraph("Phone Number:  " + report.Phone_no, styleN))
    story.append(Paragraph("Email:  " + report.email, styleN))

    c = Canvas(response)
    f = Frame( inch, inch, 7 * inch, 10 * inch, )
    f.addFromList(story, c)
    c.save()

    return  response
Exemple #9
0
def draw(lines):
    from tkinter import Tk, LEFT
    from turtle import Canvas, RawTurtle, TurtleScreen

    # set up the environment
    root = Tk()
    canvas = Canvas(root, width=800, height=800)
    canvas.pack()

    s = TurtleScreen(canvas)

    t = RawTurtle(canvas)
    t.speed(0)
    t.width(1)

    for line in lines:
        x, y = line[0]
        t.up()
        t.goto(x * 800 / 1024 - 400, -(y * 800 / 1024 - 400))
        for point in line:
            t.down()
            t.goto(point[0] * 800 / 1024 - 400, -(point[1] * 800 / 1024 - 400))

    s.mainloop()
Exemple #10
0
def ex63():
    x, y = 360, 160
    top = bottom = y - 30

    canvas = Canvas(width=400, height=600, bg='white')
    for i in range(20):
        canvas.create_oval(250 - top, 250 - bottom, 250 + top, 250 + bottom)
        top -= 5
        bottom += 5
    canvas.pack()
    mainloop()
Exemple #11
0
def ex57():
    canvas = Canvas(width=300, height=300, bg='green')
    canvas.pack(expand=YES, fill=BOTH)
    x0 = y0 = 263
    x1 = y1 = 275
    for i in range(19):
        canvas.create_line(x0, y0, x0, y1, width=1, fill='red')
        x0 -= 5
        y0 -= 5
        x1 += 5
        y1 += 5
    x0 = y0 = 263
    y1 = 275
    for i in range(21):
        canvas.create_line(x0, y0, x0, y1, fill='red')
        x0 += 5
        y0 += 5
        y1 += 5
    mainloop()
Exemple #12
0
def ex58():
    root = Tk()
    root.title('Canvas')
    canvas = Canvas(root, width=400, height=400, bg='yellow')
    x0 = y0 = 263
    x1 = y1 = 275
    for i in range(19):
        canvas.create_rectangle(x0, y0, x1, y1)
        x0 -= 5
        y0 -= 5
        x1 += 5
        y1 += 5
    canvas.pack()
    mainloop()
Exemple #13
0
obj2 = ViewDetails()
obj3 = IssueBook()
obj4 = Return()

root = Tk()
root.title("Library")
root.minsize(width=400, height=400)
root.geometry("600x500")
photo = ImageTk.PhotoImage(file="libicon.png")
root.iconphoto(False, photo)
#root.mainloop()
same = True
n = 0.25

# Adding a background image
canvas = Canvas(root)
canvas.pack(expand=YES, fill=BOTH)

image = ImageTk.PhotoImage(file="lib.jpg")
canvas.create_image(10, 10, image=image, anchor=NW)
#Adding a header
headingFrame1 = Frame(root, bg="#FFFFFF", bd=5)
headingFrame1.place(relx=0.2, rely=0.1, relwidth=0.6, relheight=0.16)
headingLabel = Label(headingFrame1,
                     text="Welcome to \n the Library",
                     bg='black',
                     fg='white',
                     font=('Courier', 15))
headingLabel.place(relx=0, rely=0, relwidth=1, relheight=1)

btn1 = Button(root,
class HP(tk.Tk):
    """
    * In requirements analysis there was method called configure(). I used method called config(),
    * because tk has method configure and don't know if it's meant to override that method and don't know how to get
    * around this without overriding tk method..
    * Currently there might not be enough words in expert level to play the game through..
    """
    class THangman(Hangman):
        def __init__(self, parent):
            self.level = parent.config()
            self.points = 0
            self._Hangman__words = self.readWords()
            super().__init__()

        def readWords(self):
            """
            * Overrides Hangman class method to use Classifier class method 
            """
            c = Classifier()
            return c.readWords(self.level)

        def newLevel(self):
            """
            * game has levels 0-4. Method updates level to next one. If player is in level 4, next one is 0.
            * After the level is updated, corresponding words are read to attribute _Hangman__words
            """
            if self.level < 4:
                self.level += 1
                message = "Congratulations! You have reached new level. You are now at " + levels[
                    self.level] + " level"
                messagebox.showinfo("New level reached", message)
            else:
                self.level = 0
                message = "Congratulations! You are now master of Hangman game, a Yoda of words!. Game will now start" \
                          " again in the demonstration level"
                messagebox.showinfo("New level reached", message)
            self._Hangman__words = self.readWords()

    def __init__(self, title="Hangman"):
        super().__init__()
        self.title(title)
        self.geometry("720x600")
        self.configurationFile = "level.conf"
        self.dataFile = "hangman.dat"
        self.dataPath = "data/"
        self.__hp = HP.THangman(self)
        if os.path.exists(self.dataPath + self.dataFile):
            self.deserialize()
        self.output = tk.StringVar()
        self.output.set(self.__hp.getLetters)
        self.info = tk.StringVar()
        alphabets = 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', \
                    'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'Å', 'Ä', 'Ö', '-'
        self.Buttons = ButtonsBlock(self, alphabets, 15)
        self.Buttons.grid(row=0, column=0, columnspan=3, padx=10, pady=5)

        self.frame2 = tk.Frame(self).grid(row=2)
        tk.Label(self.frame2, textvariable=self.output).grid(pady=10,
                                                             columnspan=5)

        self.frame3 = tk.Frame(self).grid(row=3)
        tk.Label(self.frame3, textvariable=self.info).grid(padx=10,
                                                           pady=10,
                                                           columnspan=5,
                                                           sticky=tk.W + tk.E)

        tk.Button(self, text="Guess a new word",
                  command=self.new).grid(row=5,
                                         padx=30,
                                         pady=5,
                                         sticky=tk.E + tk.W,
                                         columnspan=5)
        self.canvas = Canvas(self, width=500, height=350)
        self.canvas.grid(row=8,
                         column=0,
                         columnspan=5,
                         padx=10,
                         sticky=tk.W + tk.E + tk.S + tk.N)
        self.turtle_screen = TurtleScreen(self.canvas)
        self.raw_turtle = RawTurtle(self.canvas)
        self.raw_turtle.hideturtle()
        self.raw_turtle.speed(0)

        self.restoreGUI()

        message = "You are currently playing in " + levels[
            self.__hp.level] + " level"
        messagebox.showinfo("Level of difficulty", message)

        self.protocol("WM_DELETE_WINDOW", self.close)

    def deserialize(self):
        """
        * deserializes HP.THangman object from file hangman.dat
        * reads object in binary mode
        """
        file = None
        try:
            file = open(self.dataPath + self.dataFile, 'br')
            hp = pickle.load(file)
            if hp is not None and isinstance(hp, type(self.__hp)):
                self.__hp = hp
        except IOError as e:
            print(f'Tapahtui virhe: {e}')
        finally:
            if file:
                file.close()

    def restoreGUI(self):
        """
        * restores already drawn hanging tree from saved game
        * and restores already pressed buttons from saved game
        """
        missed = len(self.__hp.missed)
        if missed > 0:
            drawer = Drawer(self.turtle_screen, self.raw_turtle)
            for i in range(1, missed + 1):
                step_to_draw = {
                    1: drawer.basement,
                    2: drawer.main_bar,
                    3: drawer.upper_bar,
                    4: drawer.rope,
                    5: drawer.head,
                    6: drawer.body,
                    7: drawer.left_foot,
                    8: drawer.right_foot,
                    9: drawer.left_arm,
                    10: drawer.right_arm
                }
                step_to_draw[i]()
        if missed > 0 or len(self.__hp.corrects) > 0:
            for button in self.Buttons.buttons:
                letter = button['text'].lower()
                if letter in self.__hp.missed or letter in self.__hp.corrects:
                    button.config(state='disabled')

    def serialize(self):
        """
        * Saves the state of HP.THangman object to file
        * writes in binary mode and creates file if it doesn't exist
        """
        file = None
        try:
            file = open(self.dataPath + self.dataFile, 'bw+')
            pickle.dump(self.__hp, file)
        except IOError as e:
            print(f'Tapahtui virhe: {e}')
        finally:
            if file:
                file.close()

    def close(self):
        """
        * Called when main window's exit is pressed
        * Ask from user if one want's to save game before quitting
        """
        msg_box = messagebox.askquestion(
            "Save",
            "Do you want to save your game before closing?",
            icon='warning')
        if msg_box == "yes":
            self.serialize()
        self.destroy()

    def config(self, write=False):
        """
        * write=False:
            * creates new dir for data if there isn't one
            * creates new conf. file if there isn't one
            * returns level if write=False, default is 0
        * write=True:
            * writes level to conf. file
        """
        file = None
        level = None
        if not write:
            if not os.path.exists("data/"):
                os.makedirs("data")
            try:
                file = open(self.dataPath + self.configurationFile,
                            'r',
                            encoding="utf-8")
                for row in file:
                    row = row.strip()
                    if len(row) > 0:
                        level = int(row.split(":", 1)[1])
                file.close()
            except (FileNotFoundError, IOError):
                c = Classifier()
                c.read()
                c.classify()
                level = 0
                try:
                    file = open(self.dataPath + self.configurationFile,
                                'w',
                                encoding="utf-8")
                    file.write("level:" + str(level) + "\n")
                    file.close()
                except IOError as e:
                    print(
                        f'Tiedostoa {self.configurationFile} ei voitu luoda: {e}'
                    )
            finally:
                if file is not None:
                    file.close()
                return level
        else:
            try:
                file = open(self.dataPath + self.configurationFile,
                            'w',
                            encoding="utf-8")
                file.write("level:" + str(self.__hp.level) + '\n')
                file.close()
            except IOError as e:
                print(
                    f'Tiedostoon {self.configurationFile} ei voitu kirjoittaa: {e}'
                )
            finally:
                if file is not None:
                    file.close()

    def check(self, c_letter):
        """
        * every (wrong) or right guessed letter is worth (-)100 points.
        * e.g. guessable word includes three times letter 'A' -> only worth 100 points
        * if word is guessed right then 100*[length_of_word] is added to points
        * player can reach next level only then when word is guessed right and one has 10 000 or more points
        """
        letter = c_letter.lower()
        if letter not in self.__hp.corrects and letter not in self.__hp.missed:
            if self.__hp.check(letter):
                self.__hp.points += 100
                self.output.set(self.__hp.getLetters)
                if self.__hp.isWin():
                    self.__hp.points = 100 * len(
                        self.__hp.getWord) + self.__hp.points
                    self.Buttons.disableAll()
                    self.info.set("You guessed right, well done!!")
                    if self.__hp.points >= 10000:
                        self.__hp.newLevel()
                        self.config(True)
            else:
                self.__hp.points -= 100
                drawer = Drawer(self.turtle_screen, self.raw_turtle)
                step_to_draw = {
                    1: drawer.basement,
                    2: drawer.main_bar,
                    3: drawer.upper_bar,
                    4: drawer.rope,
                    5: drawer.head,
                    6: drawer.body,
                    7: drawer.left_foot,
                    8: drawer.right_foot,
                    9: drawer.left_arm,
                    10: drawer.right_arm
                }
                step_to_draw[len(self.__hp.missed)]()
                if len(self.__hp.missed) == len(step_to_draw):
                    self.info.set("HANGED! You failed to guess " +
                                  str(self.__hp.getWord))

    def new(self):
        self.__hp.reset()
        self.output.set(self.__hp.getLetters)
        self.Buttons.enableAll()
        self.info.set("")
        self.raw_turtle.reset()
        self.raw_turtle.hideturtle()
        self.raw_turtle.speed(0)
class HP(tk.Tk):
    """
    * In requirements analysis there was method called configure(). I used method called config(),
    * because tk has method configure and don't know if it's meant to override that method and don't know how to get
    * around this without overriding tk method..
    * Currently there might not be enough words in expert level to play the game through..
    """
    class THangman(Hangman):
        def __init__(self, parent):
            self.level = parent.config()
            self.points = 0
            self._Hangman__words = self.readWords()
            super().__init__()

        def readWords(self):
            """
            * Overrides Hangman class method to use Classifier class method 
            """
            c = Classifier()
            return c.readWords(self.level)

        def newLevel(self):
            """
            * game has levels 0-4. Method updates level to next one. If player is in level 4, next one is 0.
            * After the level is updated, corresponding words are read to attribute _Hangman__words
            """
            if self.level < 4:
                self.level += 1
                message = "Congratulations! You have reached new level. You are now at " + levels[
                    self.level] + " level"
                messagebox.showinfo("New level reached", message)
            else:
                self.level = 0
                message = "Congratulations! You are now master of Hangman game, a Yoda of words!. Game will now start" \
                          " again in the demonstration level"
                messagebox.showinfo("New level reached", message)
            self._Hangman__words = self.readWords()

    def __init__(self, title="Hangman"):
        super().__init__()
        self.title(title)
        self.geometry("720x600")
        self.configurationFile = "level.conf"
        self.__hp = HP.THangman(self)
        self.output = tk.StringVar()
        self.output.set(self.__hp.getLetters)
        self.info = tk.StringVar()
        alphabets = 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', \
                    'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'Å', 'Ä', 'Ö', '-'
        self.Buttons = ButtonsBlock(self, alphabets, 15)
        self.Buttons.grid(row=0, column=0, columnspan=3, padx=10, pady=5)

        self.frame2 = tk.Frame(self).grid(row=2)
        tk.Label(self.frame2, textvariable=self.output).grid(pady=10,
                                                             columnspan=5)

        self.frame3 = tk.Frame(self).grid(row=3)
        tk.Label(self.frame3, textvariable=self.info).grid(padx=10,
                                                           pady=10,
                                                           columnspan=5,
                                                           sticky=tk.W + tk.E)

        tk.Button(self, text="Start a new game",
                  command=self.new).grid(row=5,
                                         padx=30,
                                         pady=5,
                                         sticky=tk.E + tk.W,
                                         columnspan=5)
        self.canvas = Canvas(self, width=500, height=350)
        self.canvas.grid(row=8,
                         column=0,
                         columnspan=5,
                         padx=10,
                         sticky=tk.W + tk.E + tk.S + tk.N)
        self.turtle_screen = TurtleScreen(self.canvas)
        self.raw_turtle = RawTurtle(self.canvas)
        self.raw_turtle.hideturtle()
        self.raw_turtle.speed(0)
        message = "You are currently playing in " + levels[
            self.__hp.level] + " level"
        messagebox.showinfo("Level of difficulty", message)

    def config(self, write=False):
        file = None
        level = None
        if not write:
            try:
                file = open(self.configurationFile, 'r', encoding="utf-8")
                for row in file:
                    row = row.strip()
                    if len(row) > 0:
                        level = int(row.split(":", 1)[1])
                file.close()
            except (FileNotFoundError, IOError):
                c = Classifier()
                c.read()
                c.classify()
                level = 0
                try:
                    file = open(self.configurationFile, 'w', encoding="utf-8")
                    file.write("level:" + str(level) + "\n")
                    file.close()
                except IOError as e:
                    print(
                        f'Tiedostoa {self.configurationFile} ei voitu luoda: {e}'
                    )
            finally:
                if file is not None:
                    file.close()
                return level
        else:
            try:
                file = open(self.configurationFile, 'w', encoding="utf-8")
                file.write("level:" + str(self.__hp.level) + '\n')
                file.close()
            except IOError as e:
                print(
                    f'Tiedostoon {self.configurationFile} ei voitu kirjoittaa: {e}'
                )
            finally:
                if file is not None:
                    file.close()

    def check(self, c_letter):
        """
        * every (wrong) or right guessed letter is worth (-)100 points.
        * e.g. guessable word includes three times letter 'A' -> only worth 100 points
        * if word is guessed right then 100*[length_of_word] is added to points
        * player can reach next level only then when word is guessed right and one has 10 000 or more points
        """
        letter = c_letter.lower()
        if letter not in self.__hp.corrects and letter not in self.__hp.missed:
            if self.__hp.check(letter):
                self.__hp.points += 100
                self.output.set(self.__hp.getLetters)
                if self.__hp.isWin():
                    self.__hp.points = 100 * len(
                        self.__hp.getWord) + self.__hp.points
                    self.Buttons.disableAll()
                    self.info.set("You guessed right, well done!!")
                    if self.__hp.points >= 10000:
                        self.__hp.newLevel()
                        self.config(True)
            else:
                self.__hp.points -= 100
                drawer = Drawer(self.turtle_screen, self.raw_turtle)
                step_to_draw = {
                    1: drawer.basement,
                    2: drawer.main_bar,
                    3: drawer.upper_bar,
                    4: drawer.rope,
                    5: drawer.head,
                    6: drawer.body,
                    7: drawer.left_foot,
                    8: drawer.right_foot,
                    9: drawer.left_arm,
                    10: drawer.right_arm
                }
                step_to_draw[len(self.__hp.missed)]()
                if len(self.__hp.missed) == len(step_to_draw):
                    self.info.set("HANGED! You failed to guess " +
                                  str(self.__hp.getWord))

    def new(self):
        self.__hp.reset()
        self.output.set(self.__hp.getLetters)
        self.Buttons.enableAll()
        self.info.set("")
        self.raw_turtle.reset()
        self.raw_turtle.hideturtle()
        self.raw_turtle.speed(0)
Exemple #16
0
def ex59():
    canvas = Canvas(width=300, height=300, bg='green')
    canvas.pack(expand=YES, fill=BOTH)
    x0 = 150
    y0 = 100
    canvas.create_oval(x0 - 10, y0 - 10, x0 + 10, y0 + 10)
    canvas.create_oval(x0 - 20, y0 - 20, x0 + 20, y0 + 20)
    canvas.create_oval(x0 - 50, y0 - 50, x0 + 50, y0 + 50)
    B = 0.809
    for i in range(16):
        a = 2 * math.pi / 16 * i
        x = math.ceil(x0 + 48 * math.cos(a))
        y = math.ceil(y0 + 48 * math.sin(a) * B)
        canvas.create_line(x0, y0, x, y, fill='red')
    canvas.create_oval(x0 - 60, y0 - 60, x0 + 60, y0 + 60)

    for k in range(501):
        for i in range(17):
            a = (2 * math.pi / 16) * i + (2 * math.pi / 180) * k
            x = math.ceil(x0 + 48 * math.cos(a))
            y = math.ceil(y0 + 48 + math.sin(a) * B)
            canvas.create_line(x0, y0, x, y, fill='red')
        for j in range(51):
            a = (2 * math.pi / 16) * i + (2 * math.pi / 180) * k - 1
            x = math.ceil(x0 + 48 * math.cos(a))
            y = math.ceil(y0 + 48 * math.sin(a) * B)
            canvas.create_line(x0, y0, x, y, fill='red')
    mainloop()
            # remove cars that drove out of the scene
            if (car.pos_x < 0 or car.pos_x > width or car.pos_y < 0
                    or car.pos_y > height):
                cars.remove(car)

        canvas.update()
        time.sleep(0.01)


if __name__ == '__main__':
    root = Tk()

    # main global variables
    width = root.winfo_screenwidth()
    height = root.winfo_screenheight()
    roadWidth = 300

    #  canvas is a white piece of paper on which you can draw
    canvas = Canvas(root, width=width, height=height, bg="dimgrey")
    canvas.pack()

    # list of cars in the scene
    cars = []

    # run the simulation
    simulate_cars()

    # must be the last line before exit for TKinter
    root.mainloop()
Exemple #18
0
import math
import time

from tkinter import Tk
from turtle import Canvas

# Draw a Clock
# create the drawing system
root = Tk()

# main dimensions
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()

#  canvas is a white piece of paper on which you can draw
canvas = Canvas(root, width=screen_width, height=screen_height, bg="black")
canvas.pack()


def draw_hand(angle, someradius, some_thinkness, some_color):
    # this function draws a hand with a certain angle and radius
    canvas.create_line(
        screen_width / 2,  # x1
        screen_height / 2,  # y1
        screen_width / 2 + math.cos(angle) * someradius,  # x2
        screen_height / 2 + math.sin(angle) * someradius,  # y2
        width=some_thinkness,  # line thickness
        fill=some_color)  # line color


def draw_clock():
Exemple #19
0
            # remove cars that drove out of the scene
            if (car.pos_x < 0 or car.pos_x > width or car.pos_y < 0
                    or car.pos_y > height):
                cars.remove(car)

        canvas.update()
        time.sleep(0.01)


if __name__ == '__main__':
    root = Tk()

    # main global variables
    width = root.winfo_screenwidth()
    height = root.winfo_screenheight()
    roadWidth = 200

    #  canvas is a white piece of paper on which you can draw
    canvas = Canvas(root, width=width, height=height, bg="black")
    canvas.pack()

    # list of cars in the scene
    cars = []

    # run the simulation
    simulate_cars()

    # must be the last line before exit for TKinter
    root.mainloop()