使用外部文件创建一个句子并在屏幕上显示它们

时间:2013-12-31 18:30:43

标签: python pygame

所以我基本上试图将外部文本文件加载到后端以显示在前端。这是我被困的地方。我目前不知道如何通过后端来做到这一点。

我还需要能够从文件中获取前10个单词,并确保前端只显示前10个单词。我以为我可以通过冒泡排序来做到这一点,但我不知道它是否有效。

通过视觉表示更容易解释: enter image description here

因此,不是那些数字是他们的,你可以将后端的前10个单词放在那里(当你点击任何一个方框时,除了键盘,数字会显示在顶部窗格上)和每次选择一个窗格时,理论上应该出现一组新的单词,就像你创建一个句子一样(下面的代码中的SENTENCE_DEFINITIONS就是你如何创建一个句子)。

这是后端代码:〜

#This here is to be the backend of displayBox.py.


import fileinput
import random
import displayBox

NOUN_TREE = 0
VERB_TREE = 1
PRONOUN_TREE = 2
ADVERB_TREE = 3
ADJECTIVE_TREE = 4
DETERMINER_TREE = 5
PREPOSITION_TREE = 6
CONNECTIVE_TREE = 7
SENTENCE_TREE = 8
ERROR_TREE = 999


#sentence definitions to check against user input
SENTENCE_DEFINITIONS = [[DETERMINER_TREE, NOUN_TREE, PREPOSITION_TREE, NOUN_TREE], [PRONOUN_TREE, VERB_TREE, NOUN_TREE], [DETERMINER_TREE, NOUN_TREE, VERB_TREE, NOUN_TREE]]


class Branch():
    def __init__(self, value):
        self.left = None
        self.right = None
        self.value = value

class Tree():
    def __init__(self):
        self.root = None
        self.found = False

    #lessThan function needed to compare strings
    def lessThan(self, a, b):
        if len(a) < len(b):
            loopCount = len(a)
        else:
            loopCount = len(b)        
        for pos in range(0, loopCount):
            if a[pos] > b[pos]:
                return False        
        return True

    def insert(self, value):
        self.root = self.insertAtBranch(self.root, value)

    def exists(self, value):
        #set the class variable found to False to assume it is not there      
        self.found = False
        self.findAtBranch(self.root, value)
        return self.found

    #Used to fine a value in a tree
    def findAtBranch(self, branch, value):    
        if branch == None:
            pass
        else:
            if branch.value == value:
                self.found = True                
            else:
                self.findAtBranch(branch.left, value)
                self.findAtBranch(branch.right, value)        

    def insertAtBranch(self, branch, value):
        if branch == None:
            return Branch(value)
        else:
            if self.lessThan(branch.value, value):
                branch.right = self.insertAtBranch(branch.right, value)            
            else:
                branch.left = self.insertAtBranch(branch.left, value)
            return branch


def testCompare():
    if "A" == "a":
        print("Same")
    elif "A" < "a":
        print("less than")
    else:
        print("More than")

testCompare()


pronoun = Tree()
noun = Tree();
verb = Tree();    
adverb = Tree();
adjective = Tree();
preposition = Tree();
connective = Tree();
sentence = Tree();




#split the sentence into individual words and add to word list
#and assign a token to the word
def splitSentence(sentence):

    words = []
    token = []
    startPos = 0    
    for charPos in range(0, len(sentence)):
        if sentence[charPos] == " ":
            #print ("splitSentence: " + sentence[startPos:charPos]) #TEST
            token = [sentence[startPos:charPos], findWordType(sentence[startPos:charPos])]
            words.append(token)
            startPos = charPos + 1

    token = [sentence[startPos:charPos+1], 0]
    words.append(token)

    return words



#Loads trees from external source
#By inserting the word with the [:-1], it allows it gets read of the newLine character at the end of each word
def loadTree(filename, treeType):

        if treeType == PRONOUN_TREE:                    
            for word in fileinput.input("pronounTree.txt"):
                print (word)
                pronoun.insert(word[:-1])
        elif treeType == VERB_TREE:
            for word in fileinput.input("verbTree.txt"):
                print (word)
                verb.insert(word[:-1])
        elif treeType == NOUN_TREE:
            for word in fileinput.input("nounTree.txt"):
                print (word)
                noun.insert(word[:-1])
        elif treeType == ADJECTIVE_TREE:
            for word in fileinput.input("adjectiveTree.txt"):
                print (word)
                adjective.insert(word[:-1])
        elif treeType == PREPOSITION_TREE:
            for word in fileinput.input("prepositonTree.txt"):
                print (word)
                preposition.insert(word[:-1])
        elif treeType == ADVERB_TREE:
            for word in fileinput.input("adverbTree.txt"):
                print (word)
                adverb.insert(word[:-1])
        elif treeType == CONNECTIVE_TREE:
            for word in fileinput.input("connectiveTree.txt"):
                print (word)
                connective.insert(word[:-1])
        elif treeType == SENTENCE_TREE:
            for word in fileinput.input("sentenceTree.txt"):
                print (word)
                connective.insert(word[:-1])
        else:
            determiner.insert(word)
            line = file.readline


#Using the loaded trees, find the word
#Outputs what wordgroup the word belongs to
def findWordType(word):

    if noun.exists(word):
        return NOUN_TREE
    elif verb.exists(word):
        return VERB_TREE
    elif pronoun.exists(word):
        return PRONOUN_TREE
    elif adjective.exists(word):
        return ADJECTIVE_TREE
    elif adverb.exists(word):
        return ADVERB_TREE
    elif connective.exists(word):
        return CONNECTIVE_TREE
    elif preposition.exists(word):
        return PREPOSITION_TREE
    else:
        return DETERMINER_TREE



def getFileContents(filename):
    words = [line.strip() for line in open(filename)]    
    return words




###################My second attempt at Checking if sentence is valid###########################

def getWordGroup(sentenceToCheck):

    parse =[]
    words = splitSentence(sentenceToCheck)

    for word in words:
        parse.extend(word[:-1])

    return parseSentence(parse)

def parseSentence(parse):

    for sentenceDef in SENTENCE_DEFINITIONS:

        validSentence == True
        if sentenceDef == parse:
            return validSentence
        else:
            return validSentence == False





if __name__ == '__main__':

    #Calls upon the file displayBox.py and we call the Application class.
    displayBox.Application()

    #Calls upon the loadTree function
    loadTree("pronounTree.txt", PRONOUN_TREE)
    loadTree("nounTree.txt", NOUN_TREE)
    loadTree("verbTree.txt", VERB_TREE)
    loadTree("adverb.txt", ADVERB_TREE)
    loadTree("adjectiveTree.txt", ADJECTIVE_TREE)
    loadTree("prepositonTree.txt", PREPOSITION_TREE)
    loadTree("connectiveTree.txt", CONNECTIVE_TREE)
    loadTree("sentenceTree.txt", SENTENCE_TREE)

    words = []

    words.extend(nouns)
    words.extend(pronouns)
    words.extend(adverbs)
    words.extend(adjectives)
    words.extend(preps)
    words.extend(connectives)
    words.extend(verbs)

如何选择单词: 那么这些词就可以从诸如pronounTree.txt,nounTree.txt,verbTree.txt等文件中选择。它们被预先加载到后端。 .txt文件看起来像这样(Numbers表示使用频率,以便我们可以轻松选择使用的前10个单词。):

nounTree.txt:
people,372      
history,100 
way,185     
art,60      
money,174       
world,51        
information,50      
map,67      
two,69      
family,210  
government,190
health,45
system,11
computer,19
meat,75
year,96
thanks,32
music,80
person,80
reading,77

理论上,后端应该采用前10个最常用的名词(在这种情况下)并在最大的框中显示频率最高的那个。在这种情况下,名词将排序以发现“人物”是具有最高频率的单词并将在框1中显示。然后从那里将其他单词从最高到最低,按顺序放入其他框中。

如果您需要,这是前端代码:

import pygame
import sys


WHITE = (255,255,255)
BLACK = (0  ,0  ,0  )



MAIN_BUTTON = 2

KEYBOARD = True
WORDS = False



class Pane():

    def __init__(self, textToDisplay, textValue, coordinates, screen):

        self.textToDisplay = textToDisplay
        self.textValue = textValue
        self.coordinates = coordinates
        self.screen = screen
        self.font = pygame.font.SysFont('Palace Script MT', 25)



    def coordinates(self):
        return self.coordinates



    def text(self):
        return self.textValue



    def drawPane(self):
        pygame.draw.rect(self.screen, BLACK, self.coordinates, 2)
        self.screen.blit(self.font.render(self.textToDisplay, True, BLACK), self.coordinates)



class Terminal(Pane):

    def __init__(self, textToDisplay, coordinates, screen):

        Pane.__init__(self, textToDisplay, "", coordinates, screen)

        self.text = "" # keeps text displayed in top pane
        self.text_pos = (10,20) # left margin, top margin
        self.text_changed = True
        self.cursor_visible = True # changes after self.cursor_delay
        self.cursor_delay = 500 # This is 0.5 second
        self.cursor_next_change = pygame.time.get_ticks() + self.cursor_delay

    def draw(self):
        self.drawPane() 
        self.drawText()

    def drawText(self):
        #TODO: split self.text to lines

        # changes the cursor visibility
        if self.cursor_next_change <= pygame.time.get_ticks():
            self.cursor_next_change = pygame.time.get_ticks() + self.cursor_delay
            self.cursor_visible = not self.cursor_visible
            self.text_changed = True

        # renders new text only if text was changed (or cursor changed visibility)
        if self.text_changed:
            if self.cursor_visible:
                self.text_surface = self.font.render(self.text+"_", True, BLACK)
            else:
                self.text_surface = self.font.render(self.text, True, BLACK)

            self.text_rect = self.text_surface.get_rect(topleft = self.text_pos)
            self.text_changed = False

        self.screen.blit(self.text_surface, self.text_rect)

    def setText(self, text):
        self.text = text
        self.text_changed = True

    def addText(self, text):
        if text == "Backspace":
            if self.text: # text not empty
                self.text = self.text[:-1] # delete last char
        else:
            self.text += text
        self.text_changed = True

    def addWord(self, text):
        if text == "Backspace":
            if self.text: # text not empty
                self.text = self.text[:-1] # delete last char
        else:
            if self.text:
                self.text += " " # adds space before word
            self.text += text
        self.text_changed = True


class Application():

    NoOfPanes = 0
    NoOfKeys = 0
    Panes = []
    Keys = []

    paneLocs = [(583, 334, 300, 150), 
                            (633, 150, 200, 125), 
                            (633, 600, 200, 125), 
                            (350, 360, 200, 100), 
                            (925, 360, 200, 100), 
                            (1000, 150, 150, 100), 
                            (275, 150, 150, 100), 
                            (275, 600, 150, 100), 
                            (1000, 600, 150, 100), 
                            (75, 350, 200, 100),
                            (0, 668, 200, 100)
                            ]    

    keyboardPaneLocs = [(0, 100, 50, 50),
                        (75, 100, 50, 50),
                        (150, 100, 50, 50),
                        (225, 100, 50, 50),
                        (300, 100, 50, 50),
                        (375, 100, 50, 50),
                        (450, 100, 50, 50),
                        (525, 100, 50, 50),
                        (600, 100, 50, 50),
                        (675, 100, 50, 50),
                        (0, 200, 50, 50),
                        (75, 200, 50, 50),
                        (150, 200, 50, 50),
                        (225, 200, 50, 50),
                        (300, 200, 50, 50),
                        (375, 200, 50, 50),
                        (450, 200, 50, 50),
                        (525, 200, 50, 50),
                        (600, 200, 50, 50),
                        (675, 200, 50, 50),
                        (0, 300, 50, 50),
                        (75, 300, 50, 50),
                        (150, 300, 50, 50),
                        (225, 300, 50, 50),
                        (300, 300, 50, 50),
                        (375, 300, 50, 50),
                        (450, 300, 50, 50),
                        (525, 300, 50, 50),
                        (600, 300, 50, 50),
                        (0, 400, 50, 50),
                        (75, 400, 50, 50),
                        (150, 400, 50, 50),
                        (225, 400, 50, 50),
                        (300, 400, 50, 50),
                        (375, 400, 50, 50),
                        (450, 400, 50, 50),
                        (525, 400, 125, 50),
                        (0, 668, 200, 100),
                        (800, 150, 100, 50)]

    textPaneLoc = [(0, 0, 1000, 100)]



    def __init__(self):

        pygame.init()
        pygame.display.set_caption('Box Test')

        self.font = pygame.font.SysFont('Arial', 25)
        self.screen = pygame.display.set_mode((1366,768), 0, 32)

        self.show_panes = True
        self.show_keyboard = False
        self.show_terminal = True

        self.createPanes()
        self.createKeyboard()

        self.terminal = Terminal("", (0,0, 1000, 100), self.screen)

    def close(self):
        print ("pygame quit")
        pygame.quit()
        sys.exit()



    def createPanes(self):
        self.addPane("1", WORDS)
        self.addPane("2", WORDS)
        self.addPane("3", WORDS)
        self.addPane("4", WORDS)
        self.addPane("5", WORDS)
        self.addPane("6", WORDS)
        self.addPane("7", WORDS)
        self.addPane("8", WORDS)
        self.addPane("9", WORDS)
        self.addPane("10", WORDS)
        self.addPane("Keyboard", WORDS)



    def createKeyboard(self):
        self.addPane("1", KEYBOARD)
        self.addPane("2", KEYBOARD)
        self.addPane("3", KEYBOARD)
        self.addPane("4", KEYBOARD)
        self.addPane("5", KEYBOARD)
        self.addPane("6", KEYBOARD)
        self.addPane("7", KEYBOARD)
        self.addPane("8", KEYBOARD)
        self.addPane("9", KEYBOARD)
        self.addPane("0", KEYBOARD)
        self.addPane("Q", KEYBOARD)
        self.addPane("W", KEYBOARD)
        self.addPane("E", KEYBOARD)
        self.addPane("R", KEYBOARD)
        self.addPane("T", KEYBOARD)
        self.addPane("Y", KEYBOARD)
        self.addPane("U", KEYBOARD)
        self.addPane("I", KEYBOARD)
        self.addPane("O", KEYBOARD)
        self.addPane("P", KEYBOARD)
        self.addPane("A", KEYBOARD)
        self.addPane("S", KEYBOARD)
        self.addPane("D", KEYBOARD)
        self.addPane("F", KEYBOARD)
        self.addPane("G", KEYBOARD)
        self.addPane("H", KEYBOARD)
        self.addPane("J", KEYBOARD)
        self.addPane("K", KEYBOARD)
        self.addPane("L", KEYBOARD)
        self.addPane("Z", KEYBOARD)
        self.addPane("X", KEYBOARD)
        self.addPane("C", KEYBOARD)
        self.addPane("V", KEYBOARD)
        self.addPane("B", KEYBOARD)
        self.addPane("N", KEYBOARD)
        self.addPane("M", KEYBOARD)
        self.addPane(" ", KEYBOARD)
        self.addPane("Boxes", KEYBOARD)
        self.addPane("Backspace", KEYBOARD)



    def addPane(self, textToDisplay, keyboardFlag):      
        if (not keyboardFlag) and (self.NoOfPanes > 11):
            print("Limit Reached")            
        else:
            print(int(self.NoOfPanes))

            if keyboardFlag:
                self.Keys.append(Pane(textToDisplay, textToDisplay, self.keyboardPaneLocs[self.NoOfKeys], self.screen))
                self.NoOfKeys += 1
            else:
                self.Panes.append(Pane(textToDisplay, textToDisplay, self.paneLocs[self.NoOfPanes], self.screen))
                self.NoOfPanes += 1


    def drawPanes(self):
        for Pane in self.Panes:
            Pane.drawPane()



    def drawKeyboard(self):
        for Key in self.Keys:
            Key.drawPane()



    def mousePosition(self, event):
        if event.type == MAIN_BUTTON:
            self.Pos = pygame.mouse.get_pos()
            return MAIN_BUTTON
        else:
            return False



    def mouseDown(self):
        posx,posy = pygame.mouse.get_pos()      
        textToReturn = "Nothing selected"
        if self.show_panes:
            for Pane in self.Panes:
                paneCoords = Pane.coordinates
                print(str(paneCoords[0]) + ":" + str(paneCoords[1]) + ":" + str(paneCoords[2]) + ":" + str(paneCoords[3]))
                if (paneCoords[0] <= posx <= paneCoords[0]+paneCoords[2]) and (paneCoords[1] <= posy <= paneCoords[1]+paneCoords[3]):
                    textToReturn = Pane.text()
        elif self.show_keyboard:
            for Pane in self.Keys:
                paneCoords = Pane.coordinates
                print(str(paneCoords[0]) + ":" + str(paneCoords[1]) + ":" + str(paneCoords[2]) + ":" + str(paneCoords[3]))
                if (paneCoords[0] <= posx <= paneCoords[0]+paneCoords[2]) and (paneCoords[1] <= posy <= paneCoords[1]+paneCoords[3]):            
                    textToReturn = Pane.text()

        return textToReturn



    def run(self):

        clock = pygame.time.Clock()

        RUNNING = True
        while RUNNING:

            for event in pygame.event.get():

                if event.type == pygame.QUIT:
                    RUNNING = False
                    break

                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_ESCAPE:
                        self.show_keyboard = not self.show_keyboard
                        self.show_panes = not self.show_panes

                if event.type == pygame.MOUSEBUTTONUP:
                    textSelected = self.mouseDown()
                    print(textSelected)
                    if textSelected == "Keyboard":

                        self.show_keyboard = True
                        self.show_panes = False
                    elif textSelected == "Boxes":
                        self.show_keyboard = False
                        self.show_panes = True
                    elif textSelected != "Nothing selected":
                        if self.show_keyboard:
                            self.terminal.addText(textSelected)
                        else:
                            self.terminal.addWord(textSelected)

            # --- draws ---

            self.screen.fill(WHITE)

            if self.show_panes:
                self.drawPanes()

            if self.show_keyboard:
                self.screen.blit(self.font.render("Spacebar", True, BLACK), (525, 400, 100, 50))
                self.drawKeyboard()

            if self.show_terminal:
                self.terminal.draw()

            pygame.display.update()

            # --- FPS ---

            clock.tick(60)

        self.close()    


Application().run()

非常感谢给予的帮助。

0 个答案:

没有答案