Example #1
0
    def drawBoard(self, root):
        self.world = [-1, -1, 1, 1]
        self.bgcolor = "#F5E7C4"
        self.root = root
        self.pad = 25
        self._ALL = 'all'
        WIDTH, HEIGHT = 400, 400

        root.bind_all("<Escape>", lambda _: root.destroy())
        root.bind_all('<Key>', self.key)
        root.bind_all('<Button-1>', self.mouseClick)

        self.canvas = Canvas(
            root,
            width=WIDTH,
            height=HEIGHT,
            bg=self.bgcolor,
            bd=10,
        )

        # start the countdown clock
        self.clock = Countdown(10, self.canvas)
        self.root.title('Boggle')

        # draw the board
        self.paintgraphics()
        self.canvas.pack(fill=BOTH, expand=YES)
        self.refresh()
Example #2
0
  def drawBoard(self, root):
    self.world   = [-1, -1, 1, 1]
    self.bgcolor = "#F5E7C4"
    self.root    = root
    self.pad     = 25
    self._ALL    = 'all'
    WIDTH, HEIGHT = 400, 400
    
    root.bind_all("<Escape>", lambda _ : root.destroy())
    root.bind_all('<Key>', self.key)
    root.bind_all('<Button-1>', self.mouseClick)

    self.canvas = Canvas(root, 
        width = WIDTH, 
        height = HEIGHT, 
        bg = self.bgcolor,
        bd = 10,
      )
      
    # start the countdown clock
    self.clock = Countdown(10, self.canvas)
    self.root.title('Boggle')
    
    # draw the board
    self.paintgraphics()    
    self.canvas.pack(fill=BOTH, expand=YES)
    self.refresh()
Example #3
0
    def __init__(self,parent):
        #The frame instance is stored in a local variable 'f'.
        #After creating the widget, we immediately call the 
        #pack method to make the frame visible.
        
        f = Frame(parent)
        f.pack(padx=100,pady=50)
        self.f=f
        self.parent = parent
        # keep track of my player id
        self.myPid=None
        # keep track of the other players
        self.otherPlayers={}
        # keep track of the ip
        self.ip = "142.150.2.94"
        self.port = 1337
        self.gameCount = 0 
        self.playerName = "Player" + str(random.randint(1,100))
        #we then create an entry widget,pack it and then 
        #create two more button widgets as children to the frame.
        self.name = Label(f, text="Your Name:", font=("Helvetica", 15))
        self.name.pack(side=TOP)

        self.nameE = Entry(f, width=15)
        self.nameE.insert(0, self.playerName)
        self.nameE.pack(side=TOP,padx=5,pady=5)

        self.startBtn = Button(f, text="Join Game", command=self.setupChat)
        self.startBtn.pack(side=TOP,padx=10,pady=10)

        menubar = Menu(root)

        # create more pulldown menus
        editmenu = Menu(menubar, tearoff=0)
        editmenu.add_command(label="Restart", command=self.restartGame)
        editmenu.add_command(label="Settings", command=self.settings)
        editmenu.add_command(label="Quit", command=self.onClose)
        menubar.add_cascade(label="Game", menu=editmenu)

        self.parent.config(menu=menubar)

        self.listall = None

        #make the player client thread
        self.myListener = None
        self.parent.protocol('WM_DELETE_WINDOW', self.onClose)

        #make an instance of the counter but do not start it
        self.counter = Countdown(5)
        self.counter.addObserver(self)
def Init():
    global ScriptSettings
    ScriptSettings = Settings(SettingsFile)
    ScriptSettings.Save(SettingsFile)

    global BanWordReward
    BanWordReward = BanWord.BanWord(ScriptName, Parent,
                                    ScriptSettings.EnableDebug)

    global CountdownReward
    CountdownReward = Countdown.Countdown(ScriptName, Parent,
                                          ScriptSettings.EnableDebug)

    global AlertReward
    AlertReward = Alert.Alert(ScriptName, Parent, ScriptSettings.EnableDebug)

    return
    while mode == "ready2":
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()

        mode = "countdown"
        # pygame.time.delay(500)
        voiceCount.play(1)
        voiceCount.fadeout(3300)

        dirty = all.draw(screen)
        pygame.display.update(dirty)
        pygame.display.flip()
        clock.tick(60)

    cd = Countdown()
    print "counting down"
    while mode == "countdown":
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
        all.update()
        if cd.done:
            mode = "secret"
        dirty = all.draw(screen)
        pygame.display.update(dirty)
        pygame.display.flip()
        clock.tick(60)

    bg.kill()
    bg = Background("Screen Display/Background/images/space.png")
Example #6
0
 def Countdown(self):
     return countdown.Countdown(self.contract)
Example #7
0
def main():
    print "Reading argument list:"

    usage = "python " + sys.argv[
        0] + """ directory1 directory2 ... OR you can use the -m option to provide a multicrab file; furthermore -r allows resubmission and -t kills the initial timeout"""

    parser = OptionParser(usage=usage, version="%prog 0.1")
    parser.add_option("-r",
                      "--resubmit",
                      action="store_true",
                      dest="doresubmit",
                      default=False,
                      help="If activated, resubmits failed and aborted jobs")
    parser.add_option(
        "-t",
        "--notimeout",
        action="store_true",
        dest="notimeout",
        default=False,
        help="Eliminates, if activated, the initial timeout of 2 min")
    parser.add_option("-m",
                      "--multicrab",
                      action="store_true",
                      dest="multicrab",
                      default=False,
                      help="Read entries from multicrab.cfg file")
    (options, args) = parser.parse_args()

    global DoResubmit
    DoResubmit += options.doresubmit
    print "Overview of running options: "
    print "    Allow to resubmit?   " + str(
        int(DoResubmit)) + "    (option r = resubmit)"
    print "    Disable timeout ?    " + str(int(
        options.notimeout)) + "    (option t = no timeout)"
    print "    Read from multicrab? " + str(int(
        options.multicrab)) + "    (option m = read from multicrab file) \n"

    for arg in args:
        if os.path.isdir(arg) and os.path.isfile(
                arg + "/share/default.tgz"
        ):  # making sure that the directory exists and that it is a crab job
            JobDatabase[arg] = {}
            TaskDatabase[arg] = {}
        else:
            print "The supplied argument " + arg + " is not a valid task; it will not be considered. \n"

    if options.multicrab:
        ReadFromMulticrab()

    if len(TaskDatabase) < 1:
        print "No valid tasks have been found. Try again."
        sys.exit(-1)

    print "The following tasks are going to get checked:"
    taskCounter = 0
    for task in TaskDatabase:
        taskCounter += 1
        print str(taskCounter) + " ) " + task

    if not options.notimeout == True:
        print "\n"
        Countdown(120)

    for i in range(0, 3 * 24 * 60 / CheckInterval):  #check for up to 3 days
        print "\n"
        print " \033[1m ***************************************************************************** \033[0m "
        d = datetime.now()
        print
        print "                          Check #" + str(
            i + 1) + "   (at " + str(d.hour) + ":" + str(d.minute) + ":" + str(
                d.second) + "  on  " + str(d.month) + " / " + str(
                    d.day) + " / " + str(d.year) + "\n\n"

        for task in TaskDatabase:
            process_job(task)
        print "\n\n\n"
        print "     Check summary: "
        for task in TaskDatabase:
            if "nJobs" in TaskDatabase[
                    task] and TaskDatabase[task]["nJobs"] > 0:
                print "        " + task + " : " + str(
                    100 * TaskDatabase[task]["NJobsPleasingCRAB"] /
                    float(TaskDatabase[task]["nJobs"])) + " % done"
            else:
                print "        " + task + " : experienced problems while retrieving information"
        print "\n\n\n"
        Countdown(CheckInterval * 60)
Example #8
0
class Boggle:
    def __init__(self, root):
        self.upd = 0
        self.roots = {}
        self.guess = []
        self.guessList = []
        self.stopClock = False
        self.play = True

        #define color scheme
        self.black = "#0B0E06"
        self.lyellow = "#F1D58A"
        self.yellow = "#E7C963"
        self.ygreen = "#A6AE33"
        self.orange = "#C67822"
        self.blue = "#438288"
        self.green = "#4D793F"
        self.dgreen = "#5C5E21"

        # build the dictionary of words
        self.readfile("dictionary.txt")
        unplayable = True

        # keep track of how many boards were tried
        newBoardstat = 0

        while unplayable:
            #holds a double array of tile objects
            self.grid = defaultdict(lambda: defaultdict(list))
            self.grid = self.randomBoard()

            # list for all possible words on the board
            self.foundWords = []

            for i in range(5):
                for j in range(5):
                    #print self.grid[i][j].letter
                    self.findWords("", None, i, j)

            # if there are not at least 20 possible words
            # create a different board
            if len(self.foundWords) > 20:
                unplayable = False
            else:
                newBoardstat += 1
                self.foundWords = []

        # put the list in alphabetical order
        self.foundWords.sort()

        print "Tried %d" % newBoardstat + " board(s) before this one."

        # temporary, to see all possible words
        #for i in self.foundWords:
        #print i

        # create the board
        self.drawBoard(root)

    # method for reading in lines of a given filename
    def readfile(self, filename):
        file = open(filename, 'r')
        # uppercase letters to standardize and strip newlines
        line = file.readline().upper().strip()
        while line:
            self.insert(line)
            line = file.readline().upper().strip()
        file.close()

    # insert a word into the dictionary
    def insert(self, line):
        # if the root node doesn't exist yet, add it
        if not self.roots.has_key(line[0]):
            self.roots[line[0]] = TrieNode(line[0])
            #print "add "+self.roots[line[0]].letter+" to dictionary"
        #else:
        #print line[0]+" already exists in dictionary"
        # insert the rest of the word, send the root node and rest of word
        self.insertWord(line[1:], self.roots[line[0]])

    # recursive method that inserts new word into trie tree
    def insertWord(self, word, node):
        #each node has children nodes to build diff words
        #check if children nodes contain next letter
        if node.children.has_key(word[0]):
            nextChild = node.children.get(word[0])
        else:
            nextChild = TrieNode(word[0])
            #print "add "+nextChild.letter
            node.children[word[0]] = nextChild

        if len(word) == 1:
            nextChild.fullWord = True
        else:
            self.insertWord(word[1:], nextChild)

    # depth first search starting with cell (i, j)
    def findWords(self, prefix, node, row, col):
        # add the next letter we're trying
        prefix = prefix + self.grid[row][col].letter

        if row < 0 or col < 0 or row >= 5 or col >= 5:
            #system out of bounds
            #print "System out of bounds"
            return

        if self.grid[row][col].visited:
            #already visited, can't visit more than once
            return

        # tile is visited
        self.grid[row][col].visited = True

        # get the first node for the root layer
        if len(prefix) == 1 and prefix[0] in self.roots:
            # grab root node for first letter
            node = self.roots[prefix[0]]

        if not self.grid[row][col].letter in node.children and len(prefix) > 1:
            self.grid[row][col].visited = False
            return
        else:
            if len(prefix) > 1 and self.grid[row][col].letter in node.children:
                node = node.children[self.grid[row][col].letter]

        # words must be at least 3 long, a full word, and not in list
        if len(prefix) > 2 and node.fullWord:
            if not prefix in self.foundWords:
                self.foundWords.append(prefix)

        for a in range(-1, 2):
            for b in range(-1, 2):
                nrow = row + a
                ncol = col + b
                if nrow >= 0 and ncol >= 0 and nrow < 5 and ncol < 5 and math.fabs(
                        a) != math.fabs(b):
                    self.findWords(prefix, node, nrow, ncol)

        self.grid[row][col].visited = False

    # contains instructions for drawing the boggle board
    def drawBoard(self, root):
        self.world = [-1, -1, 1, 1]
        self.bgcolor = "#F5E7C4"
        self.root = root
        self.pad = 25
        self._ALL = 'all'
        WIDTH, HEIGHT = 400, 400

        root.bind_all("<Escape>", lambda _: root.destroy())
        root.bind_all('<Key>', self.key)
        root.bind_all('<Button-1>', self.mouseClick)

        self.canvas = Canvas(
            root,
            width=WIDTH,
            height=HEIGHT,
            bg=self.bgcolor,
            bd=10,
        )

        # start the countdown clock
        self.clock = Countdown(10, self.canvas)
        self.root.title('Boggle')

        # draw the board
        self.paintgraphics()
        self.canvas.pack(fill=BOTH, expand=YES)
        self.refresh()

    def refresh(self):
        self.upd += 1
        if self.upd % 10 == 0: self.upd = 0
        self.redraw(self.upd)
        # redraw screen at faster rate for smoother interface
        if self.play: self.root.after(100, self.refresh)

    def redraw(self, sec):
        self.canvas.delete(self._ALL)

        # only decrement after a full second passes
        if self.clock.remaining > 0 and sec == 0 and not self.stopClock:
            self.clock.remaining -= 1

        if self.play and self.clock.remaining < 1:
            self.scoreBoard()

        if self.clock.remaining < 1:
            self.stopClock = True
            self.play = False

        if self.stopClock:
            self.clock.remaining = 0
            self.play = False

        self.clock.countdown()
        self.paintgraphics()

    # draw letters on the board
    def paintgraphics(self):
        # mac and windows size differently
        if platform.system() == "Windows":
            self.text_size = 20
        else:
            self.text_size = 35

        actfill = self.black
        if self.play:
            actfill = self.orange

        # 25px padding from edges
        r, c = 30, 30
        for i in range(5):
            for j in range(5):
                # draw letter on the canvas
                self.canvas.create_text(
                    r,
                    c,
                    text=self.grid[i][j].letter,
                    fill=self.grid[i][j].color,
                    activefill=actfill,
                    font="Arial %d bold" % self.text_size,
                )
                self.grid[i][j].x, self.grid[i][j].y = r, c

                # increment row
                r += 65
            # increment column outside first loop
            c += 65
            # reset to first row
            r = 30

        if self.play:
            act2fill = actfill
            fillclr = self.green
            button_text = "Submit\n Word"
            button_text2 = "Possible: %d" % len(self.foundWords)
        else:
            act2fill = self.orange
            fillclr = self.orange
            button_text = "Play\nAgain?"
            button_text2 = "Found %d\nout of %d\npossible words" % (len(
                self.guessList), len(self.foundWords))

        self.canvas.create_rectangle(160,
                                     335,
                                     250,
                                     395,
                                     fill=fillclr,
                                     outline=self.dgreen,
                                     activefill=act2fill)

        self.canvas.create_text(175,
                                365,
                                font="Arial %d bold" % (self.text_size / 2),
                                anchor="w",
                                text=button_text)

        self.canvas.create_text(260,
                                350,
                                font="Helvetica %d bold" %
                                (self.text_size / 2),
                                fill="#CFA130",
                                anchor="w",
                                text=button_text2)

        # print user's found words
        if self.guessList:
            coorx, coory = 340, 25
            spaceH = 335
            pad = len(self.foundWords) * 2
            fontsize = (spaceH - pad) / len(self.foundWords)
            #print "%d minus %d divided by %d = %d" %(spaceH, pad, len(self.foundWords), fontsize)
            for word in self.guessList:
                self.canvas.create_text(coorx,
                                        coory,
                                        text=word.lower(),
                                        anchor="w",
                                        fill="black",
                                        font="Arial %d" % (fontsize))
                coory += fontsize + 5

    #reads in user input
    def key(self, event):
        if event.keysym == 'Return' and self.play:
            self.tryWord()

        for i in range(5):
            for j in range(5):
                if self.grid[i][j].letter.lower() == event.keysym.lower(
                ) and self.play:
                    self.buildWord(i, j)

    def mouseClick(self, mouseevent):
        # only process mouse clicks if it falls within the board
        if mouseevent.x < 315 and mouseevent.y < 315 and self.play:
            self.mouseWord(mouseevent.x, mouseevent.y)

        if mouseevent.x > 160 and mouseevent.x < 250 and mouseevent.y > 335 and mouseevent.y < 395:
            if self.play:
                self.tryWord()
            else:
                self.restartGame(self.root)

    def mouseWord(self, x, y):
        # map mouse clicks to a particular letter
        for i in range(5):
            for j in range(5):
                if x >= (self.grid[i][j].x -
                         5) and x <= (self.grid[i][j].x + 25) and y >= (
                             self.grid[i][j].y -
                             15) and y <= (self.grid[i][j].y + 15):
                    self.buildWord(i, j)

    def buildWord(self, r, c):
        # check if it's first selected or near last selected
        if not self.guess:
            self.guess.append(self.grid[r][c])
            self.grid[r][c].select(True)
        else:
            nrow = math.fabs(self.grid[r][c].row -
                             self.guess[len(self.guess) - 1].row)
            ncol = math.fabs(self.grid[r][c].column -
                             self.guess[len(self.guess) - 1].column)
            if nrow < 2 and ncol < 2 and nrow != ncol and not self.find(
                    self.grid[r][c], self.guess):
                self.guess.append(self.grid[r][c])
                self.grid[r][c].select(True)

    def find(self, f, seq):
        try:
            return (seq.index(f) + 1)
        except:
            return False

    def tryWord(self):
        # user has hit the submit button
        word = ""
        for l in self.guess:
            word = word + l.letter
            l.select(False)

        # if the word is less than 3 characters long: ERROR
        if len(word) < 3:
            tkMessageBox.showinfo(
                title="ERROR",
                message="Words must be longer than 2 characters.")
        # if the word does not exist on the board: ERROR
        elif not self.find(word, self.foundWords):
            tkMessageBox.showinfo(title="ERROR",
                                  message=word + " is not a word.")
        # if the word has already been found: ERROR
        elif self.find(word, self.guessList):
            tkMessageBox.showinfo(title="ERROR",
                                  message=word + " has already been found.")
        # else add to the guessList
        else:
            self.guessList.append(word)

        # reinitialize guess to empty
        self.guess = []

        # check if all words have been found
        if len(self.guessList) == len(self.foundWords):
            print "all words have been found"
            self.stopClock = True
            self.scoreBoard()

    def randomBoard(self):
        board = defaultdict(lambda: defaultdict(list))
        alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        alpha = 26
        boardl = 25
        row, col = 0, 0

        while boardl > 0:
            r = random.randrange(alpha)
            a = alphabet[r]
            board[row][col] = Tile(a, row, col)
            alphabet = alphabet.replace(a, "")
            col += 1

            if col >= 5:
                col = 0
                row += 1

            alpha -= 1
            boardl -= 1

        return board

    def scoreBoard(self):
        self.score = 0
        for word in self.guessList:
            if len(word) > 7: self.score += 11
            elif len(word) == 7: self.score += 5
            elif len(word) == 6: self.score += 3
            elif len(word) == 5: self.score += 2
            elif len(word) < 5: self.score += 1

        print self.score

        self.play = False
        self.redraw(0)

    def restartGame(self, root):
        #restart the game somehow
        print "here"
Example #9
0
class App(Observer):
    def __init__(self,parent):
        #The frame instance is stored in a local variable 'f'.
        #After creating the widget, we immediately call the 
        #pack method to make the frame visible.
        
        f = Frame(parent)
        f.pack(padx=100,pady=50)
        self.f=f
        self.parent = parent
        # keep track of my player id
        self.myPid=None
        # keep track of the other players
        self.otherPlayers={}
        # keep track of the ip
        self.ip = "142.150.2.94"
        self.port = 1337
        self.gameCount = 0 
        self.playerName = "Player" + str(random.randint(1,100))
        #we then create an entry widget,pack it and then 
        #create two more button widgets as children to the frame.
        self.name = Label(f, text="Your Name:", font=("Helvetica", 15))
        self.name.pack(side=TOP)

        self.nameE = Entry(f, width=15)
        self.nameE.insert(0, self.playerName)
        self.nameE.pack(side=TOP,padx=5,pady=5)

        self.startBtn = Button(f, text="Join Game", command=self.setupChat)
        self.startBtn.pack(side=TOP,padx=10,pady=10)

        menubar = Menu(root)

        # create more pulldown menus
        editmenu = Menu(menubar, tearoff=0)
        editmenu.add_command(label="Restart", command=self.restartGame)
        editmenu.add_command(label="Settings", command=self.settings)
        editmenu.add_command(label="Quit", command=self.onClose)
        menubar.add_cascade(label="Game", menu=editmenu)

        self.parent.config(menu=menubar)

        self.listall = None

        #make the player client thread
        self.myListener = None
        self.parent.protocol('WM_DELETE_WINDOW', self.onClose)

        #make an instance of the counter but do not start it
        self.counter = Countdown(5)
        self.counter.addObserver(self)

    def settings(self):
        ''' Handle the GUI for the settings page '''
        self.settingsDialog = Tk()
        self.settingsDialog.title('Frogger Settings')

        labelframe = LabelFrame(self.settingsDialog, text="Server Connection Settings")
        labelframe.pack(fill="both", expand="yes")

        f = Frame(self.settingsDialog)
        f.pack()

        # set the ip address
        ipaddress = Label(labelframe, text="Server ip:")
        ipaddress.grid(row=1, column=0, sticky=E)

        self.inp = Entry(labelframe, width=15)
        self.inp.insert(0, self.ip)
        self.inp.grid(row=1, column=1, sticky=E)

        port = Label(labelframe, text="Server port:")
        port.grid(row=2, column=0, sticky=W)

        self.pinp = Entry(labelframe, width=10)
        self.pinp.insert(0, self.port)
        self.pinp.grid(row=2, column=1, sticky=W)

        savebtn = Button(labelframe, text="Save")
        savebtn.grid(row=3, column=1, sticky=W)
        savebtn.bind('<Button-1>',self.saveServer)

        RWidth= 300
        RHeight= 100
        self.settingsDialog.geometry(("%dx%d")%(RWidth,RHeight))
        self.settingsDialog.mainloop()

    def saveServer(self, e):
        '''Save the ip address and port from settings dialog'''
        try:
            self.ip = self.inp.get()
            self.port = self.pinp.get()
            self.settingsDialog.destroy()
        except Exception as e:
            print("Error reading ip")


    def closeDialog(self):
        ''' Close the dialog for the settings '''
        try:
            self.settingsDialog.destroy()
        except Exception as e:
            print("Error closing dialog")

    def onClose(self):
        ''' handle the parent and GUI on close '''
        if self.myListener!=None:
            self.myListener.disconnect()
        self.parent.quit()
        self.parent.destroy()
        sys.exit()

    def callback(self,e):
        ''' after user enters name into the main page '''
        if(self.nameE.get()!=''):
            self.playerName=self.nameE.get()
            self.button1.pack_forget()
            self.button2.pack_forget()
            self.button3.pack_forget()
            self.exit.pack_forget()
            self.setupChat(e)

    def setupChat(self,e=None):
        ''' Setup the chat GUI '''
        self.playerName = self.nameE.get()
        #setup listener
        if self.myListener is None:
            self.myListener = PlayerClient(self.playerName, self.ip, self.port)
            self.myListener.start()
            self.myListener.addObserver(self)
            self.myListener.clearChanged()

        # forget the last frame
        self.f.pack_forget()
        self.fr = Frame(self.parent)

        # init the elements for the GUI
        self.textbox = Text(self.fr, height=20, width=70, wrap=WORD, state=DISABLED)
        self.textbox.grid(row=0, column=0, sticky=W)
        self.scroll = Scrollbar(self.fr)
        self.textbox.config(yscrollcommand=self.scroll.set)

        self.scroll.config(command=self.textbox.yview)
        self.v = StringVar()
        self.inp = Entry(self.fr, width=55, textvariable=self.v)
        self.inp.grid(row=1, column=0, sticky=W)
        self.send = Button(self.fr, text="send")
        self.send.grid(row=1, column=0, sticky=E)
        self.listall = Listbox(self.fr)
        self.listall.grid(row=0, column=1, sticky=N)
        self.time = Label(self.fr, text="", font=("Helvetica", 50))
        self.time.grid(row=0, column=1, sticky=S)

        self.restartbtn = Button(self.fr, text="restart")
        self.restartbtn.grid(row=1, column=1, sticky=S)

        # bind the keys to callback functions
        self.send.bind('<Button-1>', self.sendtext)
        self.inp.bind('<Return>', self.sendtext)
        self.restartbtn.bind('<Button-1>', self.restartGame)
        
        self.fr.pack()
        self.updatelistall(self.playerName)
        
    def sendtext(self,e):
        ''' handle sending text to all the players  '''
        self.textbox.yview(END) 
        if(self.inp.get()!=''):
            self.textbox.config(state=NORMAL)
            self.textbox.insert(END, self.playerName+'> '+self.inp.get().strip(' ')+ '\n')


            #send the message to all players
            if self.myListener is not None:
                self.myListener.send(MsgCommand.encode('MSG', self.playerName, self.inp.get().strip(' ')))
                
            self.textbox.config(state=DISABLED)
            self.v.set('')
            self.fr.update_idletasks()
    
    def updatelistall(self,name):
        ''' update the player list in chat '''
        try:
            self.listall.insert(END,name)
            self.fr.update_idletasks()
        except Exception as e:
            print("Error updating listall: ", e)

    def restartGame(self, e):
        ''' take user back to old view '''
        self.fr.destroy()
        self.f.pack()

    def update(self, listener):
        ''' update function that is used to notify every one '''
        try:
            if listener.data is not None:
                commands = listener.data.decode().splitlines()
                for cmd in commands:
                    cmd = Command.decode(cmd)
                    if cmd["CMD"].strip() == "MSG":
                        # Message command coming in, insert into textarea
                        self.textbox.config(state=NORMAL)
                        self.textbox.insert(END, cmd["pname"] + "> " + cmd["msg"] + '\n')
                        self.textbox.config(state=DISABLED)
                        self.textbox.yview(END)
                        self.fr.update_idletasks()
                    elif cmd["CMD"].strip() == "ACK":
                    # ACK command coming in, send Join command out
                        self.myPid=cmd['pid']
                        self.myListener.send(JoinCommand.encode('JOIN',self.myPid,self.playerName))
                        
                    elif cmd["CMD"].strip() == "EXIST":
                    # Exist command coming in, making sure that others exist in chat area
                        print(str(self.playerName) + " GOT EXIST >> ")
                        k = list(self.otherPlayers.keys())
                        if(cmd['pid'] not in k):
                            self.otherPlayers[cmd['pid']]=cmd['pname']
                            self.updatelistall(cmd['pname'])
                            # play the game if 3 players are present
                        if len(self.otherPlayers.keys())==2 and self.counter.started == False:
                            self.counter.start()
                            
                    elif cmd["CMD"].strip() == "JOIN":
                    # Join command coming in
                        print(str(self.playerName) + " GOT JOIN >> ")
                        self.otherPlayers[cmd['pid']]=cmd['pname']
                        self.updatelistall(cmd['pname'])
                        self.myListener.send(JoinCommand.encode('EXIST',self.myPid,self.playerName))
                        
                        if len(self.otherPlayers.keys())==2 and self.counter.started == False:
                            self.counter.start()

                    elif cmd["CMD"].strip() == "DC":
                    # Disconnect Command coming in
                        print("Got a disconnect")
                        k = list(self.otherPlayers.keys())
                        if(str(cmd['pid']) in k):
                            del self.otherPlayers[str(cmd['pid'])]

                        self.listall.delete(1, END)
                        for k,v in self.otherPlayers.items():
                            self.updatelistall(v)

                    elif cmd["CMD"].strip() == "COUNT":
                    # Count command, meaning we should count down and run the game
                        self.time.config(text=cmd["count"])
                        self.gameCount = 0
                        if(cmd['count'] == 0):
                            self.myGame=FroggerRun(self.myPid,list(self.otherPlayers.keys()),self.myListener)
                            self.myGame.start()

                    elif cmd["CMD"].strip() == "END":
                        # END command that tells us that game is over
                        if self.gameCount == 0:

                            self.myGame._can_quit=True
                            self.textbox.config(state=NORMAL)
                            # check to see if theres no winner
                            if cmd["winnerPid"] == None:
                                self.textbox.insert(END, "EVERYBODY LOST :( !" + '\n')
                            elif self.myPid == str(cmd["winnerPid"]):
                            # check if i'm the winner
                                self.textbox.insert(END, self.playerName +  " WON!" + '\n')
                            else:
                            # someone else is the winner
                                self.textbox.insert(END, str(self.otherPlayers[str(cmd["winnerPid"])]) +  " WON!" + '\n')

                            ##self.textbox.insert(END, str(cmd["winnerPid"]) +  " WON!" + '\n')
                            self.textbox.config(state=DISABLED)
                            self.textbox.yview(END)
                            self.fr.update_idletasks()
                            self.gameCount += 1

        except Exception as e:
            print("An error occurred while parsing Command: ", e)
Example #10
0
class Boggle:
  
  def __init__(self, root):
    self.upd = 0
    self.roots = {}
    self.guess = []
    self.guessList = []
    self.stopClock = False
    self.play = True

    #define color scheme
    self.black   = "#0B0E06"
    self.lyellow = "#F1D58A"
    self.yellow  = "#E7C963"
    self.ygreen  = "#A6AE33"
    self.orange  = "#C67822"
    self.blue    = "#438288"
    self.green   = "#4D793F"
    self.dgreen  = "#5C5E21"
    
    # build the dictionary of words
    self.readfile("dictionary.txt")
    unplayable = True
    
    # keep track of how many boards were tried
    newBoardstat = 0
    
    while unplayable:
      #holds a double array of tile objects
      self.grid = defaultdict(lambda : defaultdict(list))
      self.grid      = self.randomBoard()
    
      # list for all possible words on the board
      self.foundWords = []
    
      for i in range(5):
        for j in range(5):
          #print self.grid[i][j].letter
          self.findWords("", None, i, j)
    
      # if there are not at least 20 possible words
      # create a different board
      if len(self.foundWords) > 20:
        unplayable = False
      else:
        newBoardstat += 1
        self.foundWords = []
        
    # put the list in alphabetical order    
    self.foundWords.sort()
    
    print "Tried %d" % newBoardstat + " board(s) before this one."
    
    # temporary, to see all possible words
    #for i in self.foundWords:
      #print i
    
    # create the board
    self.drawBoard(root)
    
  # method for reading in lines of a given filename  
  def readfile(self, filename):
    file = open(filename, 'r')
    # uppercase letters to standardize and strip newlines
    line = file.readline().upper().strip()
    while line:
        self.insert(line)
        line = file.readline().upper().strip()
    file.close()
    
  # insert a word into the dictionary  
  def insert(self, line):
    # if the root node doesn't exist yet, add it
    if not self.roots.has_key(line[0]):
      self.roots[line[0]] = TrieNode(line[0])
      #print "add "+self.roots[line[0]].letter+" to dictionary"
    #else:
      #print line[0]+" already exists in dictionary"
    # insert the rest of the word, send the root node and rest of word  
    self.insertWord(line[1:], self.roots[line[0]])
    
  # recursive method that inserts new word into trie tree  
  def insertWord(self, word, node):
    #each node has children nodes to build diff words
    #check if children nodes contain next letter
    if node.children.has_key(word[0]):
      nextChild = node.children.get(word[0])
    else:
      nextChild = TrieNode(word[0])
      #print "add "+nextChild.letter
      node.children[word[0]] = nextChild
      
    if len(word) == 1:
      nextChild.fullWord = True
    else:
      self.insertWord(word[1:], nextChild)
      
  # depth first search starting with cell (i, j)
  def findWords(self, prefix, node, row, col):
    # add the next letter we're trying
    prefix = prefix + self.grid[row][col].letter
      
    if row < 0 or col < 0 or row >= 5 or col >= 5:
      #system out of bounds
      #print "System out of bounds"
      return
    
    if self.grid[row][col].visited:
      #already visited, can't visit more than once
      return
    
    # tile is visited  
    self.grid[row][col].visited = True
    
    # get the first node for the root layer
    if len(prefix) == 1 and prefix[0] in self.roots:
      # grab root node for first letter
      node = self.roots[prefix[0]]
      
    if not self.grid[row][col].letter in node.children and len(prefix) > 1:
      self.grid[row][col].visited = False
      return
    else:
      if len(prefix) > 1 and self.grid[row][col].letter in node.children:
        node = node.children[self.grid[row][col].letter]
      
    # words must be at least 3 long, a full word, and not in list  
    if len(prefix) > 2 and node.fullWord:
      if not prefix in self.foundWords:
        self.foundWords.append(prefix)
          
    for a in range(-1, 2):
      for b in range(-1, 2):
        nrow = row+a
        ncol = col+b
        if nrow >= 0 and ncol >= 0 and nrow < 5 and ncol < 5 and math.fabs(a) != math.fabs(b):
          self.findWords(prefix, node, nrow, ncol)
    
    self.grid[row][col].visited = False
      
  # contains instructions for drawing the boggle board  
  def drawBoard(self, root):
    self.world   = [-1, -1, 1, 1]
    self.bgcolor = "#F5E7C4"
    self.root    = root
    self.pad     = 25
    self._ALL    = 'all'
    WIDTH, HEIGHT = 400, 400
    
    root.bind_all("<Escape>", lambda _ : root.destroy())
    root.bind_all('<Key>', self.key)
    root.bind_all('<Button-1>', self.mouseClick)

    self.canvas = Canvas(root, 
        width = WIDTH, 
        height = HEIGHT, 
        bg = self.bgcolor,
        bd = 10,
      )
      
    # start the countdown clock
    self.clock = Countdown(10, self.canvas)
    self.root.title('Boggle')
    
    # draw the board
    self.paintgraphics()    
    self.canvas.pack(fill=BOTH, expand=YES)
    self.refresh()
    
  def refresh(self):
    self.upd += 1
    if self.upd%10 == 0: self.upd = 0
    self.redraw(self.upd)
    # redraw screen at faster rate for smoother interface
    if self.play: self.root.after(100,self.refresh)

  def redraw(self, sec):
    self.canvas.delete(self._ALL)

    # only decrement after a full second passes
    if self.clock.remaining > 0 and sec == 0 and not self.stopClock:
      self.clock.remaining -= 1
      
    if self.play and self.clock.remaining < 1:
      self.scoreBoard()
      
    if self.clock.remaining < 1:
      self.stopClock = True
      self.play = False
      
    if self.stopClock:
      self.clock.remaining = 0
      self.play = False

    self.clock.countdown()
    self.paintgraphics()

  # draw letters on the board
  def paintgraphics(self):
    # mac and windows size differently
    if platform.system() == "Windows":
      self.text_size=20
    else:
      self.text_size=35
      
    actfill = self.black  
    if self.play:
      actfill = self.orange
      
    # 25px padding from edges
    r, c = 30, 30
    for i in range(5):
      for j in range(5):
        # draw letter on the canvas
        self.canvas.create_text(r, c, 
            text=self.grid[i][j].letter, 
            fill=self.grid[i][j].color, 
            activefill=actfill,
	    font="Arial %d bold" % self.text_size,
        )
        self.grid[i][j].x, self.grid[i][j].y = r, c

        # increment row
        r += 65
      # increment column outside first loop  
      c += 65
      # reset to first row
      r = 30

    if self.play:
      act2fill    = actfill
      fillclr     = self.green
      button_text = "Submit\n Word"
      button_text2= "Possible: %d" % len(self.foundWords)
    else:
      act2fill    = self.orange
      fillclr     = self.orange
      button_text = "Play\nAgain?"
      button_text2= "Found %d\nout of %d\npossible words" % (len(self.guessList), len(self.foundWords))
        
    self.canvas.create_rectangle(160, 335, 250, 395, 
	  fill=fillclr, outline=self.dgreen, 
	  activefill=act2fill
	)
	  
    self.canvas.create_text(175, 365, 
	  font="Arial %d bold" % (self.text_size/2),
	  anchor="w", 
	  text=button_text
	)
	
    self.canvas.create_text(260, 350,
      font="Helvetica %d bold" % (self.text_size/2),
      fill="#CFA130",
      anchor="w",
      text=button_text2
    )

    # print user's found words
    if self.guessList:
	  coorx, coory = 340, 25
	  spaceH = 335
	  pad = len(self.foundWords) * 2
	  fontsize = (spaceH - pad)/len(self.foundWords)
	  #print "%d minus %d divided by %d = %d" %(spaceH, pad, len(self.foundWords), fontsize)
	  for word in self.guessList:
	    self.canvas.create_text(coorx, coory,
          text=word.lower(),
          anchor="w",
		  fill="black",
		  font="Arial %d" % (fontsize)
		)
	    coory += fontsize+5

  #reads in user input
  def key(self, event):
    if event.keysym == 'Return' and self.play:
      self.tryWord()

    for i in range(5):
      for j in range(5):
        if self.grid[i][j].letter.lower() == event.keysym.lower() and self.play:
	  self.buildWord(i, j)

  def mouseClick(self, mouseevent):
    # only process mouse clicks if it falls within the board
    if mouseevent.x < 315 and mouseevent.y < 315 and self.play:
      self.mouseWord(mouseevent.x, mouseevent.y)

    if mouseevent.x > 160 and mouseevent.x < 250 and mouseevent.y > 335 and mouseevent.y < 395:
      if self.play:
        self.tryWord()
      else:
        self.restartGame(self.root)

  def mouseWord(self, x, y):
    # map mouse clicks to a particular letter
    for i in range(5):
      for j in range(5):
        if x >= (self.grid[i][j].x-5) and x <= (self.grid[i][j].x+25) and y >= (self.grid[i][j].y-15) and y <= (self.grid[i][j].y+15):
	  self.buildWord(i, j)

  def buildWord(self, r, c):
    # check if it's first selected or near last selected
    if not self.guess:
      self.guess.append(self.grid[r][c])
      self.grid[r][c].select(True)
    else:
      nrow = math.fabs(self.grid[r][c].row - self.guess[len(self.guess)-1].row)
      ncol = math.fabs(self.grid[r][c].column - self.guess[len(self.guess)-1].column)
      if nrow < 2 and ncol < 2 and nrow != ncol and not self.find(self.grid[r][c], self.guess):
        self.guess.append(self.grid[r][c])
        self.grid[r][c].select(True)

  def find(self, f, seq):
    try:
      return (seq.index(f)+1)      
    except:
      return False

  def tryWord(self):
    # user has hit the submit button
    word = ""
    for l in self.guess:
      word = word + l.letter
      l.select(False)

    # if the word is less than 3 characters long: ERROR
    if len(word) < 3:
      tkMessageBox.showinfo(title="ERROR",message="Words must be longer than 2 characters.")
    # if the word does not exist on the board: ERROR
    elif not self.find(word, self.foundWords):
      tkMessageBox.showinfo(title="ERROR",message=word+" is not a word.")
    # if the word has already been found: ERROR
    elif self.find(word, self.guessList):
      tkMessageBox.showinfo(title="ERROR",message=word+" has already been found.")
    # else add to the guessList
    else:
      self.guessList.append(word)

    # reinitialize guess to empty
    self.guess = []

    # check if all words have been found
    if len(self.guessList) == len(self.foundWords):
      print "all words have been found"
      self.stopClock = True
      self.scoreBoard()

  def randomBoard(self):
    board    = defaultdict(lambda : defaultdict(list)) 
    alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    alpha    = 26
    boardl   = 25
    row, col = 0, 0
   
    while boardl > 0:
      r = random.randrange(alpha)
      a = alphabet[r]
      board[row][col] = Tile(a, row, col)
      alphabet = alphabet.replace(a, "")
      col += 1

      if col >= 5:
        col   = 0
        row  += 1
      
      alpha  -= 1
      boardl -= 1

    return board

  def scoreBoard(self):
    self.score = 0
    for word in self.guessList:
      if len(word) > 7:    self.score += 11
      elif len(word) == 7: self.score += 5
      elif len(word) == 6: self.score += 3
      elif len(word) == 5: self.score += 2
      elif len(word) < 5: self.score += 1

    print self.score

    self.play = False
    self.redraw(0)

  def restartGame(self, root):
    #restart the game somehow
    print "here"
 def test_after_creating_instance_of_countdown_its_state_should_be_isStopped(self):
     counter = Countdown()
     self.assertTrue(counter.isStopped())
 def test_after_decreaseCounter_if_counter_is_less_than_zero_the_state_should_be_isStopped(self):
     counter = Countdown()
     counter.startCountDown(1)
     counter.decreaseCounter()
     counter.decreaseCounter()
     self.assertTrue(counter.isStopped())
 def test_after_decreaseCounter_if_counter_is_greater_than_zero_the_state_should_be_Not_isStopped(self):
     counter = Countdown()
     counter.startCountDown(10)
     counter.decreaseCounter()
     self.assertFalse(counter.isStopped())
 def test_after_starting_the_countdown_its_state_should_be_Not_isStopped(self):
     counter = Countdown()
     counter.startCountDown(10)
     self.assertFalse(counter.isStopped())