Exemplo n.º 1
0
def rkick(word, word_eol, userdata):
    #try:
    reason = select((
                     'Goodbye!','See you later.','Cya.','Bye.','Later!',
                     'Kindergarden is elsewhere!','Ugh. BYE!','G\'day',
                     'Seeya later!','Be gone!','This is awkward. Bye.',
                     'I didn\'t do it!'
                    ))
    if len(word) == 2:
        # Assume they supplied a username
        return xchat.command('kick %s %s' % (word[1], reason))
    elif len(word) == 1:
        # Assume they want a random user
        list = xchat.get_list("users") 
        if not list:
            return xchat.prnt(help)
        user = select((list))
        return xchat.command('kick %s %s' % (user.nick, reason))
    else:
        # Assume they entered some weird stuff
        return xchat.prnt(help)
    #except:
    #    xchat.prnt(help)
    
    return xchat.EAT_ALL
Exemplo n.º 2
0
 def define_action(act_a, ac, phrase):
     action = act_a
     selection = select(players)
     if action == ac:
         killer = select(players)
         while killer == selection:
             killer = select(players)
         print(phrase.replace("$k", killer).replace("$s", selection), end = ' ')
Exemplo n.º 3
0
 async def steal(self, ctx, *, message):
     """Steal something! Be careful not to get caught..."""
     possibleactions = ["steal", "steal", "getcaught"]
     action = select(possibleactions)
     if action == "steal":
         message = "You successfully stole " + message + "!"
     elif action == "getcaught":
         punishments = ["fine", "comserv", "prison", "serverban"]
         punishment = select(punishments)
         if punishment == "fine":
             fines = [
                 "10", "50", "100", "250", "500", "1000", "2500", "5000",
                 "10000", "25000", "50000", "100000", "250000", "500000"
             ]
             amount = select(fines)
             message = "You got caught! Your punishment is a fine of $" + amount + "!"
         elif punishment == "comserv":
             possiblehours = [
                 "50", "100", "250", "500", "1000", "2500", "5000"
             ]
             hours = select(possiblehours)
             message = "You got caught! Your punishment is " + hours + " hours of community service!"
         elif punishment == "prison":
             possibleyears = [
                 "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11",
                 "12", "13", "14", "15", "16", "17", "18", "19", "20", "21",
                 "22", "23", "24", "25"
             ]
             years = select(possibleyears)
             message = "You got caught! Your punishment is " + years + " years in prison!"
         elif punishment == "serverban":
             units = ["d", "w", "m", "i"]
             unit = select(units)
             if unit == "d":
                 possibledays = ["1", "2", "3", "4", "5", "6", "7"]
                 days = select(possibledays)
                 message = "You got caught! Your punishment is a ban from this server for " + days + " days!\n*Note: This is only a joke, you won't actually get banned.*"
             elif unit == "w":
                 possibleweeks = ["1", "2", "3", "4"]
                 weeks = select(possibleweeks)
                 message = "You got caught! Your punishment is a ban from this server for " + weeks + " weeks!\n*Note: This is only a joke, you won't actually get banned.*"
             elif unit == "m":
                 possiblemonths = [
                     "1", "2", "3", "4", "5", "6", "7", "8", "9", "10",
                     "11", "12"
                 ]
                 months = select(possiblemonths)
                 message = "You got caught! Your punishment is a ban from this server for " + months + " months!\n*Note: This is only a joke, you won't actually get banned.*"
             elif unit == "i":
                 message = "You got caught! Your punishment is a permanent ban from this server!\n*Note: This is only a joke, you won't actually get banned.*"
     await ctx.send(
         message.replace("@everyone",
                         "@.everyone").replace("@here", "@.here"))
Exemplo n.º 4
0
 async def yes(self, ctx, *, message):
     """Similar to echo, but repeats the output several times."""
     loopcount = select(1,10)
     final = message
     for i in range(1,loopcount):
         final = final + "\n" + message
     await ctx.send(final.replace("@everyone", "@\u200beveryone").replace("@here", "@\u200bhere"))
Exemplo n.º 5
0
 def define_gun(zgun_a, ac, gun):
     if rint(1, 10) != 5:
         action = zgun_a
         selection = select(players)
         if action == ac:
             killer = select(players)
             while killer == selection:
                 killer = select(players)
             print(killer + ' killed ' + selection + " with a", gun, end = ' ')
             players.remove(selection)
     else:
         action = gun_a
         selection = select(players)
         if action == ac:
             print(selection + " commited suicide with a", gun, end = ' ')
             players.remove(selection)
Exemplo n.º 6
0
def dostuff(samplertt,counter,congwin):
	ring = select([0.25,0.5,0.75,1])
	temp = 0 
	if ring == 0.25:
		temp = formalize(1.85*samplertt[-1])
		samplertt.append(temp)
		counter += 1
	elif ring == 0.5:
		temp = formalize(0.65*samplertt[-1])
		samplertt.append(temp)
		counter += 1
	elif ring == 0.75:
		temp2 = formalize(1.6*samplertt[-1])
		samplertt.append(temp2)
		counter += 1
		if counter+1 <200:
			temp3 = formalize(0.7*samplertt[-1])
			samplertt.append(temp3)
			counter += 1
			coin = bell(0,1)
			probability = 0.6*(1-exp(-congwin/25.0))
			if (coin - probability)<=0:
				state = False
				congwin = congevo(congwin,state) #here we have segment loss
			else:
				state = True
				congwin = congevo(congwin,state) #here we pass it
	else:
		samplertt,counter = normalestimation(samplertt,counter)
	return samplertt,counter,congwin
Exemplo n.º 7
0
def hug(word, word_eol, userdata):
    response = select((
                       'a nice warm hug','a nice warm cuddle','a bear hug',
                       'a snuggly hug','a huge hug','a hug','a small hug',
                       'a weird hug','an awkward hug'
                       ))
    try:
        xchat.command('me gives \x02%s\x02 %s' % (word[1], response))
    except:
        xchat.prnt(help)
        
    return xchat.EAT_ALL
Exemplo n.º 8
0
def meme_callback(message):
    tmp = yield from client.send_message(message.channel, "Getting memes")

    headerData = {"User-Agent": "Part of a discord bot", "From": "CUB3D"}

    redditResponce = requests.get("http://reddit.com/r/dankmemes/hot.json", headerData)
    json = redditResponce.json()
    if "error" in json:
        if int(json["error"]) == 429:
            print("Too many requests")
            yield from client.edit_message(tmp, "Error: Too dank, much request (try again later)")
            return

    children = json["data"]["children"]
    selected = select(children)
    url = selected["data"]["url"]

    print("Image URL:", url)

    yield from client.edit_message(tmp, str(url))
Exemplo n.º 9
0
def dostuff(samplertt,counter):
	ring = select([0.25,0.5,0.75,1])
	temp = 0 
	if ring == 0.25:
		temp = formalize(1.85*samplertt[-1])
		samplertt.append(temp)
		counter += 1
	elif ring == 0.5:
		temp = formalize(0.65*samplertt[-1])
		samplertt.append(temp)
		counter += 1
	elif ring == 0.75:
		temp2 = formalize(1.6*samplertt[-1])
		samplertt.append(temp2)
		counter += 1
		if counter+1 <200:
			temp3 = formalize(0.7*samplertt[-1])
			samplertt.append(temp3)
			counter += 1
	else:
		samplertt,counter = normalestimation(samplertt,counter)
	return samplertt,counter
Exemplo n.º 10
0
 def switch_quiz(self, quiz_filer=None):
     """
     Set the Userinterface to test a different Quiz (represented by a 
     Quiz_Filer object or randomly selected).
     """
     # disconnect old listeners #
     quiz_filer.quiz.disconnect('question_changed', self.update_gui)
     quiz_filer.quiz.disconnect('break_time', self.start_relax_time)
     # replace #
     if quiz_filer == None:
         quiz_filer = random.select(self.quiz_filer_list)
     self.quiz_filer = quiz_filer
     self.quiz = quiz_filer.quiz
     self.update_gui()
     # show and hide notebookpanels #
     if not quiz_filer.type in self.SHOW_TABS:
         print _('Warning: unknown quiz type "%s".') % quiz_filer.type
         type = "all"
     else:
         type = self.quiz_filer.type
     for tab, visi in zip(self.main_notbook_tabs.itervalues(),
                          self.SHOW_TABS[type]):
         for widget in tab:  # tab is tab-label + tab-content
             if visi:
                 widget.show()
             else:
                 widget.hide()
     # show, hide and settext of combobox #
     if quiz_filer.all_subquizzes == []:
         self.subquiz_combobox.hide()
     else:
         for i in range(2):  # dirty clear combobox
             self.subquiz_combobox.remove_text(0)
         for subquiz in quiz_filer.all_subquizzes:
             self.subquiz_combobox.append_text(subquiz)
         self.subquiz_combobox.set_active(self.quiz.ask_from)
         self.subquiz_combobox.show()
     #
     for label in self.question_topic_labels:
         label.set_markup("<b>%s</b>" %
                          quiz_filer.question_topic[self.quiz.ask_from])
     # treeview #
     ## Question/Answer-Columns ##
     for column in self.word_treeview.get_columns():
         self.word_treeview.remove_column(column)
     for i, title in enumerate(quiz_filer.data_name):
         tvcolumn = gtk.TreeViewColumn(title,
                                       gtk.CellRendererText(),
                                       text=i)
         self.word_treeview.append_column(tvcolumn)
     ## toggler ##
     toggler = gtk.CellRendererToggle()
     toggler.connect('toggled', self.on_treeview_toogled)
     tvcolumn = gtk.TreeViewColumn(_("test"), toggler)
     tvcolumn.add_attribute(toggler, "active", 2)
     self.word_treeview.append_column(tvcolumn)
     self.word_treeview.set_model(quiz_filer.treestore)
     # clean statusbar #
     self.statusbar1.pop(self.statusbar_contextid["last_answer"])
     # connect listeners #
     quiz_filer.quiz.connect('question_changed', self.update_gui)
     quiz_filer.quiz.connect('break_time', self.start_relax_time)
Exemplo n.º 11
0
     print 'decision tree prediction: ' + str(d_tree)
     #print '\tprob:' + str(fit_dtree.predict_proba(test_X))
     print 'KNN prediciton: ' + str(knn)
     #print '\tprob:' + str(fit_neigh.predict_proba(test_X))
     #print OvO
     print 'One vs.Rest prediction: ' + str(OvR)
     #print '\tprob:' + str(fit_OvR.predict_proba(test_X))
     if OvR == knn:
         guess = OvR
     else:
         guess = d_tree
     if str(guess) == 'test':
         y_copy = list(y_words)
         while 'test' in y_words:
             y_copy.remove('test')
         guess = random.select(y_copy)
     os.system('espeak ' + str(guess) + ' &> /dev/null')
     print 'best guess: ' + str(guess)
 else:
     print 'Letters excluded...'
     OneVone = OneVsOneClassifier(LinearSVC(random_state=0))
     OneVrest = OneVsRestClassifier(RandomForestClassifier(random_state=0))
     DTree = DecisionTreeClassifier(random_state=0)
     neigh = KNeighborsClassifier(n_neighbors=3)
     fit_dtree = DTree.fit(train_X_words, y_words)
     fit_neigh = neigh.fit(train_X_words, y_words)
     OvR = " "
     #fit_OvO = OneVone.fit(train_X_words, y_words)
     try:
         fit_OvR = OneVrest.fit(train_X_words, y_words)
         OvR = fit_OvR.predict(test_X)
    def __getitem__(self, idx):
        if type( self.augmentation) is str and 'affine' in self.augmentation:
            strech = (self.max_strech*2)*np.random.random() - self.max_strech +1
            #self.max_rot_rad = self.max_rot_deg/180 * np.pi
            skew = (self.max_rot_rad*2)*np.random.random() - self.max_rot_rad
        if self.include_stroke_aug:
            thickness_change= np.random.randint(-4,5)
            fg_shade = np.random.random()*0.25 + 0.75
            bg_shade = np.random.random()*0.2
            blur_size = np.random.randint(2,4)
            noise_sigma = np.random.random()*0.02

        batch=[]

        if self.triplet=='hard':
            authors = random.sample(self.authors.keys(),self.triplet_author_size)
            alines=[]
            for author in authors:
                if len(self.authors[author])>=self.triplet_sample_size*self.batch_size:
                    lines = random.sample(range(len(self.authors[author])),self.triplet_sample_size*self.batch_size)
                else:
                    lines = list(range(len(self.authors[author])))
                    random.shuffle(lines)
                    dif = self.triplet_sample_size*self.batch_size-len(self.authors[author])
                    lines += lines[:dif]
                alines += [(author,l) for l in lines]
        else:


            inst = self.lineIndex[idx]
            author=inst[0]
            lines=inst[1]


            alines = [(author,l) for l in lines]
            used_lines = set(lines)
            if self.triplet:
                if len(self.authors[author])<=2*self.batch_size:
                    for l in range(len(self.authors[author])):
                        if l not in used_lines:
                            alines.append((author,l))
                    if len(alines)<2*self.batch_size:
                        dif = 2*self.batch_size - len(alines)
                        for i in range(dif):
                            alines.append(alines[self.batch_size+i])
                else:
                    unused_lines = set(range(len(self.authors[author])))-used_lines
                    for i in range(self.batch_size):
                        l = random.select(unused_lines)
                        unused_lines.remove(l)
                        alines.append((author,l))
                
                other_authors = set(range(len(self.authors)))
                other_authors.remove(author)
                author = random.select(other_authors)
                unused_lines = set(range(len(self.authors[author])))-used_lines
                for i in range(self.batch_size):
                    l = random.select(unused_lines)
                    unused_lines.remove(l)
                    alines.append((author,l))

            

        images=[]
        for author,line in alines:
            if line>=len(self.authors[author]):
                line = (line+37)%len(self.authors[author])
            img_path, lb, gt = self.authors[author][line]
            img_path = os.path.join(self.dirPath,'images_gray',img_path)

            if self.no_spaces:
                gt = gt.replace(' ','')
            if type(self.augmentation) is str and 'normalization' in  self.augmentation and self.normalized_dir is not None and os.path.exists(os.path.join(self.normalized_dir,'{}_{}.png'.format(author,line))):
                img = cv2.imread(os.path.join(self.normalized_dir,'{}_{}.png'.format(author,line)),0)
                readNorm=True
            else:
                img = cv2.imread(img_path,0)
                if img is None:
                    print('Error, could not read image: {}'.format(img_path))
                    return None
                lb[0] = max(lb[0],0)
                lb[2] = max(lb[2],0)
                lb[1] = min(lb[1],img.shape[0])
                lb[3] = min(lb[3],img.shape[1])
                img = img[lb[0]:lb[1],lb[2]:lb[3]] #read as grayscale, crop line
                readNorm=False


            if img.shape[0] != self.img_height:
                if img.shape[0] < self.img_height and not self.warning:
                    self.warning = True
                    print("WARNING: upsampling image to fit size")
                percent = float(self.img_height) / img.shape[0]
                if img.shape[1]*percent > self.max_width:
                    percent = self.max_width/img.shape[1]
                img = cv2.resize(img, (0,0), fx=percent, fy=percent, interpolation = cv2.INTER_CUBIC)
                if img.shape[0]<self.img_height:
                    diff = self.img_height-img.shape[0]
                    img = np.pad(img,((diff//2,diff//2+diff%2),(0,0)),'constant',constant_values=255)
            elif img.shape[1]> self.max_width:
                percent = self.max_width/img.shape[1]
                img = cv2.resize(img, (0,0), fx=percent, fy=percent, interpolation = cv2.INTER_CUBIC)
                if img.shape[0]<self.img_height:
                    diff = self.img_height-img.shape[0]
                    img = np.pad(img,((diff//2,diff//2+diff%2),(0,0)),'constant',constant_values=255)

            if self.augmentation=='affine':
                if img.shape[1]*strech > self.max_width:
                    strech = self.max_width/img.shape[1]
            images.append( (line,gt,img,author) )
            #we split the processing here so that strech will be adjusted for longest image in author batch


        for line,gt,img,author in images:
            if self.fg_masks_dir is not None:
                fg_path = os.path.join(self.fg_masks_dir,'{}_{}.png'.format(author,line))
                fg_mask = cv2.imread(fg_path,0)
                fg_mask = fg_mask/255
                if fg_mask.shape!=img[:,:].shape:
                    print('Error, fg_mask ({}, {}) not the same size as image ({})'.format(fg_path,fg_mask.shape,img[:,:,0].shape))
                    th,fg_mask = cv2.threshold(img,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
                    fg_mask = 255-fg_mask
                    ele = cv2.getStructuringElement(  cv2.MORPH_ELLIPSE, (9,9) )
                    fg_mask = cv2.dilate(fg_mask,ele)
                    fg_mask = fg_mask/255
            else:
                fg_mask=None

                    
            if type(self.augmentation) is str and 'normalization' in  self.augmentation and not readNorm:
                img = normalize_line.deskew(img)
                img = normalize_line.skeletonize(img)
                if self.normalized_dir is not None:
                    cv2.imwrite(os.path.join(self.normalized_dir,'{}_{}.png'.format(author,line)),img)
            if type(self.augmentation) is str and 'affine' in  self.augmentation:
                img,fg_mask = augmentation.affine_trans(img,fg_mask,skew,strech)
            elif self.augmentation is not None and (type(self.augmentation) is not None or 'warp' in self.augmentation):
                #img = augmentation.apply_random_color_rotation(img)
                img = augmentation.apply_tensmeyer_brightness(img)
                img = grid_distortion.warp_image(img)
                assert(fg_mask is None)

            if self.include_stroke_aug:
                new_img = augmentation.change_thickness(img,thickness_change,fg_shade,bg_shade,blur_size,noise_sigma)
                if len(new_img.shape)==2:
                    new_img = new_img[...,None]
                new_img = new_img*2 -1.0

            if len(img.shape)==2:
                img = img[...,None]

            img = img.astype(np.float32)
            if self.remove_bg:
                img = 1.0 - img / 256.0
                #kernel = torch.FloatTensor(7,7).fill_(1/49)
                #blurred_mask = F.conv2d(fg_mask,kernel,padding=3)
                blurred_mask = cv2.blur(fg_mask,(7,7))
                img *= blurred_mask[...,None]
                img = 2*img -1
            else:
                img = 1.0 - img / 128.0



            if len(gt) == 0:
                return None
            gt_label = string_utils.str2label_single(gt, self.char_to_idx)

            if self.styles:
                style_i = self.npr.choice(len(self.styles[author][id]))
                style = self.styles[author][id][style_i]
            else:
                style=None
            name = '{}_{}'.format(author,line)
            if self.identity_spaced:
                spaced_label = gt_label[:,None].astype(np.long)
            else:
                spaced_label = None if self.spaced_by_name is None else self.spaced_by_name[name]
                if spaced_label is not None:
                    assert(spaced_label.shape[1]==1)
            toAppend= {
                "image": img,
                "gt": gt,
                "style": style,
                "gt_label": gt_label,
                "spaced_label": spaced_label,
                "name": name,
                "center": self.center,
                "author": author,
                "author_idx": self.author_list.index(author)
                
                }
            if self.fg_masks_dir is not None:
                toAppend['fg_mask'] = fg_mask
            if self.include_stroke_aug:
                toAppend['changed_image'] = new_img
            batch.append(toAppend)
            
        #batch = [b for b in batch if b is not None]
        #These all should be the same size or error
        assert len(set([b['image'].shape[0] for b in batch])) == 1
        assert len(set([b['image'].shape[2] for b in batch])) == 1

        dim0 = batch[0]['image'].shape[0]
        dim1 = max([b['image'].shape[1] for b in batch])
        dim2 = batch[0]['image'].shape[2]

        all_labels = []
        label_lengths = []
        if self.spaced_by_name is not None or self.identity_spaced:
            spaced_labels = []
        else:
            spaced_labels = None
        max_spaced_len=0

        input_batch = np.full((len(batch), dim0, dim1, dim2), PADDING_CONSTANT).astype(np.float32)
        if self.fg_masks_dir is not None:
            fg_masks = np.full((len(batch), dim0, dim1, 1), 0).astype(np.float32)
        if self.include_stroke_aug:
            changed_batch = np.full((len(batch), dim0, dim1, dim2), PADDING_CONSTANT).astype(np.float32)
        for i in range(len(batch)):
            b_img = batch[i]['image']
            toPad = (dim1-b_img.shape[1])
            if 'center' in batch[0] and batch[0]['center']:
                toPad //=2
            else:
                toPad = 0
            input_batch[i,:,toPad:toPad+b_img.shape[1],:] = b_img
            if self.fg_masks_dir is not None:
                fg_masks[i,:,toPad:toPad+b_img.shape[1],0] = batch[i]['fg_mask']
            if self.include_stroke_aug:
                changed_batch[i,:,toPad:toPad+b_img.shape[1],:] = batch[i]['changed_image']

            l = batch[i]['gt_label']
            all_labels.append(l)
            label_lengths.append(len(l))

            if spaced_labels is not None:
                sl = batch[i]['spaced_label']
                spaced_labels.append(sl)
                max_spaced_len = max(max_spaced_len,sl.shape[0])

        #all_labels = np.concatenate(all_labels)
        label_lengths = torch.IntTensor(label_lengths)
        max_len = label_lengths.max()
        all_labels = [np.pad(l,((0,max_len-l.shape[0]),),'constant') for l in all_labels]
        all_labels = np.stack(all_labels,axis=1)
        if self.spaced_by_name is not None or self.identity_spaced:
            spaced_labels = [np.pad(l,((0,max_spaced_len-l.shape[0]),(0,0)),'constant') for l in spaced_labels]
            ddd = spaced_labels
            spaced_labels = np.concatenate(spaced_labels,axis=1)
            spaced_labels = torch.from_numpy(spaced_labels)
            assert(spaced_labels.size(1) == len(batch))


        images = input_batch.transpose([0,3,1,2])
        images = torch.from_numpy(images)
        labels = torch.from_numpy(all_labels.astype(np.int32))
        #label_lengths = torch.from_numpy(label_lengths.astype(np.int32))
        if self.fg_masks_dir is not None:
            fg_masks = fg_masks.transpose([0,3,1,2])
            fg_masks = torch.from_numpy(fg_masks)
        
        if batch[0]['style'] is not None:
            styles = np.stack([b['style'] for b in batch], axis=0)
            styles = torch.from_numpy(styles).float()
        else:
            styles=None
        mask, top_and_bottom, center_line = makeMask(images,self.mask_post, self.mask_random)
        ##DEBUG
        #for i in range(5):
        #    mask2, top_and_bottom2 = makeMask(images,self.mask_post, self.mask_random)
        #    #extra_masks.append(mask2)
        #    mask2 = ((mask2[0,0]+1)/2).numpy().astype(np.uint8)*255
        #    cv2.imshow('mask{}'.format(i),mask2)
        #mask = ((mask[0,0]+1)/2).numpy().astype(np.uint8)*255
        #cv2.imshow('mask'.format(i),mask)
        #cv2.waitKey()
        toRet= {
            "image": images,
            "mask": mask,
            "top_and_bottom": top_and_bottom,
            "center_line": center_line,
            "label": labels,
            "style": styles,
            "label_lengths": label_lengths,
            "gt": [b['gt'] for b in batch],
            "spaced_label": spaced_labels,
            "name": [b['name'] for b in batch],
            "author": [b['author'] for b in batch],
            "author_idx": [b['author_idx'] for b in batch],
        }
        if self.fg_masks_dir is not None:
            toRet['fg_mask'] = fg_masks
        if self.include_stroke_aug:
            changed_images = changed_batch.transpose([0,3,1,2])
            changed_images = torch.from_numpy(changed_images)
            toRet['changed_image']=changed_images
        return toRet
Exemplo n.º 13
0
 def player2(self):
     if choices != []:
         player2 = select(choices)
         return player2
     elif choices == []:
         return "Stalemate"
Exemplo n.º 14
0
import random
while True:
	pdf = input("どれか選んでね (R, P, S) 終了するときは(e)")
	tsp = random.select(["R","P","S"])
	if pdf == tsp:
		print ("あいこ")
	elif (pdf == "R" and tsp == "P") or (pdf == "P" and tsp == "S") or (pdf == "S" and tsp == "R"):
		print("負け")
	elif (pdf == "P" and tsp == "R") or (pdf == "R" and tsp == "S") or (pdf == "S" and tsp == "P"):
		print("勝ち")
Exemplo n.º 15
0
    play = input("Enter a number between 1 and 9 : ")

    if int(play) not in choices:
        play = input(f'''
That number has already been played. 
Available numbers are ; {choices}
Enter a number fom the available choices : ''')

    for i in board:
        for j in i:
            j = (i.index(j))
            if int(play) == i[j]:
                i[j] = "x"
                choices.remove(int(play))

    comp = select(choices)

    for i in board:
        for j in i:
            j = (i.index(j))
            if comp == i[j]:
                i[j] = "o"
                choices.remove(comp)

    game = f""" 
            {board[0][0]} | {board[0][1]} | {board[0][2]}
            --+---+--
            {board[1][0]} | {board[1][1]} | {board[1][2]}
            --+---+--
            {board[2][0]} | {board[2][1]} | {board[2][2]}
        """
Exemplo n.º 16
0
 def switch_quiz(self, quiz_filer=None):
     """
     Set the Userinterface to test a different Quiz (represented by a 
     Quiz_Filer object or randomly selected).
     """
     # disconnect old listeners #
     quiz_filer.quiz.disconnect('question_changed', self.update_gui)
     quiz_filer.quiz.disconnect('break_time', self.start_relax_time)
     # replace #
     if quiz_filer == None:
         quiz_filer = random.select(self.quiz_filer_list)
     self.quiz_filer = quiz_filer
     self.quiz = quiz_filer.quiz
     self.update_gui()
     # show and hide notebookpanels #
     if not quiz_filer.type in self.SHOW_TABS:
         print _('Warning: unknown quiz type "%s".') % quiz_filer.type
         type = "all"
     else:
         type = self.quiz_filer.type
     for tab, visi in zip(self.main_notbook_tabs.itervalues(),
             self.SHOW_TABS[type]):
         for widget in tab:   # tab is tab-label + tab-content
             if visi:
                 widget.show()
             else:
                 widget.hide()
     # show, hide and settext of combobox #
     if quiz_filer.all_subquizzes == []:
         self.subquiz_combobox.hide()
     else:
         for i in range(2):            # dirty clear combobox
             self.subquiz_combobox.remove_text(0)
         for subquiz in quiz_filer.all_subquizzes:
             self.subquiz_combobox.append_text(subquiz)
         self.subquiz_combobox.set_active(self.quiz.ask_from)
         self.subquiz_combobox.show()
     #
     for label in self.question_topic_labels:
         label.set_markup("<b>%s</b>" % 
                 quiz_filer.question_topic[self.quiz.ask_from])
     # treeview #
     ## Question/Answer-Columns ##
     for column in self.word_treeview.get_columns():
         self.word_treeview.remove_column(column)
     for i, title in enumerate(quiz_filer.data_name):
         tvcolumn = gtk.TreeViewColumn(title,
                 gtk.CellRendererText(), text=i)
         self.word_treeview.append_column(tvcolumn)
     ## toggler ##
     toggler = gtk.CellRendererToggle()
     toggler.connect( 'toggled', self.on_treeview_toogled )
     tvcolumn = gtk.TreeViewColumn(_("test"), toggler)
     tvcolumn.add_attribute(toggler, "active", 2)
     self.word_treeview.append_column(tvcolumn)
     self.word_treeview.set_model(quiz_filer.treestore)
     # clean statusbar #
     self.statusbar1.pop(self.statusbar_contextid["last_answer"])
     # connect listeners #
     quiz_filer.quiz.connect('question_changed', self.update_gui)
     quiz_filer.quiz.connect('break_time', self.start_relax_time)