コード例 #1
0
class Game2(Widget):
    #Create the data base
    db = dataBase.DataBase()
    table_name = "Game2"
    table_attributes = ["time Date", "score int"]
    db.create_Table(table_name, table_attributes)
    #test
    JSON = db.SQliteToJSOn("Game2")

    print(Widget.width)
    print(Widget.height)
    #Score display
    score = NumericProperty(0)
    remaining = NumericProperty(18)
    clock = NumericProperty(0)

    #Define the three categories
    category_house = ObjectProperty(None)
    category_vehicle = ObjectProperty(None)
    category_character = ObjectProperty(None)

    def increment_clock(self, dt):
        if (self.remaining != 0):
            self.clock += 1
        else:
            return False

    def update(self, dt):
        if (self.remaining == 0):
            self.on_winning()
            return False

    def on_winning(self):
        layout = BoxLayout(orientation='vertical')

        def callback(instance):
            if (instance.text == 'Rejouer'):
                return Game2App().run()
            else:
                return gameMenu.GameMenuApp().run()
            print('The button <%s> is being pressed' % instance.text)

        btn1 = Button(text='Rejouer')
        btn1.bind(on_press=callback)
        btn2 = Button(text='Changer de jeu')
        btn2.bind(on_press=callback)
        layout.add_widget(btn1)
        layout.add_widget(btn2)
        popup = Popup(title='Felicitations !!! Ton score : ' + str(self.score),
                      title_size='20sp',
                      content=layout,
                      size_hint=(None, None),
                      size=(400, 400),
                      auto_dismiss=False)
        popup.open()
        print("popup ouvert")
        sound = SoundLoader.load('../sound/finished.wav')
        sound.play()
コード例 #2
0
    def export(self, path, filename):
        """Function to export the database to a CSV format
        :param path: path of the export file
        :param filename: name of the export file
        """

        db = dataBase.DataBase()
        str = path + '/' + filename
        db.JSonToCSV(db.SQliteToJSOn("Game3"), str, [])
        self.dismiss_popup()
コード例 #3
0
class MongoDb():
    mongo = dataBase.DataBase()

    def createUser(self, email, password, name):
        if (self.findUser(email)):
            return False
        try:
            self.mongo.insert_user(name, email, password, [" "], [0], "", {})
            return True
        except:
            return False

    def findUser(self, email):
        try:
            return self.mongo.find_user(email)
        except:
            return None

    def saveProgram(self, email, name, program):
        user = self.findUser(email)
        if (user):
            try:
                self.mongo.remove_program(email, name)
            except:
                pass
            self.mongo.insert_program(email, name, program["fieldData"],
                                      program["pos"], program["machine"])

    def loadProgram(self, email, name):
        user = self.findUser(email)
        if (user):
            program = self.mongo.find_program(email, name)
            field = program["default_field"]
            dimensions = 1
            if (type(field[0]) is list):
                dimensions = 2
            size = len(field)

            return {
                "moves": None,
                "pos": [0 for i in range(dimensions)],
                "state": list(program["table_states"].keys())[0],
                "machine": program["table_states"],
                "fieldData": field
            }

        return None

    def deleteProgram(self, email, name):
        user = self.findUser(email)
        if (user):
            self.mongo.remove_program(email, name)
コード例 #4
0
ファイル: ui.py プロジェクト: czy0538/DataBaseExperiment
 def __init__(self):
     self.table_item = ''
     db = dataBase.DataBase(messagebox=self)
     self.isSelected = [False] * 11  # 框选list,bool
     self.lineEditMessage = [''] * 11  # 获取所有文本框中的内容
     self.mode = ''  # 功能模式
     self.cursor = db.getCursor()
     self.cnxn = db.getCnxn()
     self.display_item = ''  # select子句
     self.condition_item = ''  # where子句
     self.table_item = ''  # from子句
     self.table_selected = [False] * 3  # 0为S,1为SC,2为C
     self.WrongInputError = False  # 输入错误为True
コード例 #5
0
ファイル: GUI.py プロジェクト: czy0538/DataBaseExperiment
 def getMessage(self):
     message = self.inputAdd.text()  # 获取输入的字符串
     db = dataBase.DataBase()
     outputdata = ""  # 存放获得的内容
     cursor = db.getCursor()  # 获取游标
     cursor.execute(
         '''select sno,sname,ssex,sage,saddr
                     from s
                     where s.saddr=?
                     ''', (message))
     row = cursor.fetchone()  # 读取游标数据
     if row is None:  # 没有这个人输出没有
         outputdata = '查无此人'
     else:
         while row:
             for i in row:
                 outputdata = outputdata + i.strip() + ' '  # 去掉多余的空格
             outputdata = outputdata + '\n'
             row = cursor.fetchone()
     self.answerDisplay.setText(outputdata)  # 将数据发送到显示区域
コード例 #6
0
class Object(Widget):
    """Class to manage drag and drop
   
    """
    #Open a connection for each Object
    local_db = dataBase.DataBase()

    def on_touch_move(self, touch):
        """Function called when the object is moved
        
        :param touch: finger on the screen     
        
        """
        #If the current object is the one grab
        if touch.grab_current is self:
            #Update of position
            self.parent.touched_object = self
            self.center_x = touch.x
            self.center_y = touch.y

    def on_touch_down(self, touch):
        """Function called when the object is double clicked
        
        :param touch: finger on the screen     
        
        """
        #Get the object touched by the user
        if self.collide_point(*touch.pos):
            if touch.is_double_tap:
                #Play a sound if the user do a double tap
                sound = SoundLoader.load(self.text)
                sound.play()
                return
            #Set opacity to display the current selected object
            self.opacity = 0.2
            #The object is grabbed
            touch.grab(self)
            return True

    def on_touch_up(self, touch):
        """Function called when the object is dropped after a move
        
        :param touch: finger on the screen     
        
        """
        #If this is the correct object
        if touch.grab_current is self:
            #The Object is ungrabbed
            touch.ungrab(self)
            #The initial opacity is set
            self.opacity = 1
            #Check if the object has been dropped on the category House
            if (self.collide_customed(self.parent.category_house)):
                print("House touched")
                #If there is no other category in collision
                if (not self.collide_customed(self.parent.category_vehicle)):
                    #Check if the object has been dropped on the good category
                    if (self.category == "house"):
                        print("Congratulations !")
                        sound = SoundLoader.load('../sound/right.wav')
                        sound.play()
                        #Update of score
                        self.parent.score += 5
                        self.parent.remaining = self.parent.remaining - 1
                        val = self.parent.score
                        print(
                            time.strftime("%a, %d %b %Y %H:%M:%S",
                                          time.gmtime()))
                        #Object is removed
                        self.parent.remove_widget(self)
                        #SAving in dataBase
                        self.local_db.insert_into_Table(
                            "Game2", ["time Date", "score int"], [
                                time.strftime("%a %d %b %Y %H:%M:%S",
                                              time.gmtime()),
                                str(val)
                            ])
                        self.local_db.print_table("game2")
                        self.local_db.JSonToCSV(
                            self.local_db.SQliteToJSOn("Game2"))
                        return True
                    else:
                        print("This is the wrong category")
                        sound = SoundLoader.load('../sound/wrong.wav')
                        sound.play()
                        #Update of score
                        self.parent.score -= 1
                        #The object is moved back to the initial position
                        self.pos = self.pos_base

            #Check if the object has been dropped on the category Vehicle
            elif (self.collide_customed(self.parent.category_vehicle)):
                print("Vehicle touched")
                #If there is no other category in collision
                if ((not self.collide_customed(self.parent.category_house))
                        and (not self.collide_customed(
                            self.parent.category_character))):
                    #Check if the object has been dropped on the good category
                    if (self.category == "vehicle"):
                        print("Congratulations !")
                        sound = SoundLoader.load('../sound/right.wav')
                        sound.play()
                        #Update of score
                        self.parent.score += 5
                        self.parent.remaining = self.parent.remaining - 1
                        #Object is removed
                        self.parent.remove_widget(self)
                        return True
                    else:
                        print("This is the wrong category")
                        sound = SoundLoader.load('../sound/wrong.wav')
                        sound.play()
                        #Update of score
                        self.parent.score -= 1
                        #The object is moved back to the initial position
                        self.pos = self.pos_base

            #Check if the object has been dropped on the category Character
            elif (self.collide_customed(self.parent.category_character)):
                print("Character touched")
                #If there is no other category in collision
                if (not self.collide_customed(self.parent.category_vehicle)):
                    #Check if the object has been dropped on the good category
                    if (self.category == "character"):
                        print("Congratulations !")
                        sound = SoundLoader.load('../sound/right.wav')
                        sound.play()
                        #Update of score
                        self.parent.score += 5
                        self.parent.remaining = self.parent.remaining - 1
                        #Object is removed
                        self.parent.remove_widget(self)
                        return True
                    else:
                        print("This is the wrong category")
                        sound = SoundLoader.load('../sound/wrong.wav')
                        sound.play()
                        #Update of score
                        self.parent.score -= 1
                        #The object is moved back to the initial position
                        self.pos = self.pos_base

            #The object is moved back to the initial position
            self.pos = self.pos_base

    def collide_customed(self, widget):
        '''
        Function which implement custom collision between 2 widgets
        This function draw a square with center (self.center_x, self.center_y) and size = ( widget.size - self.size)/2 (1 if res <0)
        :param Widget: the widget to test collision with self
        :type widget = Widget, we will use center_x,center_y and size
        
        :return Return true is self's custom zone is in collision with widget
    '''
        #Calcul of radius
        size = ((widget.size_hint_x - self.size_hint_x) / 4)
        # if r <=0, the test will be done with a point
        if (size <= 0):
            size = 1
        #Creation of the zone
        zone = Widget()
        zone.center_x = widget.center_x
        zone.center_y = widget.center_y
        zone.size_hint_x = size
        zone.size_hint_y = size

        #Test the collision
        return (self.collide_widget(zone))
コード例 #7
0
class Activite1_easy(Widget):

    #Open a dataBase connexion
    local_db = dataBase.DataBase()
    table_name = "activite1_easy"
    table_attributes = [
        "time Date", "score integer", "source string", "destination string",
        "result string"
    ]
    local_db.create_Table(table_name, table_attributes)
    #Save window's size to use later
    windowSave = Window.size
    #Creation d'une liste de sons
    SoundList = []
    score = NumericProperty(0)
    clock = NumericProperty(0)
    sound = ''
    category = ''
    picture1 = ObjectProperty(None)
    picture2 = ObjectProperty(None)
    picture3 = ObjectProperty(None)
    picture4 = ObjectProperty(None)

    def sound_init(self):
        #Cette methode parse le fichier .txt ou se trouve tous les sons et les place dans la liste de sons
        #Elle est appelee dans la methode suivante
        # Opening file reading mode
        loaded_file = open("./activite1_easy.txt", "r")
        #read the first line
        line = loaded_file.readline()

        #Loading all the file in 2 different lists
        while (line != "endfile"):
            if (line[0] != '#'):
                tab_res = line.split('&')
                tab_save = tab_res[1].split('/')
                tab_name = tab_save[2].split('.')
                if (tab_res[0] == "Sound"):
                    sound = tab_res[1]
                    #updating form's list
                    self.SoundList.append(sound)

#read the next line
            line = loaded_file.readline()

    def new_round(self):
        #Cette methode appele sound_init et prend un son aleatoirement parmi la liste de son
        self.sound_init()
        size_list_sound = len(self.SoundList)
        rand_sound = random.randint(0, size_list_sound - 1)
        loaded_file = open("./activite1_easy.txt", "r")
        #read the first line
        line = loaded_file.readline()
        self.sound = self.SoundList[rand_sound]
        #On recupere la categorie du son pioche precedemment
        while (line != "endfile"):
            if (line[0] != '#'):
                tab_res = line.split('&')
                tab_save = tab_res[1].split('/')
                tab_name = tab_save[2].split('.')
                if (tab_res[0] == "Sound"):
                    if (tab_res[1] == self.sound):
                        Activite1_easy.category = tab_res[2]
            #read the next line
            line = loaded_file.readline()

        print('le son qui passe cest', str(self.sound))
        print('Sa categorie est ', str(self.category))
        return self.sound

    def increment_clock(self, dt):
        self.clock += 1

    #Methode permettant d'initialiser un vecteur de mouvement pour les 4 images.
    #On veut les faire defiler de gauche a droite, donc le vecteur est (1,0)
    def serve(self):
        self.picture1.center = self.center
        self.picture1.velocity = Vector(1, 0)

        self.picture2.center = self.center
        self.picture2.velocity = Vector(1, 0)

        self.picture3.center = self.center
        self.picture3.velocity = Vector(1, 0)
        self.picture4.center = self.center
        self.picture4.velocity = Vector(1, 0)

    def update(self, dt):

        self.picture1.move()
        self.picture2.move()
        self.picture3.move()
        self.picture4.move()
        #Si une image sort de la fenetre elle reapparait de l'autre cote
        if (self.picture1.y < 0):
            self.picture1.y = self.height
        if (self.picture1.y > self.height):
            self.picture1.y = 0
        if (self.picture1.x < 0):
            self.picture1.x = self.width
        if (self.picture1.x > self.width):
            self.picture1.x = 0
        if (self.picture2.y < 0):
            self.picture2.y = self.height
        if (self.picture2.y > self.height):
            self.picture2.y = 0
        if (self.picture2.x < 0):
            self.picture2.x = self.width
        if (self.picture2.x > self.width):
            self.picture2.x = 0

        if (self.picture3.y < 0):
            self.picture3.y = self.height
        if (self.picture3.y > self.height):
            self.picture3.y = 0
        if (self.picture3.x < 0):
            self.picture3.x = self.width
        if (self.picture3.x > self.width):
            self.picture3.x = 0
        if (self.picture4.y < 0):
            self.picture4.y = self.height
        if (self.picture4.y > self.height):
            self.picture4.y = 0
        if (self.picture4.x < 0):
            self.picture4.x = self.width
        if (self.picture4.x > self.width):
            self.picture4.x = 0

    def niveaux(self):
        #Cette methode est appelee par on_winning. Il s'agit de la fenetre proposant les differents niveaux de jeu
        l = BoxLayout(orientation='vertical')

        def callback(instance):
            #Si l'utilisateur clique sur "Facile" on ferme la fenetre et retourne le jeu 1 facile
            if (instance.text == 'Facile'):
                popup.dismiss()
                self.new_round()
                self.score = 0
                self.clock = 0
                sound = SoundLoader.load(self.sound)
                sound.play()
            #Si l'utilisateur clique sur "Moyen" on ferme la fenetre et on retourne le jeu moyen
            if (instance.text == 'Moyen'):
                popup.dismiss()
                activite1_medium.Activite1_mediumApp().run()
            #Si l'utilisateur clique sur "Difficile" on ferme la fenetre, on fait appele a la methode new_round pour choisir un nouveau son
            #On remet le score et le chrono a zero et on lance le son choisit
            if (instance.text == 'Difficile'):
                popup.dismiss()
                activite1_difficult.Activite1_difficultApp().run()

            print('The button <%s> is being pressed' % instance.text)

        #Creation des differents bouttons
        b1 = Button(text='Facile', size_hint=(1, 0.1))
        b1.bind(on_press=callback)
        b2 = Button(text='Moyen', size_hint=(1, 0.1))
        b2.bind(on_press=callback)
        b3 = Button(text='Difficile', size_hint=(1, 0.1))
        b3.bind(on_press=callback)
        l.add_widget(b1)
        l.add_widget(b2)
        l.add_widget(b3)
        popup = Popup(title='Choisis le niveau de difficulte ',
                      content=l,
                      size_hint=(None, None),
                      size=(300, 300),
                      auto_dismiss=False)
        popup.open()

    def on_winning(self):
        #Cette methode est appelee lorsque l'utilisateur clique sur la bonne image
        #On lui propose alors plusieurs boutons
        layout = BoxLayout(orientation='vertical')

        def callback(instance):
            #S'il clique sur rejouer on ferme la fenetre, on fait un appele a new_round pour repiocher un son, on met a zero score et temps et on lance le son correspondant
            if (instance.text == 'REJOUER'):
                sound1.stop()
                popup.dismiss()
                self.new_round()
                self.clock = 0
                self.score = 0
                sound = SoundLoader.load(self.sound)
                sound.play()
            #S'il clique sur 'changer de niveau' il est redirigie vers la methode niveaux()
            if (instance.text == 'CHANGER DE NIVEAU'):
                popup.dismiss()
                sound1.stop()
                self.niveaux()
            #S'il clique sur "menu", il quitte ce jeu et est redirige vers la fenetre du menu principal
            if (instance.text == 'MENU'):
                sound1.stop()
                popup.dismiss()
                menu.MenuApp().run()
            #S'il clique sur "Quitter le jeu", il quitte toute l'application
            if (instance.text == 'QUITTER LE JEU'):
                sound1.stop()
                popup.dismiss()
                self.parent.stop()
            print('The button <%s> is being pressed' % instance.text)

        """ Creation des bouttons:  """
        btn1 = Button(text='REJOUER')
        btn1.bind(on_press=callback)
        btn2 = Button(text='MENU')
        btn2.bind(on_press=callback)
        btn3 = Button(text='CHANGER DE NIVEAU')
        btn3.bind(on_press=callback)
        btn4 = Button(text='QUITTER LE JEU')
        btn4.bind(on_press=callback)
        layout.add_widget(btn1)
        layout.add_widget(btn2)
        layout.add_widget(btn3)
        layout.add_widget(btn4)
        popup = Popup(title='Felicitations ! \nScore : ' + str(self.score) +
                      '\nTemps: ' + str(self.clock) + ' secondes',
                      title_size='20sp',
                      title_color=[0.5, 1, 1, 1],
                      title_font='Red',
                      content=layout,
                      size_hint=(None, None),
                      size=(400, 400),
                      auto_dismiss=False)
        popup.open()
        print "popup ouvert"
        sound1 = SoundLoader.load('../sound/public.wav')
        sound1.play()

    #Methode appelee dans le .kv:
    #Si l'utilisateur clique sur le bouton Aide en haut a gauche de la fenetre de jeu, une fenetre expliquant le fonctionnement du jeu apparaitra
    #boutton cree dans le .kv
    def aide(self):
        l = BoxLayout(orientation='vertical')
        b = Button(text='Quitter', size_hint=(0.5, 0.1))
        l.add_widget(b)

        popup = Popup(
            title='Aide',
            content=Label(
                text=
                'Il faut trouver l image qui correspond \nau son entendu. Tu peux reecouter le son \nen cliquant sur l image en haut a \ndroite correspondante.\n Le but du jeu etant de trouver la bonne image le \nplus vite possible.'
            ),
            size_hint=(None, None),
            size=(400, 200),
        )
        b.bind(on_press=popup.dismiss)
        popup.open()

    #Methode appelee dans le .kv:
    #Si l'utilisateur clique sur le bouton Menu en haut a gauche de la fenetre de jeu, il sera redirige vers le Menu
    #Boutton cree dans le .kv
    def menu(self):
        return menu.MenuApp().run()

    #Methode appellee dans le .kv:
    #Si l'utilisateur clique le boutton Quitter en haut a gauche de la fenetre de jeu, l'application s'arretera
    #Boutton cree dans le .kv
    def stop(self):
        return Activite1_easyApp().stop()
コード例 #8
0
import telebot
import dataBase

users = {}

bot = telebot.TeleBot("TOKEN")
db = dataBase.DataBase()
db.createEventsTable()
db.createTasksTable()


@bot.message_handler(commands=['start', 'help'])
def help(message):
    bot.send_message(
        message.from_user.id,
        """/reg for registration. Вы можете продолжить без регистрации, если хотите.
    \n /addevent - добавить событие \n /addtask - добавить задание \n /deleteevent - удалить событие \n /deletetask - удалить задание
    \n /deleteuser - удалить пользователя со всеми заданиями (работает после регистрации)
    \n /getevents - получить события по параметрам
    \n /gettasks - получить задания по параметрам
    \n /settaskdone - пометить задание как сделанное""")


@bot.message_handler(commands=['reg'])
def register(message):
    db.addUser(message.from_user.id)
    bot.send_message(message.from_user.id, "Успешно зарегистрирован")


@bot.message_handler(commands=['addevent'])
def add_event(message):
コード例 #9
0
class Game3(Widget):
    """Class representing the game 3
   
    """
    #Open a dataBase connexion
    local_db = dataBase.DataBase()
    table_name = "Game3"
    table_attributes = [
        "time Date", "score integer", "source string", "destination string",
        "result string"
    ]
    local_db.create_Table(table_name, table_attributes)
    #Save window's size to use later
    windowSave = Window.size

    #Create object list
    ObjectList = []

    #Create cat list
    ObjectFormList = []

    #List to store Form displayed and Object displayed
    FormDisplayed = []
    ObjDisplayed = []

    #Create a list to store pictures already found by the children
    already_learned = []

    #When init the Game
    def __init__(self, **kwargs):
        """Function called when the game3 is created
   
        """
        Widget.__init__(self, **kwargs)
        # Opening file reading mode
        loaded_file = open("./game3.txt", "r")
        #read the first line
        line = loaded_file.readline()

        #Loading all the file in 2 different lists
        while (line != "endfile"):
            if (line[0] != '#'):
                tab_res = line.split('&')
                tab_save = tab_res[1].split('/')
                tab_name = tab_save[4].split('.')
                nameImg = tab_name[0]
                if (tab_res[0] == "Object"):
                    #Create Object with src and category
                    obj = Object2(tab_res[1],
                                  nameImg,
                                  tab_res[2],
                                  tab_res[3],
                                  size=(self.windowSave[0] * 1 / 4,
                                        self.windowSave[1] * 1 / 3),
                                  text=tab_res[4])
                    #Updating object's list
                    self.ObjectList.append(obj)
                if (tab_res[0] == "ObjectForm"):
                    cat = tab_res[2]
                    form = ObjectForm(tab_res[1],
                                      nameImg,
                                      cat,
                                      tab_res[3],
                                      size=(self.windowSave[0] * 1 / 4,
                                            self.windowSave[1] * 1 / 3))
                    #updating form's list
                    self.ObjectFormList.append(form)
            #read the next line
            line = loaded_file.readline()
        self.new_round()

    #Score display
    score = NumericProperty(0)
    remaining = NumericProperty(18)
    clock = NumericProperty(0)

    def new_round(self):
        """Function called when the user win a round to start a new one
   
        """
        #Store ObjectList and ObjectFormList size
        size_list_obj = len(self.ObjectList)
        size_list_obj_form = len(self.ObjectFormList)
        #Create 2 list to store random values
        mem_rand_obj = []
        mem_rand_form = []
        #Reset list of objects and forms displayed
        for o in self.ObjDisplayed:
            self.remove_widget(o)
        for f in self.FormDisplayed:
            self.remove_widget(f)
        self.FormDisplayed = []
        self.ObjDisplayed = []
        #2 list to store objects before update
        saveFormDisplayed = []
        saveObjDisplayed = []
        #Display 3 items on the right
        for i in [1, 3, 5]:
            ##############"PART FOR THE OBJ######################
            #Choose an integer randomly, but different for the previous one
            rand_obj = random.randint(0, size_list_obj - 1)
            checked = 0
            while (checked != 1):
                rand_obj = random.randint(0, size_list_obj - 1)
                checked = 1
                for j in mem_rand_obj:
                    if (j == rand_obj):
                        checked = 0

            mem_rand_obj.append(rand_obj)

            #Select the corresponding object
            obj = self.ObjectList[rand_obj]
            #print(obj.get_name())
            #Set object
            obj.set_center_y(self.windowSave[1] * i / 6)
            obj.set_x(self.windowSave[0] * 1 / 8)
            ##############"PART FOR THE FORM######################
            #Choose an integer randomly, but different for the previous one
            rand_form = random.randint(0, size_list_obj_form - 1)
            checked = 0
            while (checked != 1):
                rand_form = random.randint(0, size_list_obj_form - 1)
                checked = 1
                for j in mem_rand_obj:
                    if (j == rand_form):
                        checked = 0
                for j in mem_rand_form:
                    if (j == rand_form):
                        checked = 0
            mem_rand_form.append(rand_form)

            objForm = self.ObjectFormList[rand_form]

            #Set Object
            objForm.set_center_y(self.windowSave[1] * i / 6)
            objForm.set_x(self.windowSave[0] * 5 / 8)

            #Update lists
            saveFormDisplayed.append(objForm)
            saveObjDisplayed.append(obj)

        #choose 2 random numbers
        rand_identique = random.randint(0, 2)
        rand_pos = random.randint(0, 2)

        for obj in saveObjDisplayed:
            #Both Widgets are added
            obj2 = Object2(obj.src,
                           obj.name,
                           obj.category,
                           obj.video,
                           size=obj.size,
                           center_y=obj.center_y - 50,
                           x=obj.x)
            obj2.set_pos_base([obj.x, obj.y])
            self.add_widget(obj2)
            self.ObjDisplayed.append(obj2)
        indice = 0
        for objForm in saveFormDisplayed:
            if (indice == rand_pos):
                for obj_inter in self.ObjectFormList:
                    #print(len(obj_inter.category))
                    #print(len(self.ObjDisplayed[rand_identique].category))
                    #print(obj_inter.category)
                    #print(self.ObjDisplayed[rand_identique].category)
                    if (obj_inter.category == (
                            self.ObjDisplayed[rand_identique].category)):
                        objForm = obj_inter
                        objForm.x = self.windowSave[0] * 5 / 8
                        objForm.center_y = self.windowSave[1] * (indice * 2 +
                                                                 1) / 6
                        break
            #print("cat ="+objForm.category)
            objForm2 = ObjectForm(objForm.src,
                                  objForm.name,
                                  objForm.category,
                                  objForm.video,
                                  size=objForm.size,
                                  center_y=objForm.center_y - 50,
                                  x=objForm.x)
            objForm2.set_pos_base([objForm.x, objForm.y])
            self.add_widget(objForm2)
            self.FormDisplayed.append(objForm2)
            #update list
            self.FormDisplayed[indice] = objForm2
            indice = indice + 1

    def increment_clock(self, dt):
        if (self.remaining != 0):
            self.clock += 1
        else:
            return False

    def updateWidget(self):
        for obj in self.ObjectList:
            obj.updateCatSize()
            break

    def update(self, dt):
        if (Window.size != self.windowSave):
            self.windowSave = Window.size
            self.updateWidget()
        if (self.remaining == 0):
            self.on_winning()
            return False

    def on_winning(self):
        layout = BoxLayout(orientation='vertical')

        def callback(instance):
            if (instance.text == 'Rejouer'):
                return Game3App().run()
            else:
                return gameMenu.GameMenuApp().run()
            print('The button <%s> is being pressed' % instance.text)

        btn1 = Button(text='Rejouer')
        btn1.bind(on_press=callback)
        btn2 = Button(text='Changer de jeu')
        btn2.bind(on_press=callback)
        layout.add_widget(btn1)
        layout.add_widget(btn2)
        popup = Popup(title='Felicitations !!! Ton score : ' + str(self.score),
                      title_size='20sp',
                      content=layout,
                      size_hint=(None, None),
                      size=(400, 400),
                      auto_dismiss=False)
        popup.open()
        print("popup ouvert")
        sound = SoundLoader.load('../sound/finished.wav')
        sound.play()
コード例 #10
0
class Activite4(Widget):

    #Open a dataBase connexion
    local_db = dataBase.DataBase()
    table_name = "activite4"
    table_attributes = [
        "time Date", "score integer", "source string", "destination string",
        "result string"
    ]
    local_db.create_Table(table_name, table_attributes)
    #Save window's size to use later
    windowSave = Window.size

    #Creation d'une liste de sons ou seront stockees tous les sons avec leurs categories respectives
    SoundList = []
    score = NumericProperty(0)
    clock = NumericProperty(0)
    porte1 = ObjectProperty(None)
    porte2 = ObjectProperty(None)
    porte3 = ObjectProperty(None)
    sound = SoundLoader
    category = ''

    def sound_init(self):
        #Dans cette methode on remplit notre liste de sons en parcourant le fichier ou se trouvent tous les noms des sons avec leurs categories
        #Cete methode est appelee dans la methode new_round
        # Opening file reading mode
        loaded_file = open("./activite4.txt", "r")
        #read the first line
        line = loaded_file.readline()

        while (line != "endfile"):
            if (line[0] != '#'):
                tab_res = line.split('&')
                tab_save = tab_res[1].split('/')
                tab_name = tab_save[2].split('.')
                if (tab_res[0] == "Sound"):
                    sound = tab_res[1]
                    #updating form's list
                    self.SoundList.append(sound)
#read the next line
            line = loaded_file.readline()

    def new_round(self):
        #Cette fonction est appelee quand le joueur gagne une partie et souhaite rejouer.
        #On choisit un nombre aleatoiret afin de tirer un nouveau son de la liste.
        self.sound_init()
        size_list_sound = len(self.SoundList)
        rand_sound = random.randint(0, size_list_sound - 1)
        loaded_file = open("./activite4.txt", "r")
        #read the first line
        line = loaded_file.readline()
        self.sound = self.SoundList[rand_sound]
        #On met a jour la categorie de la classe courante = categorie du nouveau son tire
        while (line != "endfile"):
            if (line[0] != '#'):
                tab_res = line.split('&')
                tab_save = tab_res[1].split('/')
                tab_name = tab_save[2].split('.')
                if (tab_res[0] == "Sound"):
                    if (tab_res[1] == self.sound):
                        Activite4.category = tab_res[2]
                        print('est', str(self.category))
            #read the next line
            line = loaded_file.readline()

        print('la categorie du son', str(self.sound))
        print('est', str(self.category))
        return self.sound

    def increment_clock(self, dt):
        self.clock += 1

    def update(self, dt):
        if (Window.size != self.windowSave):
            self.windowSave = Window.size
            self.updateWidget()
            return False

    def on_winning(self):
        #Methode mettant en place une fenetre avec differents boutons:
        layout = BoxLayout(orientation='vertical')

        def callback(instance):
            #Si l'utilisateur clique sur rejouer, on remet le score et la date a 0, on refait appel a new_round et on lance le nouveau son
            if (instance.text == 'REJOUER'):
                sound1.stop()
                self.new_round()
                popup.dismiss()
                self.score = 0
                self.clock = 0
                sound = SoundLoader.load(self.sound)
                sound.play()
            #Si l'utilisateur clique sur Menu on lance le Menu
            if (instance.text == 'MENU'):
                sound1.stop()
                popup.dismiss()
                return menu.MenuApp().run()
            #Si l'utilisateur clique sur "quitter" on stoppe l'application
            if (instance.text == 'QUITTER LE JEU'):
                sound1.stop()
                popup.dismiss()
                Activite1_difficultApp().stop()

            print('The button <%s> is being pressed' % instance.text)

        #Creation du boutton 1 "rejouer"
        btn1 = Button(text='REJOUER')
        btn1.bind(on_press=callback)
        #Creation du boutton 2 Menu
        btn2 = Button(text='MENU')
        btn2.bind(on_press=callback)

        #Creation du boutton 3 Quitter Le jeu
        btn3 = Button(text='QUITTER LE JEU')
        btn3.bind(on_press=callback)
        layout.add_widget(btn1)
        layout.add_widget(btn2)
        layout.add_widget(btn3)
        popup = Popup(title='Felicitations ! \nScore : ' + str(self.score) +
                      '\nTemps: ' + str(self.clock) + ' secondes',
                      title_size='20sp',
                      title_color=[0.5, 1, 1, 1],
                      title_font='Red',
                      content=layout,
                      size_hint=(None, None),
                      size=(400, 400),
                      auto_dismiss=False)
        popup.open()
        sound1 = SoundLoader.load('../sound/finished.wav')
        sound1.play()

#Methode appelee dans le .kv:

    #Si l'utilisateur clique sur le bouton Aide en haut a gauche de la fenetre de jeu, une fenetre expliquant le fonctionnement du jeu apparaitra
    #boutton cree dans le .kv
    def aide(self):
        l = BoxLayout(orientation='vertical')

        popup = Popup(
            title='Aide',
            content=Label(
                text=
                'Laisse toi guider par le son pour trouver \nla bonne porte. Si le son vient de la droite,\n clique sur la porte de droite, si le son\n vient de la gauche, clique sur la partie gauche, sinon,\n clique sur la porte en face ! .'
            ),
            size_hint=(None, None),
            size=(400, 200),
        )
        popup.open()

    #Methode appelee dans le .kv:
    #Si l'utilisateur clique sur le bouton Menu en haut a gauche de la fenetre de jeu, il sera redirige vers le Menu
    #Boutton cree dans le .kv
    def menu(self):
        return menu.MenuApp().run()

    #Methode appellee dans le .kv:
    #Si l'utilisateur clique le boutton Quitter en haut a gauche de la fenetre de jeu, l'application s'arretera
    #Boutton cree dans le .kv
    def stop(self):
        return Activite1_difficultApp().stop()