def intensity_0(line): if line[0]: # If change value is 1 correct_line = line[1].split(" ") len_sen = len(correct_line) line = copy.copy(correct_line) int_range = [i for i in range(2, len_sen - 2)] if random.randint(0, 1): # choose adjacent if 1 or one word apart if len_sen > 20: changed = swap_adjacent(line, 5, int_range) elif 20 >= len_sen >= 10: changed = swap_adjacent(line, 3, int_range) elif 10 > len_sen >= 5: changed = swap_adjacent(line, 2, int_range) else: print(line) changed = swap_adjacent(line, 1, int_range) else: int_range[0] += 1 int_range[-1] -= 1 if len_sen > 30: changed = swap_apart(line, 3, int_range) elif 30 >= len_sen > 15: changed = swap_apart(line, 2, int_range) else: changed = swap_apart(line, 1, int_range) label = Label(False) label.assign(" ".join(correct_line), " ".join(changed)) return label
def make_label(self, text, font=None): if not font: font = self.font label = Label(font, Color.white, Color.medium_blue) label.set_text(text) return label
def intensity_1(line): if line[0]: correct_line = line[1].split(" ")[1:-1] # remove <START> and <END> len_sen = len(correct_line) line = copy.copy(correct_line) correct_line.insert(0, '<START>') correct_line.append('<END>') if len_sen > 40: changed = three_words_swap(line[:len_sen // 2], 2) changed.append(three_words_swap(line[len_sen // 2:], 2)) elif 40 >= len_sen > 20: changed = three_words_swap(line[:len_sen // 3], 1) changed.append( three_words_swap(line[len_sen // 3:2 * len_sen // 3], 1)) changed.append(three_words_swap(line[2 * len_sen // 3:], 1)) elif 20 >= len_sen > 10: changed = three_words_swap(line[:len_sen // 2], 1) changed.append(three_words_swap(line[len_sen // 2:], 1)) else: changed = three_words_swap(line, 1) changed.insert(0, '<START>') changed.append('<END>') answer = "" for value in changed: try: answer = answer + " " + value except: answer = answer + " " + " ".join(value) label = Label(False) label.assign(" ".join(correct_line), answer) return label
def initUI(self): # перемещение self.move(300, 300) # фиксируем ширину и высоту поля self.setFixedSize(Arkanoid.W, Arkanoid.H) # задаём имя программы self.setWindowTitle('Арканоид') # загружаем фоновое изображение self.background = QImage('background.jpg') # создаём кубики self.cubes = Cubes() # созаём ракетку self.racket = Racket(Arkanoid.W / 2 - Racket.W / 2) # создаём шарик self.ball = Ball(Arkanoid.W / 2, Racket.Y - Ball.R, 60) # создаём надпись self.label = Label(150, Arkanoid.H // 2, Arkanoid.W - 300, 60) # создаем очки self.scores = Scores(0, 9, Arkanoid.W, 30) # создаём таймер self.timer = QtCore.QTimer() # заканчиваем время self.timer.timeout.connect(self.tick) # задаём начало счётчика self.timer.start(2) # включаем отслеживание мыши self.setMouseTracking(1) # переходим в состояние запуска self.restart()
def convert_to_label(lines): label_list = [] for line in lines: if not line[0]: label = Label(True) label.assign(line[1]) label_list.append(label) return label_list
def removePlageCharacters(self, plage): label = Label(None, self._label.text.string[0:plage.x] + \ self._label.text.string[plage.y:len(self._label.text.string)], \ characterSize = self._label.characterSize, font=\ self._label.font, style = self._label.style, color=\ self._label.color) label.size = self._label.size self.setLabel(label)
def removeCharacter(self, index): label = Label(None, self._label.text.string[0:index] + \ self._label.text.string[index+1:len(self._label.text.string)], \ characterSize = self._label.characterSize, font=\ self._label.font, style = self._label.style, color=\ self._label.color) label.size = self._label.size self.setLabel(label)
def __init__(self, font, text_color, background_color, selected_color, y, text): Label.__init__(self, font, text_color, background_color, y, text) self.normal_color = background_color self.selected_color = selected_color self.border_color = Color.black self.checked = False self.check_color = Color.black
class Button(Rectangle, Clickable): def __init__(self, font, label, backgroundColor=None, opacity=1.0, borderColor=(0.0,0.0,0.0), borderWidth=1.0, prelightColor=None, textColor=(1.0, 1.0, 1.0), textPrelightColor=None, padding=5.0): Rectangle.__init__(self) Clickable.__init__(self) if backgroundColor is None: self.opacity = 0.0 else: self.normalColor = self.fillColor = backgroundColor self.fillOpacity = opacity self.borderColor = borderColor self.borderWidth = borderWidth self.prelightColor = prelightColor self.textColor = textColor self.textPrelightColor = textPrelightColor self.padding = padding self._label = Label(font, label, textColor) self.addChild(self._label) self._layout() def _layout(self): self._label.update() center = self.getCenter() self.h = self._label.h + self.padding*2 self.w = self._label.w + self.padding*2 self._label.setCenter(self.getCenterRel()) self.setCenter(center) def setTextColor(self, color, update=True): self._label.setColor(color) if update: self._layout() def setLabel(self, label, update=True): self._label.setText(label) if update: self._layout() def setFont(self, font, update=True): self._label.setFont(font) if update: self._layout() def _focused(self): Clickable._focused(self) if self.prelightColor is not None: self.fillColor = self.prelightColor if self.textPrelightColor is not None: self.setTextColor(self.textPrelightColor) def _unfocused(self): Clickable._unfocused(self) self.fillColor = self.normalColor if self.textPrelightColor is not None: self.setTextColor(self.textColor)
def __init__(self, html=None, wordWrap=True, Element=None, **kwargs): if not kwargs.has_key('StyleName'): kwargs['StyleName'] = "gwt-HTML" if html: kwargs['HTML'] = html kwargs['WordWrap'] = wordWrap if Element is None: Element = DOM.createDiv() self.setElement(Element) Label.__init__(self, **kwargs) self.sinkEvents(Event.ONCLICK | Event.MOUSEEVENTS)
def __init__(self, html=None, wordWrap=True, Element=None, **kwargs): if not kwargs.has_key('StyleName'): kwargs['StyleName']="gwt-HTML" if html: kwargs['HTML'] = html kwargs['WordWrap'] = wordWrap if Element is None: Element = DOM.createDiv() self.setElement(Element) Label.__init__(self, **kwargs) self.sinkEvents(Event.ONCLICK | Event.MOUSEEVENTS)
def create_ui(self): label = Label(self.title_font, Color.white, Color.medium_blue) label.set_text('Paused') label.set_y(200) a, b = self.make_spacer(), self.make_spacer() resume_button = self.make_button('Return to Game') exit_button = self.make_button('Quit') louie.connect(self.finish, Button.clicked, resume_button) louie.connect(self.exit, Button.clicked, exit_button) self.widget.create_ui([label, a, resume_button, exit_button, b])
def __createListItem(self, widget, path, name, time, summary): item = QListWidgetItem() item.setSizeHint(QSize(100, 50)) label = Label(widget) label.clicked.connect(self.__listItemClicked) label.setFocusProxy(widget) label.setFixedHeight(50) label.setText(CloudNote.NOTE_FORMAT % (name, time, summary)) label.setWhatsThis(path) widget.addItem(item) widget.setItemWidget(item, label) return item
def __init__(self, parent): super(Sort_Tab, self).__init__(parent=parent) # Variables self.stamvader = lga(None) self.container = linked_output("") # self.counter = 0 # =prune limit in this class, currently deactivated function # Widgets self.buttons = [QtGui.QPushButton(), QtGui.QPushButton()] self.labels = [Label(), Label()] font = QtGui.QFont() font.setPointSize(50) font.setBold(True) self.labels[0].setPixmap( os.path.join(os.path.dirname(sys.argv[0]), "img/nily.png")) self.labels[1].setPixmap( os.path.join(os.path.dirname(sys.argv[0]), "img/nily.png")) self.buttons[0].setMinimumSize(1, 1) self.buttons[0].setText('Links') self.buttons[0].setFont(font) self.buttons[1].setMinimumSize(1, 1) self.buttons[1].setGeometry(QtCore.QRect(10, 140, 711, 261)) self.buttons[1].setText('Rechts') self.buttons[1].setFont(font) # Layout cluster_1 = QtGui.QHBoxLayout() cluster_1.addWidget(self.labels[0], 1) cluster_1.addWidget(self.labels[1], 1) cluster_2 = QtGui.QHBoxLayout() cluster_2.addWidget(self.buttons[0], 1) cluster_2.addWidget(self.buttons[1], 1) layout = QtGui.QVBoxLayout() layout.addLayout(cluster_1, 8) layout.addLayout(cluster_2, 2) self.setLayout(layout) # Actions - buttons self.buttons[0].clicked.connect(self.commitL) self.buttons[1].clicked.connect(self.commitR)
def get_labels_by_page(self): """ Initiate Label object. :return: list with Label objects. """ count = 0 labels_by_page = [] for subject in self.input_json["subjects"]: sb = { "id": subject["id"], "superID": subject["superID"], "assertions": [] } if subject["assertions"] is not None and len( subject["assertions"]) > 0: for assertion in subject["assertions"]: if assertion is not None: if assertion["versions"] and len( assertion["versions"]) > 1: l = Label(assertion) count += 1 sb["assertions"].append(l) labels_by_page.append(sb) print(count) return labels_by_page
def __init__(self, title, buttons, results, directory=None): GenericDialog.__init__(self, title, buttons, results) if directory == None: directory = os.curdir directory = os.path.abspath(directory) # Path access. self._pathframe = HFrame() self._pathframe.minsize = 200, self._pathframe.minsize[1] self._pathframe.padding = 0 self._pathframe.border = BORDER_NONE self._lblpath = Label("#Path:") self._txtpath = Entry(directory) self._txtpath.minsize = 165, self._txtpath.minsize[1] self._lblpath.widget = self._txtpath self._pathframe.add_child(self._lblpath, self._txtpath) # File list browser. self._filelist = FileList(200, 160, directory) self.content.add_child(self._pathframe, self._filelist) # Align anything on the right. self.main.align = ALIGN_RIGHT # Events. self._txtpath.connect_signal(SIG_INPUT, self._set_directory) self._filelist.connect_signal(SIG_LISTCHANGED, self._set_path)
def __init__(self, parent): super(Bannish_Tab, self).__init__(parent=parent) # Variables self.file_list = [] self.list_order = [] self.act_compare = 1 self.container = linked_output("") # Widgets self.labels = [Label(), Label()] self.labels[0].setPixmap( os.path.join(os.path.dirname(sys.argv[0]), "img/nily.png")) self.labels[1].setPixmap( os.path.join(os.path.dirname(sys.argv[0]), "img/nily.png")) self.buttons = [QtGui.QPushButton()] self.output = QtGui.QTextEdit() # Opmaak font = QtGui.QFont() font.setPointSize(25) font.setBold(True) self.buttons[0].setMinimumSize(1, 1) self.buttons[0].setText('Sorteer') self.buttons[0].setFont(font) # Layout cluster_1 = QtGui.QVBoxLayout() cluster_1.addWidget(self.output, 3) cluster_1.addWidget(self.buttons[0], 2) cluster_2 = QtGui.QHBoxLayout() cluster_2.addWidget(self.labels[0], 5) cluster_2.addWidget(self.labels[1], 5) layout = QtGui.QHBoxLayout() layout.addLayout(cluster_1, 1) layout.addLayout(cluster_2, 6) self.setLayout(layout) # Actions self.buttons[0].clicked.connect(self.read_out_list)
def intensity_4(line): if line[0]: correct_line = line[1].split(" ")[1:-1] len_sen = len(correct_line) line = copy.copy(correct_line) init_range = [i for i in range(len_sen)] correct_line.insert(0, '<START>') correct_line.append('<END>') num_words_random = round(len_sen * 0.75) choices = random.choices(init_range, k=num_words_random) for i in range(len(choices) // 2): line[choices[-(i + 1)]], line[choices[i]] = line[choices[i]], line[ choices[-(i + 1)]] line.insert(0, '<START>') line.append('<END>') label = Label(False) label.assign(" ".join(correct_line), " ".join(line)) return label
def __init__(self, manager, editor): from TreeView.Manager import Manager Manager(manager, editor) from Label import Label Label(manager, editor) from Entry import Entry Entry(manager, editor) from Window import Window Window(manager, editor)
def __init__(self, parent): super(bucket_tab, self).__init__(parent=parent) # Variables self.container = linked_output("") # Widgets self.labels = [ Label(), Label(), Label(), Label(), Label(), Label(), Label() ] self.memarrays = [list(), list(), list(), list(), list(), list()] font = QtGui.QFont() font.setPointSize(50) font.setBold(True) # Layout self.labels[0].setPixmap( os.path.join(os.path.dirname(sys.argv[0]), "img/nily.png")) self.labels[1].setPixmap( os.path.join(os.path.dirname(sys.argv[0]), "img/1.png")) self.labels[2].setPixmap( os.path.join(os.path.dirname(sys.argv[0]), "img/2.png")) self.labels[3].setPixmap( os.path.join(os.path.dirname(sys.argv[0]), "img/3.png")) self.labels[4].setPixmap( os.path.join(os.path.dirname(sys.argv[0]), "img/4.png")) self.labels[5].setPixmap( os.path.join(os.path.dirname(sys.argv[0]), "img/5.png")) self.labels[6].setPixmap( os.path.join(os.path.dirname(sys.argv[0]), "img/6.png")) cluster_1 = QtGui.QVBoxLayout() cluster_1.addWidget(self.labels[1], 1) cluster_1.addWidget(self.labels[2], 1) cluster_1.addWidget(self.labels[3], 1) cluster_3 = QtGui.QVBoxLayout() cluster_3.addWidget(self.labels[4], 1) cluster_3.addWidget(self.labels[5], 1) cluster_3.addWidget(self.labels[6], 1) cluster_2 = QtGui.QHBoxLayout() cluster_2.addWidget(self.labels[0], 1) layout = QtGui.QHBoxLayout() layout.addLayout(cluster_1, 2) layout.addLayout(cluster_2, 6) layout.addLayout(cluster_3, 2) self.setLayout(layout)
def getExtra4(self): specs = self.getRecorda() labels = None if specs.Labels: lis = [] labs = specs.Labels.split(",") for lb in labs: lis.append("','".join(Label.getTreeLeaves(lb))) labels = "','".join(lis) return "WHERE?AND SerNr IN ('%s') " % labels
def __init__(self, manager, editor): from Window import Window Window(manager, editor) from ComboBox import ComboBox ComboBox(manager, editor) from Label import Label Label(manager, editor) from OpenButton import Button Button(manager, editor) from CloseButton import Button Button(manager, editor)
def __init__(self, manager, editor): from AddButton import Button Button(manager, editor) from TreeView.Manager import Manager Manager(manager, editor) from Label import Label Label(manager, editor) from RemoveButton import Button Button(manager, editor) from Window import Window Window(manager, editor)
def set_text (self, text=None): """I.set_text (...) -> None Sets the text to display on the ImageButton by referring to the 'text' attribute of its child Label. """ if text != None: if self.child: self.child.set_text (text) else: self.child = Label (text) else: self.child = None
def from_json_file(cls, file_path): data = None try: data = read_json(file_path) except json.JSONDecodeError: raise InvalidLabeledDataFileFormat(file_path) if not isinstance(data, list): raise InvalidLabeledDataFileFormat(file_path) labels = [Label.from_dict(l) for l in data] return cls(labels)
def __init__(self,parent): super(Screening_Tab, self).__init__(parent= parent) # Variables self.container = linked_output("") # Widgets self.buttons = [ QtGui.QPushButton(), QtGui.QPushButton() ] self.labels = [ Label() ] self.labels[0].setPixmap(os.path.join(os.path.dirname(sys.argv[0]),"img/nily.png")) font = QtGui.QFont() font.setPointSize(50) font.setBold(True) self.buttons[0].setMinimumSize(1, 1) self.buttons[0].setText('Wel') self.buttons[0].setFont(font) self.buttons[1].setMinimumSize(1, 1) self.buttons[1].setGeometry(QtCore.QRect(10, 140, 711, 261)) self.buttons[1].setText('Niet') self.buttons[1].setFont(font) # Layout cluster_1 = QtGui.QHBoxLayout() cluster_1.addWidget(self.labels[0],1) cluster_3 = QtGui.QHBoxLayout() cluster_3.addWidget(self.buttons[0],2) cluster_3.addWidget(self.buttons[1],2) layout = QtGui.QVBoxLayout() layout.addLayout(cluster_1,8) layout.addLayout(cluster_3,1) self.setLayout(layout) # Actions - buttons self.buttons[0].clicked.connect(self.commitL) self.buttons[1].clicked.connect(self.commitR)
def set_text (self, text=None): """B.set_text (...) -> None Sets the text to display on the Button. Sets the text to display on the Button by referring to the 'text' attribute of it child Label. """ if text: if self.child: self.child.set_text (text) else: self.child = Label (text) else: self.child = None self.dirty = True
def newLabel(self, pos, labelID=None): if labelID: if labelID in self.labelMap.keys(): raise RuntimeError("Already have a label " \ "with ID '%s'" % labelID ) else: l_id = labelID else: l_id = self._getLabelID() newLabel = Label(pos, self) self.labels.append(newLabel) self.labelMap[l_id] = newLabel return newLabel
def run(self): specs = self.getRecorda() leaves = Label.getTreeLeaves(specs.RootLabel) query7 = Query() query7.sql = "SELECT SerNr, %s,\n" % codeOrder("SerNr", leaves) query7.sql += monthCode("[al].TransDate") query7.sql += "\n, %s, \n" % self.getExtra2(test=1) query7.sql += self.getExtra2(0) query7.sql += "\nFROM %s al\n" % specs.name() query7.sql += self.getExtra("1", "2", val3="33") query7.sql += self.getExtra4() query7.sql += self.getExtra5("WHERE?AND :1") query7.sql += self.getExtra6() query7.sql += self.getExtra7() method = getattr(self, "getExtra3____"[:-4]) query7.sql += method() query7.open() self.run2([100, 200])
def _restoreSession(self, info): for labelInfo in info["labels"]: new_label = Label(*(labelInfo["args"] + (self, ))) self.labels.append(new_label) self.labels[-1]._restoreSession(labelInfo) if info.has_key("labelUID"): self._UID = info["labelUID"] for idx, label in enumerate(self.labels): if info.has_key("labelIDs"): uid = info["labelIDs"][idx] else: uid = self._getLabelID() self.labelMap[uid] = label if info["curLabel"] is None: self.curLabel = None else: self.curLabel = self.labels[info["curLabel"]]
def predict(self, image) -> List[Label]: frame = torchvision.transforms.ToTensor()(image) frame = frame[None, :, :] self.model.eval() prediction = self.model(frame) print(prediction) boxes = prediction[0]["boxes"] labels = prediction[0]["labels"] scores = prediction[0]["scores"] ret = list() for i in range(0, len(boxes)): score: float = float(scores[i].item()) xmin: int = int(boxes[i][0].item()) ymin: int = int(boxes[i][1].item()) xmax: int = int(boxes[i][2].item()) ymax: int = int(boxes[i][3].item()) group: str = classes[str(labels[i].item())]["category"] color: str = classes[str(labels[i].item())]["color"] ret.append(Label(i, group, xmin, xmax, ymin, ymax, color, score)) return ret
def __init__(self, font, label, backgroundColor=None, opacity=1.0, borderColor=(0.0,0.0,0.0), borderWidth=1.0, prelightColor=None, textColor=(1.0, 1.0, 1.0), textPrelightColor=None, padding=5.0): Rectangle.__init__(self) Clickable.__init__(self) if backgroundColor is None: self.opacity = 0.0 else: self.normalColor = self.fillColor = backgroundColor self.fillOpacity = opacity self.borderColor = borderColor self.borderWidth = borderWidth self.prelightColor = prelightColor self.textColor = textColor self.textPrelightColor = textPrelightColor self.padding = padding self._label = Label(font, label, textColor) self.addChild(self._label) self._layout()
def insertTab(self, text, asHTML, beforeIndex=None): """ 1st arg can, instead of being 'text', be a widget. 1st arg can also be None, which results in a blank space between tabs. Use this to push subsequent tabs out to the right hand end of the TabBar. (the "blank" tab, by not being focussable, is not clickable). """ if beforeIndex is None: beforeIndex = asHTML asHTML = False if (beforeIndex < 0) or (beforeIndex > self.getTabCount()): #throw new IndexOutOfBoundsException(); pass if text is None: text = HTML(" ", True) text.setWidth("100%") text.setStyleName("gwt-TabBarRest") self.panel.insert(text, beforeIndex + 1) self.panel.setCellWidth(text, "100%") return try: istext = isinstance(text, str) or isinstance(text, unicode) except: istext = isinstance(text, str) if istext: if asHTML: item = HTML(text) else: item = Label(text) item.setWordWrap(False) else: # passing in a widget, it's expected to have its own style item = text self.insertTabWidget(item, beforeIndex)
def make_label(self, text): label = Label(self.font, Color.white, Color.medium_blue) label.set_text(text) return label
def make_spacer(self): spacer = Label(self.button_font, Color.white, Color.medium_blue) spacer.set_text(' ') return spacer
def set_text(self, text): Label.set_text(self, text)
def execute(self): last_issue = 1 instruction_index = 0 conditional_branch_flag = False unconditional_branch_flag = False branch_label_conditional = None branch_label_unconditional = None hlt_flag = False #for instruction_index, instruction in enumerate(self.instructions): while instruction_index < len(self.instructions): next_index = instruction_index + 1 instruction = self.instructions[instruction_index] current_result = Results() current_result.set_instruction(instruction) current_result.set_instruction_index(instruction_index) instruction_type = self.instruction_type(instruction) if instruction_type == "ADDER": # Fetch Stage fetch_cycle = last_issue # I-Cache Penalty if instruction_index not in ICache.instruction_index_cache_set \ and instruction_index % self.block_size == 0: fetch_cycle += self.penalty #Need to handle Direct Associativity in the future ICache.add_instruction(instruction_index) current_result.set_fetch_stage(fetch_cycle) if hlt_flag: self.result.append(current_result) current_result.print_row() return None # Parsing Instruction to update the memory self.parse_instruction(instruction) if unconditional_branch_flag: unconditional_branch_flag = False next_index = Label.get_label(branch_label_unconditional) branch_label_unconditional = None else: #Issue Stage issue_cycle = fetch_cycle + 1 index, when = self.isAdderFree() if when > issue_cycle: current_result.set_struct_hazard('Y') issue_cycle = when + 1 temp_cycle = issue_cycle for register in instruction.dest_register: if register not in Register.value: Register.value[register] = RegisterObject() temp_cycle = max( Register.value[register].last_write + 1, temp_cycle) if temp_cycle > issue_cycle: current_result.set_waw_hazard('Y') issue_cycle = temp_cycle current_result.set_issue_stage(issue_cycle) last_issue = issue_cycle if conditional_branch_flag: conditional_branch_flag = False next_index = Label.get_label(branch_label_conditional) branch_label_conditional = None else: #Read Stage read_cycle = issue_cycle + 1 temp_cycle = read_cycle #Handling RAW Hazards (Source) for register in instruction.source_register: if register not in Register.value: Register.value[register] = RegisterObject() temp_cycle = max( Register.value[register].last_write + 1, temp_cycle) #Handling RAW Hazards (Destination) for register in instruction.dest_register: if register not in Register.value: Register.value[register] = RegisterObject() temp_cycle = max( Register.value[register].last_write + 1, temp_cycle) temp_cycle = max( Register.value[register].last_read + 1, temp_cycle) if temp_cycle > read_cycle: current_result.set_raw_hazard('Y') read_cycle = temp_cycle current_result.set_read_stage(read_cycle) #Exec Stage exec_cycle = read_cycle + self.adder_cycles current_result.set_exec_stage(exec_cycle) #Write Back Stage write_cycle = exec_cycle + 1 for register in instruction.dest_register: if register not in Register.value: Register.value[register] = RegisterObject() Register.value[register].last_write = write_cycle current_result.set_write_stage(write_cycle) self.adder_units[index].when_available = write_cycle elif instruction_type == "DATA": # Fetch Stage fetch_cycle = last_issue # I-Cache Penalty if instruction_index not in ICache.instruction_index_cache_set \ and instruction_index % self.block_size == 0: fetch_cycle += self.penalty # Need to handle Direct Associativity in the future ICache.add_instruction(instruction_index) current_result.set_fetch_stage(fetch_cycle) if hlt_flag: self.result.append(current_result) current_result.print_row() return None # Parsing Instruction to update the memory self.parse_instruction(instruction) if unconditional_branch_flag: unconditional_branch_flag = False next_index = Label.get_label(branch_label_unconditional) branch_label_unconditional = None else: #Issue Stage (WAW Pending) issue_cycle = fetch_cycle + 1 index, when = self.isDataFree() if when > issue_cycle: current_result.set_struct_hazard('Y') issue_cycle = when + 1 temp_cycle = issue_cycle for register in instruction.dest_register: if register not in Register.value: Register.value[register] = RegisterObject() temp_cycle = max( Register.value[register].last_write + 1, temp_cycle) if temp_cycle > issue_cycle: current_result.set_waw_hazard('Y') issue_cycle = temp_cycle current_result.set_issue_stage(issue_cycle) last_issue = issue_cycle if conditional_branch_flag: conditional_branch_flag = False next_index = Label.get_label(branch_label_conditional) branch_label_conditional = None else: #Read Stage read_cycle = issue_cycle + 1 temp_cycle = read_cycle #Handling RAW Hazards (Source) for register in instruction.source_register: if register not in Register.value: Register.value[register] = RegisterObject() temp_cycle = max( Register.value[register].last_write + 1, temp_cycle) #Handling RAW Hazards (Destination) for register in instruction.dest_register: if register not in Register.value: Register.value[register] = RegisterObject() temp_cycle = max( Register.value[register].last_write + 1, temp_cycle) temp_cycle = max( Register.value[register].last_read + 1, temp_cycle) if temp_cycle > read_cycle: current_result.set_raw_hazard('Y') read_cycle = temp_cycle current_result.set_read_stage(read_cycle) #Exec Stage exec_cycle = read_cycle + self.data_cycles current_result.set_exec_stage(exec_cycle) #Write Back Stage write_cycle = exec_cycle + 1 for register in instruction.dest_register: if register not in Register.value: Register.value[register] = RegisterObject() Register.value[register].last_write = write_cycle current_result.set_write_stage(write_cycle) self.data_units[index].when_available = write_cycle elif instruction_type == "ARITHMETIC": # Fetch Stage fetch_cycle = last_issue # I-Cache Penalty if instruction_index not in ICache.instruction_index_cache_set \ and instruction_index % self.block_size == 0: fetch_cycle += self.penalty # Need to handle Direct Associativity in the future ICache.add_instruction(instruction_index) current_result.set_fetch_stage(fetch_cycle) if hlt_flag: self.result.append(current_result) current_result.print_row() return None # Parsing Instruction to update the memory self.parse_instruction(instruction) if unconditional_branch_flag: unconditional_branch_flag = False next_index = Label.get_label(branch_label_unconditional) branch_label_unconditional = None else: #Issue Stage (WAW Pending) issue_cycle = fetch_cycle + 1 index, when = self.isArithmeticFree() if when > issue_cycle: current_result.set_struct_hazard('Y') issue_cycle = when + 1 temp_cycle = issue_cycle for register in instruction.dest_register: if register not in Register.value: Register.value[register] = RegisterObject() temp_cycle = max( Register.value[register].last_write + 1, temp_cycle) if temp_cycle > issue_cycle: current_result.set_waw_hazard('Y') issue_cycle = temp_cycle current_result.set_issue_stage(issue_cycle) last_issue = issue_cycle if conditional_branch_flag: conditional_branch_flag = False next_index = Label.get_label(branch_label_conditional) branch_label_conditional = None else: #Read Stage read_cycle = issue_cycle + 1 temp_cycle = read_cycle #Handling RAW Hazards (Source) for register in instruction.source_register: if register not in Register.value: Register.value[register] = RegisterObject() temp_cycle = max( Register.value[register].last_write + 1, temp_cycle) #Handling RAW Hazards (Destination) for register in instruction.dest_register: if register not in Register.value: Register.value[register] = RegisterObject() temp_cycle = max( Register.value[register].last_write + 1, temp_cycle) temp_cycle = max( Register.value[register].last_read + 1, temp_cycle) if temp_cycle > read_cycle: current_result.set_raw_hazard('Y') read_cycle = temp_cycle current_result.set_read_stage(read_cycle) #Exec Stage exec_cycle = read_cycle + self.arithmetic_cycles current_result.set_exec_stage(exec_cycle) #Write Back Stage write_cycle = exec_cycle + 1 for register in instruction.dest_register: if register not in Register.value: Register.value[register] = RegisterObject() Register.value[register].last_write = write_cycle current_result.set_write_stage(write_cycle) self.arithmetic_units[ index].when_available = write_cycle elif instruction_type == "MULTIPLIER": # Fetch Stage fetch_cycle = last_issue # I-Cache Penalty if instruction_index not in ICache.instruction_index_cache_set \ and instruction_index % self.block_size == 0: fetch_cycle += self.penalty # Need to handle Direct Associativity in the future ICache.add_instruction(instruction_index) current_result.set_fetch_stage(fetch_cycle) if hlt_flag: self.result.append(current_result) current_result.print_row() return None # Parsing Instruction to update the memory self.parse_instruction(instruction) if unconditional_branch_flag: unconditional_branch_flag = False next_index = Label.get_label(branch_label_unconditional) branch_label_unconditional = None else: #Issue Stage (WAW Pending) issue_cycle = fetch_cycle + 1 index, when = self.isMultiplierFree() if when > issue_cycle: current_result.set_struct_hazard('Y') issue_cycle = when + 1 temp_cycle = issue_cycle for register in instruction.dest_register: if register not in Register.value: Register.value[register] = RegisterObject() temp_cycle = max( Register.value[register].last_write + 1, temp_cycle) if temp_cycle > issue_cycle: current_result.set_waw_hazard('Y') issue_cycle = temp_cycle current_result.set_issue_stage(issue_cycle) last_issue = issue_cycle if conditional_branch_flag: conditional_branch_flag = False next_index = Label.get_label(branch_label_conditional) branch_label_conditional = None else: #Read Stage read_cycle = issue_cycle + 1 temp_cycle = read_cycle #Handling RAW Hazards (Source) for register in instruction.source_register: if register not in Register.value: Register.value[register] = RegisterObject() temp_cycle = max( Register.value[register].last_write + 1, temp_cycle) #Handling RAW Hazards (Destination) for register in instruction.dest_register: if register not in Register.value: Register.value[register] = RegisterObject() temp_cycle = max( Register.value[register].last_write + 1, temp_cycle) temp_cycle = max( Register.value[register].last_read + 1, temp_cycle) if temp_cycle > read_cycle: current_result.set_raw_hazard('Y') read_cycle = temp_cycle current_result.set_read_stage(read_cycle) #Exec Stage exec_cycle = read_cycle + self.multiplier_cycles current_result.set_exec_stage(exec_cycle) #Write Back Stage write_cycle = exec_cycle + 1 for register in instruction.dest_register: if register not in Register.value: Register.value[register] = RegisterObject() Register.value[register].last_write = write_cycle current_result.set_write_stage(write_cycle) self.multiplier_units[ index].when_available = write_cycle elif instruction_type == "DIVIDER": # Fetch Stage fetch_cycle = last_issue # I-Cache Penalty if instruction_index not in ICache.instruction_index_cache_set \ and instruction_index % self.block_size == 0: fetch_cycle += self.penalty # Need to handle Direct Associativity in the future ICache.add_instruction(instruction_index) current_result.set_fetch_stage(fetch_cycle) if hlt_flag: self.result.append(current_result) current_result.print_row() return None # Parsing Instruction to update the memory self.parse_instruction(instruction) if unconditional_branch_flag: unconditional_branch_flag = False next_index = Label.get_label(branch_label_unconditional) branch_label_unconditional = None else: # Issue Stage (WAW Pending) issue_cycle = fetch_cycle + 1 index, when = self.isDividerFree() if when > issue_cycle: current_result.set_struct_hazard('Y') issue_cycle = when + 1 temp_cycle = issue_cycle for register in instruction.dest_register: if register not in Register.value: Register.value[register] = RegisterObject() temp_cycle = max( Register.value[register].last_write + 1, temp_cycle) if temp_cycle > issue_cycle: current_result.set_waw_hazard('Y') issue_cycle = temp_cycle current_result.set_issue_stage(issue_cycle) last_issue = issue_cycle if conditional_branch_flag: conditional_branch_flag = False next_index = Label.get_label(branch_label_conditional) branch_label_conditional = None else: #Read Stage read_cycle = issue_cycle + 1 temp_cycle = read_cycle #Handling RAW Hazards (Source) for register in instruction.source_register: if register not in Register.value: Register.value[register] = RegisterObject() temp_cycle = max( Register.value[register].last_write + 1, temp_cycle) #Handling RAW Hazards (Destination) for register in instruction.dest_register: if register not in Register.value: Register.value[register] = RegisterObject() temp_cycle = max( Register.value[register].last_write + 1, temp_cycle) temp_cycle = max( Register.value[register].last_read + 1, temp_cycle) if temp_cycle > read_cycle: current_result.set_raw_hazard('Y') read_cycle = temp_cycle current_result.set_read_stage(read_cycle) #Exec Stage exec_cycle = read_cycle + self.divider_cycles current_result.set_exec_stage(exec_cycle) #Write Back Stage write_cycle = exec_cycle + 1 for register in instruction.dest_register: if register not in Register.value: Register.value[register] = RegisterObject() Register.value[register].last_write = write_cycle current_result.set_write_stage(write_cycle) self.divider_units[index].when_available = write_cycle elif instruction_type == "BRANCHCONDITIONAL": # Fetch Stage fetch_cycle = last_issue # I-Cache Penalty if instruction_index not in ICache.instruction_index_cache_set \ and instruction_index % self.block_size == 0: fetch_cycle += self.penalty # Need to handle Direct Associativity in the future ICache.add_instruction(instruction_index) current_result.set_fetch_stage(fetch_cycle) if hlt_flag: self.result.append(current_result) current_result.print_row() return None # Parsing Instruction to update the memory branch_label_conditional = self.branch_satisfaction( instruction) if unconditional_branch_flag: unconditional_branch_flag = False next_index = Label.get_label(branch_label_unconditional) branch_label_unconditional = None else: # Issue Stage issue_cycle = fetch_cycle + 1 current_result.set_issue_stage(issue_cycle) last_issue = issue_cycle #Read Stage read_cycle = issue_cycle + 1 temp_cycle = read_cycle #Handling RAW Hazards (Source) for register in instruction.source_register[:-1]: temp_cycle = max( Register.value[register].last_write + 1, temp_cycle) #Handling RAW Hazards (Destination) for register in instruction.dest_register: temp_cycle = max( Register.value[register].last_write + 1, temp_cycle) temp_cycle = max( Register.value[register].last_read + 1, temp_cycle) if temp_cycle > read_cycle: current_result.set_raw_hazard('Y') read_cycle = temp_cycle current_result.set_read_stage(read_cycle) elif instruction_type == "BRANCHUNCONDITIONAL": # Fetch Stage fetch_cycle = last_issue # I-Cache Penalty if instruction_index not in ICache.instruction_index_cache_set \ and instruction_index % self.block_size == 0: fetch_cycle += self.penalty # Need to handle Direct Associativity in the future ICache.add_instruction(instruction_index) current_result.set_fetch_stage(fetch_cycle) if hlt_flag: self.result.append(current_result) current_result.print_row() return None # Parsing Instruction to update the memory branch_label_unconditional = self.branch_satisfaction( instruction) # Issue Stage issue_cycle = fetch_cycle + 1 current_result.set_issue_stage(issue_cycle) last_issue = issue_cycle elif instruction_type == "CONTROL": # Fetch Stage fetch_cycle = last_issue # I-Cache Penalty if instruction_index not in ICache.instruction_index_cache_set \ and instruction_index % self.block_size == 0: fetch_cycle += self.penalty # Need to handle Direct Associativity in the future ICache.add_instruction(instruction_index) current_result.set_fetch_stage(fetch_cycle) if hlt_flag: self.result.append(current_result) current_result.print_row() return None # Issue Stage issue_cycle = fetch_cycle + 1 current_result.set_issue_stage(issue_cycle) last_issue = issue_cycle hlt_flag = True self.result.append(current_result) current_result.print_row() if branch_label_conditional is not None: conditional_branch_flag = True if branch_label_unconditional is not None: unconditional_branch_flag = True instruction_index = next_index
def printEvent(event): print event.x, event.y from Label import Label root = Tkinter.Tk() root.grid_rowconfigure(0, weight=1) root.grid_columnconfigure(0, weight=1) nrows = 5 ncols = 4 for j in range(nrows): for i in range(ncols): label = Label(root, text='label number '+str(j)+str(i)) label.grid(row=2*j, column=2*i) for j in range(1,nrows): sep = Separator(root, orient=Tkinter.HORIZONTAL, color='red') sep.canvas.bind('<ButtonPress-1>', printEvent) sep.grid(row=2*j-1, column=0, columnspan=2*ncols-1, sticky=Tkinter.EW) for i in range(1,ncols): sep = Separator(root, orient=Tkinter.VERTICAL, color='green') sep.canvas.bind('<ButtonPress-1>', printEvent) sep.grid(row=0, column=2*i-1, rowspan=2*nrows-1, sticky=Tkinter.NS) root.mainloop()
def draw(self, surface): Label.draw(self, surface) self.draw_check(surface)
def main(): address_old = 'localhost' port_old = 27017 address_new = '192.168.6.254' port_new = 37017 print("convert label type data") LabelType.insert_label_type(address_new, port_new) print("convert area data") Area.insert_area(address_old, port_old, address_new, port_new) print("convert label data") Label.convert_label(address_old, port_old, address_new, port_new) # 城市表 依赖新导入的Label表,需保证City前导入Label print("convert city data") City.convert_city(address_old, port_old, address_new, port_new) print("convert weather data") Weather.convert_weather(address_old, port_old, address_new, port_new, Weather.collection_old, Weather.collection_new, Weather.params_map) # 特别注意 weather_history 表依赖于当前的 weather 表 print("create weather_history data") WeatherHistory.create_weather_history(address_new, port_new, address_new, port_new, WeatherHistory.collection_old, WeatherHistory.collection_new, WeatherHistory.params_map) print("convert pgc data") Pgc.convert_pgc(address_old, port_old, address_new, port_new) print("convert label data") Label.convert_label(address_old, port_old, address_new, port_new) print("convert attraction data") Attraction.convert_attraction(address_old, port_old, address_new, port_new, Attraction.collection_old, Attraction.collection_new, Attraction.params_map) print("convert restaurant data") Restaurant.convert_restaurant(address_old, port_old, address_new, port_new, Restaurant.collection_old, Restaurant.collection_new, Restaurant.params_map) print("convert shopping data") Shopping.convert_shopping(address_old, port_old, address_new, port_new, Shopping.collection_old, Shopping.collection_new, Shopping.params_map) print("convert activity data") Activity.convert_activity(address_old, port_old, address_new, port_new, Activity.collection_old, Activity.collection_new, Activity.params_map) print("convert recommendBynamic data") # RecommendDynamic.convert_recommendDynamic(address_old, port_old, address_new, port_new,RecommendDynamic.collection_old, # RecommendDynamic.collection_new, RecommendDynamic.params_map) print("convert plan data") Plan.convert_plan(address_old, port_old, address_new, port_new, Plan.collection_old, Plan.collection_new, Plan.params_map) print("convert brand data") Brand.convert_brand(address_old, port_old, address_new, port_new, Brand.collection_old, Brand.collection_new, Brand.params_map) print("OK")
class Button (Bin): """Button (text=None) -> Button () A widget class, which can react upon mouse events. The Button widget can listen to mouse events such as clicks or a pressed button. It can display a short text and supports the activation using a keyboard. The text to display on the Button can be set using the 'text' attribute or the set_text() method. The text is displayed using a Label widget, which is placed upon the button surface, thus all text capabilities of the Label, such as mnemonics, can be applied to the Button as well. button.text = '#Click me' # Use the C character as mnemonic. button.text = 'Button' # A simple text. button.set_text ('Button ##1') # Creates the text 'Button #1' To operate on the displayed Label directly (which is NOT recommended), the 'child' attribute and set_child() method can be used. They have a slightly different behaviour than the methods of the Bin class and allow only Label widgets to be assigned to the Button. Additionally the Label its 'widget' attribute will be bound to the Button. Button.child = Label ('#Button') Button.set_child (None) Note: Changing the 'state' attribute of the Button will also affect the state of the Label placed on the Button. Default action (invoked by activate()): The Button emulates a SIG_CLICKED event and runs the connected callbacks. Mnemonic action (invoked by activate_mnemonic()): The Button invokes the activate_mnemonic() method of its Label (if any). Signals: SIG_MOUSEDOWN - Invoked, when a mouse button is pressed on the Button. SIG_MOUSEUP - Invoked, when a mouse button is released on the Button. SIG_MOUSEMOVE - Invoked, when the mouse moves over the Button. SIG_CLICKED - Invoked, when the left mouse button is pressed AND released over the Button. Attributes: text - The text to display on the Button. """ def __init__ (self, text=None): Bin.__init__ (self) self.set_text (text) # Internal click detector. self.__click = False # Signals, the button listens to. self._signals[SIG_MOUSEDOWN] = [] self._signals[SIG_MOUSEUP] = [] self._signals[SIG_MOUSEMOVE] = [] self._signals[SIG_KEYDOWN] = None # Dummy for keyboard activation. self._signals[SIG_CLICKED] = [] def set_text (self, text=None): """B.set_text (...) -> None Sets the text to display on the Button. Sets the text to display on the Button by referring to the 'text' attribute of it child Label. """ if text: if self.child: self.child.set_text (text) else: self.child = Label (text) else: self.child = None self.dirty = True def get_text (self): """B.get_text () -> string Returns the set text of the Button. Returns the text set on the Label of the Button """ if self.child: return self.child.text return "" def set_child (self, child=None): """B.set_child (...) -> None Sets the Label to display on the Button. Creates a parent-child relationship from the Button to a Label and causes the Label to set its mnemonic widget to the Button. Raises a TypeError, if the passed argument does not inherit from the Label class. """ if child and not isinstance (child, Label): raise TypeError ("child must inherit from Label") Bin.set_child (self, child) if child: child.set_widget (self) if not child.style: child.style = self.style or \ base.GlobalStyle.get_style (self.__class__) self.dirty = True def set_state (self, state): """B.set_state (...) -> None Sets the state of the Button. Sets the state of the Button and causes its child to set its state to the same value. """ Bin.set_state (self, state) if self.child: self.child.state = self.state def activate_mnemonic (self, mnemonic): """B.activate_mnemonic (...) -> bool Activates the mnemonic of the Button its Label. """ if self.child: return self.child.activate_mnemonic (mnemonic) return False def activate (self): """B.activate () -> None Activates the Button default action. Activates the Button default action. This usually means a click, emulated by setting the state to STATE_ACTIVE, forcing an update, setting the state back to STATE_NORMAL and running the attached callbacks for the SIG_CLICKED event. """ if base.debug: print "Button.activate ()" if not self.sensitive: return self.focus = True self.state = STATE_ACTIVE try: self.manager.force_update (100) except: pass self.state = STATE_NORMAL self.run_signal_handlers (SIG_CLICKED) def draw (self): """B.draw () -> Surface Draws the Button surface and returns it. Creates the visible surface of the Button and returns it to the caller. """ if self.child: self.child.update () return base.GlobalStyle.draw_button (self) # font = pygame.font.Font(None, 24) # return font.render(self.child.text, 1, (255,255,255,255)) def notify (self, event): """B.notify (...) -> None Notifies the Button about an event. """ if not self.eventarea or not self.sensitive: # The button does not seem to be completely realized for now or # is not sensitive. return elif event.signal == SIG_MOUSEDOWN: if self.eventarea.collidepoint (event.data.pos): if base.debug: print "Button.MOUSEDOWN" self.focus = True # The button only acts upon left clicks. if event.data.button == 1: self.state = STATE_ACTIVE self.__click = True self.run_signal_handlers (SIG_MOUSEDOWN) elif event.signal == SIG_MOUSEUP: if self.eventarea.collidepoint (event.data.pos): if base.debug: print "Button.MOUSEUP" self.run_signal_handlers (SIG_MOUSEUP) if event.data.button == 1: if self.state == STATE_ACTIVE: self.state = STATE_ENTERED else: self.state = STATE_NORMAL # Check for a previous left click. if self.__click: self.__click = False if base.debug: print "Button.CLICKED" self.run_signal_handlers (SIG_CLICKED) elif (event.data.button == 1) and (self.state == STATE_ACTIVE): # Reset the 'clicked' state for the button, if the mouse # button 1 is released at another location. self.__click = False self.state = STATE_NORMAL elif event.signal == SIG_MOUSEMOVE: if self.eventarea.collidepoint (event.data.pos): if base.debug: print "Button.MOUSEMOVE (inner)" if self.state == STATE_NORMAL: self.state = STATE_ENTERED self.run_signal_handlers (SIG_MOUSEMOVE) elif self.state == STATE_ENTERED: if base.debug: print "Button.MOUSEMOVE (outer)" self.state = STATE_NORMAL elif (event.signal == SIG_KEYDOWN) and self.focus: if event.data.key in (pygame.locals.K_SPACE, pygame.locals.K_KP_ENTER, pygame.locals.K_RETURN): # Activate the focused button, if the user presses # space, return or enter. self.activate () Bin.notify (self, event) text = property (lambda self: self.get_text (), lambda self, var: self.set_text (var), doc = "The text of the Button.")
def menu_screen(self, clock): pygame.display.set_caption("Super Zombie Flag Capturing Game") # ENTITIES # Background i = 0 # Sprites # Sprites label_color = (255, 255, 255) new_game = Label(44, (800, 130)) new_game.set_color(label_color) new_game.set_msg("Start New Game") instruction_label = Label(44, (800, 200)) instruction_label.set_color(label_color) instruction_label.set_msg("Instructions") quit_label = Label(44, (800, 270)) quit_label.set_color(label_color) quit_label.set_msg("Quit") note = Label(20, (925, 675)) note.set_color(label_color) note.set_msg("Micheal Lin , Bill Le , Ian Chen") pointer = Pointer(44, [(750, 130), (750, 200), (750, 270)], [1, 0, 3]) pointer.set_color(label_color) pointer.set_msg("*") sprite = pygame.sprite.OrderedUpdates(pointer) keep_going = True # LOOP while keep_going: i = (i + 1) % 4 # TIME clock.tick(FRAME_RATE) background = pygame.image.load(MAIN_MENU[i]) background = pygame.transform.scale(background, (1200, 700)) self.screen.blit(background, (0, 0)) self.screen.blit(new_game.image, new_game) self.screen.blit(instruction_label.image, instruction_label) self.screen.blit(quit_label.image, quit_label) self.screen.blit(note.image, note) # EVENT HANDLING for event in pygame.event.get(): if event.type == pygame.QUIT: return 3 if event.type == pygame.KEYDOWN: if event.key == pygame.K_DOWN: pointer.move_next() elif event.key == pygame.K_UP: pointer.move_previous() if event.key == pygame.K_RETURN: return pointer.get_value() if pygame.key.get_pressed()[pygame.K_c]: return 1 sprite.clear(self.screen, background) sprite.update() sprite.draw(self.screen) pygame.display.flip()
print("Check collisions:") #Collisions for a in all_entities: if a in entities_to_remove: continue b = quad_tree.check_collisions(a) if b != None: if type(a) == Player: if b.isEnemy: if not player.invulnerable: if player.lives == 1: end_game() player.get_hit() new_label = Label("-1 life", b.y, b.x) temporary_entities.add(new_label) entities_to_remove.add(b) elif type(b) == Shot and b.harm_player: if not player.invulnerable: if player.lives == 1: end_game() player.get_hit() new_label = Label("-1 life", b.y, b.x) temporary_entities.add(new_label) entities_to_remove.add(b) else: if type(a) == Shot and b.isEnemy or type( b) == Shot and a.isEnemy: if type(a) == Enemy or type(a) == EnemyT2: a, b = b, a
def instruction_screen(self, clock): pygame.display.set_caption("Instructions!!") # ENTITIES # Background background = pygame.Surface(self.screen.get_size()) background.fill((0, 0, 0)) self.screen.blit(background, (0, 0)) label_color = (255, 255, 255) line_1 = Label(30, (200, 70)) line_1.set_color(label_color) line_1.set_msg( "Your goal each round is to deliver the flag to the enemy base while" ) line_2 = Label(30, (100, 110)) line_2.set_color(label_color) line_2.set_msg( " fighting off your opponent and zombies* The game will be in a Best of 3 format* " ) line_3 = Label(30, (100, 150)) line_3.set_color(label_color) line_3.set_msg( "where player needs to win at least two rounds to win overall* Player 1 will" ) line_4 = Label(30, (100, 190)) line_4.set_color(label_color) line_4.set_msg( " move using the directional key and attack with the right control key* Player 2 " ) line_5 = Label(30, (100, 230)) line_5.set_color(label_color) line_5.set_msg( "will move using the AWSD buttons and attack with the Spacebar*") line_6 = Label(30, (200, 270)) line_6.set_color(label_color) line_6.set_msg("Please press Enter to continue*") labels = [line_1, line_2, line_3, line_4, line_5, line_6] keep_going = True i = 0 # LOOP while keep_going: i = (i + 1) % 4 # TIME clock.tick(FRAME_RATE) background = pygame.image.load(MAIN_MENU[i]) background = pygame.transform.scale(background, (1200, 700)) self.screen.blit(background, (0, 0)) for l in labels: l.set_color(label_color) self.screen.blit(l.image, l) # TIME clock.tick(FRAME_RATE) # EVENT HANDLING for event in pygame.event.get(): if event.type == pygame.QUIT: return 3 if event.type == pygame.KEYDOWN: if event.key == pygame.K_RETURN: return 2 pygame.display.flip()
def start_battle(self, clock): pygame.display.set_caption("Fight!!") # ENTITIES # Background background = pygame.Surface(self.screen.get_size()) background.fill((0, 0, 0)) self.screen.blit(background, (0, 0)) # Sprites top_widget_size = (self.screen.get_size()[0], round(self.screen.get_size()[1] / 10)) top_widget = Boundary((self.screen.get_size()[0] / 2, round(self.screen.get_size()[1] / 20)), color=(255, 255, 0), size=top_widget_size) # Grids grid_sprites, safe_grid, grid_position = self.make_grid( (0, round(self.screen.get_size()[1] / 10))) curr_map = Map(grid_position) obsticles = curr_map.make_map(OBSTACLE_GRID_TILE) potential_box = curr_map.get_box_position() obsticles = pygame.sprite.Group(obsticles) # Boundary top_boundary = Boundary((600, 69), (255, 255, 255), (1200, 20)) left_boundary = Boundary((-4, 350), (255, 255, 255), (20, 700)) right_boundary = Boundary((1204, 350), (255, 255, 255), (20, 700)) bottom_boundary = Boundary((600, 701), (255, 255, 255), (1200, 20)) top_boundary.make_invisible() left_boundary.make_invisible() right_boundary.make_invisible() bottom_boundary.make_invisible() obsticles.add(top_boundary, left_boundary, right_boundary, bottom_boundary) # Player player_1 = Player(grid_position[7][32]) player_2 = Player(grid_position[7][0]) player_1_attacks = pygame.sprite.Group() player_2_attacks = pygame.sprite.Group() # Player score zone p1_score_zone = Boundary((0, 0), (0, 0, 0), (72, 144)) p1_score_zone.rect.topleft = (grid_position[6][0][0] - 18, grid_position[6][0][1] - 18) p1_score_zone.make_invisible() p2_score_zone = Boundary((0, 0), (0, 0, 0), (72, 144)) p2_score_zone.rect.topleft = (grid_position[6][31][0] - 18, grid_position[6][31][1] - 18) p2_score_zone.make_invisible() score_zone = [p1_score_zone, p2_score_zone] # Zombies zombie_group = pygame.sprite.Group() zombie_group.add(Zombie(player_1, player_2, (500, -5), safe_grid)) zombie_group.add(Zombie(player_1, player_2, (700, -5), safe_grid)) zombie_group.add(Zombie(player_1, player_2, (600, 350), safe_grid)) zombie_group.add(Zombie(player_1, player_2, (500, 705), safe_grid)) zombie_group.add(Zombie(player_1, player_2, (700, 705), safe_grid)) # HP Bar player_2_bar = StatBar((200, 35), (0, 255, 0), (300, 25), MAX_HP) player_1_bar = StatBar((1000, 35), (0, 255, 0), (300, 25), MAX_HP) player_1_bar.set_reversed_direction() bars = [ player_2_bar.get_full_bar((255, 0, 0)), player_1_bar.get_full_bar((255, 0, 0)) ] # Box # Item Box box_sprites = pygame.sprite.Group() # Goals flag = Flag((600, 350)) goal = CaptureFlag([player_1, player_2], score_zone, flag, num_round=3) # Label color p1_label_color = (0, 0, 255) p2_label_color = (255, 0, 0) # Flag flag_p2 = Label(44, (400, 35)) flag_p2.set_color(p2_label_color) flag_p1 = Label(44, (780, 35)) flag_p1.set_color(p1_label_color) # timer timer = Timer(30, (560, 35), 4, 20, FRAME_RATE) # Labels p2_label = Label(20, (20, 35)) p2_label.set_color(p2_label_color) p2_label.set_msg("P2 ") p1_label = Label(20, (1160, 35)) p1_label.set_color(p1_label_color) p1_label.set_msg("P1") p1_head = Label(15, (player_1.rect.centerx - 8, player_1.rect.top - 5)) p1_head.set_color(p1_label_color) p1_head.set_msg("P1") p2_head = Label(15, (player_2.rect.centerx - 8, player_2.rect.top - 5)) p2_head.set_color(p2_label_color) p2_head.set_msg("P2") p1_weapon = Label(20, (990, 56)) p1_weapon.set_msg("sada") p2_weapon = Label(20, (170, 56)) p2_weapon.set_msg("sada") labels = [ p1_label, p2_label, p1_head, p2_head, p1_weapon, p2_weapon, flag_p1, flag_p2 ] keep_going = True box_flag = True all_sprites = pygame.sprite.OrderedUpdates(grid_sprites, obsticles, flag, player_1, player_2, zombie_group, top_widget, timer, labels, bars, player_1_bar, player_2_bar) # LOOP while keep_going: if goal.screen_pause: pygame.time.wait(1500) goal.screen_pause = False # TIME clock.tick(FRAME_RATE) if timer.get_real_second() % 5 == 0: # Box if box_flag: box_flag = False box = self.generate_box(potential_box) box_sprites.add(box) all_sprites.add(box) else: box_flag = True if timer.get_real_second() % 20 == 0 and len(zombie_group) <= 1: zombie_group.add( Zombie(player_1, player_2, (500, -5), safe_grid)) zombie_group.add( Zombie(player_1, player_2, (700, -5), safe_grid)) zombie_group.add( Zombie(player_1, player_2, (600, 350), safe_grid)) zombie_group.add( Zombie(player_1, player_2, (500, 705), safe_grid)) zombie_group.add( Zombie(player_1, player_2, (700, 705), safe_grid)) all_sprites.add(zombie_group) for z in zombie_group: z.move(zombie_group) # Check for Goal if goal.check_for_win(): keep_going = False if timer.time_up(): keep_going = False flag_p1.set_msg(str(goal.score[0])) flag_p2.set_msg(str(goal.score[1])) # EVENT HANDLING for event in pygame.event.get(): if event.type == pygame.QUIT: return 3 if event.type == pygame.KEYDOWN: if event.key == pygame.K_p: keep_going = False #Player 1 event handle if pygame.key.get_pressed()[pygame.K_RIGHT]: temp_block = TempBlock(player_1.rect.center, player_1.rect.size) temp_block.rect.x += player_1.velocity if pygame.sprite.spritecollide(temp_block, obsticles, False): # Check the previous directoin if player_1.direction == 1 or player_1.prev_direction == 1: i = 1 # Check if the we continue with previous direction for more frames will be able to pass through while i < player_1.velocity * SMOOTH_TURNING_FRAME_DELAY: i += 1 temp_block.rect.y += 1 if not pygame.sprite.spritecollide( temp_block, obsticles, False): player_1.go_down() break elif player_1.direction == 3 or player_1.prev_direction == 3: i = 1 while i < player_1.velocity * SMOOTH_TURNING_FRAME_DELAY: i += 1 temp_block.rect.y -= 1 if not pygame.sprite.spritecollide( temp_block, obsticles, False): player_1.go_up() break else: pass else: player_1.go_right() elif pygame.key.get_pressed()[pygame.K_DOWN]: temp_block = TempBlock(player_1.rect.center, player_1.rect.size) temp_block.rect.y += player_1.velocity if pygame.sprite.spritecollide(temp_block, obsticles, False): if player_1.direction == 0 or player_1.prev_direction == 0: i = 1 while i < player_1.velocity * SMOOTH_TURNING_FRAME_DELAY: i += 1 temp_block.rect.x += 1 if not pygame.sprite.spritecollide( temp_block, obsticles, False): player_1.go_right() break elif player_1.direction == 2 or player_1.prev_direction == 2: i = 1 while i < player_1.velocity * SMOOTH_TURNING_FRAME_DELAY: i += 1 temp_block.rect.x -= 1 if not pygame.sprite.spritecollide( temp_block, obsticles, False): player_1.go_left() break else: pass else: player_1.go_down() elif pygame.key.get_pressed()[pygame.K_UP]: temp_block = TempBlock(player_1.rect.center, player_1.rect.size) temp_block.rect.y -= player_1.velocity if pygame.sprite.spritecollide(temp_block, obsticles, False): if player_1.direction == 0 or player_1.prev_direction == 0: i = 1 while i < player_1.velocity * SMOOTH_TURNING_FRAME_DELAY: i += 1 temp_block.rect.x += 1 if not pygame.sprite.spritecollide( temp_block, obsticles, False): player_1.go_right() break elif player_1.direction == 2 or player_1.prev_direction == 2: i = 1 while i < player_1.velocity * SMOOTH_TURNING_FRAME_DELAY: i += 1 temp_block.rect.x -= 1 if not pygame.sprite.spritecollide( temp_block, obsticles, False): player_1.go_left() break else: pass else: player_1.go_up() elif pygame.key.get_pressed()[pygame.K_LEFT]: temp_block = TempBlock(player_1.rect.center, player_1.rect.size) temp_block.rect.x -= player_1.velocity if pygame.sprite.spritecollide(temp_block, obsticles, False): if player_1.direction == 1 or player_1.prev_direction == 1: i = 1 while i < player_1.velocity * SMOOTH_TURNING_FRAME_DELAY: i += 1 temp_block.rect.y += 1 if not pygame.sprite.spritecollide( temp_block, obsticles, False): player_1.go_down() break elif player_1.direction == 3 or player_1.prev_direction == 3: i = 1 while i < player_1.velocity * SMOOTH_TURNING_FRAME_DELAY: i += 1 temp_block.rect.y -= 1 if not pygame.sprite.spritecollide( temp_block, obsticles, False): player_1.go_up() break else: pass else: player_1.go_left() if pygame.key.get_pressed()[pygame.K_RCTRL]: lst = player_1.attack() player_1_attacks.add(lst) all_sprites.add(lst) # Player 2 event handle if pygame.key.get_pressed()[pygame.K_d]: temp_block = TempBlock(player_2.rect.center, player_2.rect.size) temp_block.rect.x += player_2.velocity if pygame.sprite.spritecollide(temp_block, obsticles, False): # Check the previous directoin if player_2.direction == 1 or player_2.prev_direction == 1: i = 1 # Check if the we continue with previous direction for more frames will be able to pass through while i < player_2.velocity * SMOOTH_TURNING_FRAME_DELAY: i += 1 temp_block.rect.y += 1 if not pygame.sprite.spritecollide( temp_block, obsticles, False): player_2.go_down() break elif player_2.direction == 3 or player_2.prev_direction == 3: i = 1 while i < player_2.velocity * SMOOTH_TURNING_FRAME_DELAY: i += 1 temp_block.rect.y -= 1 if not pygame.sprite.spritecollide( temp_block, obsticles, False): player_2.go_up() break else: pass else: player_2.go_right() elif pygame.key.get_pressed()[pygame.K_s]: temp_block = TempBlock(player_2.rect.center, player_2.rect.size) temp_block.rect.y += player_2.velocity if pygame.sprite.spritecollide(temp_block, obsticles, False): if player_2.direction == 0 or player_2.prev_direction == 0: i = 1 while i < player_2.velocity * SMOOTH_TURNING_FRAME_DELAY: i += 1 temp_block.rect.x += 1 if not pygame.sprite.spritecollide( temp_block, obsticles, False): player_2.go_right() break elif player_2.direction == 2 or player_2.prev_direction == 2: i = 1 while i < player_2.velocity * SMOOTH_TURNING_FRAME_DELAY: i += 1 temp_block.rect.x -= 1 if not pygame.sprite.spritecollide( temp_block, obsticles, False): player_2.go_left() break else: pass else: player_2.go_down() elif pygame.key.get_pressed()[pygame.K_w]: temp_block = TempBlock(player_2.rect.center, player_2.rect.size) temp_block.rect.y -= player_2.velocity if pygame.sprite.spritecollide(temp_block, obsticles, False): if player_2.direction == 0 or player_2.prev_direction == 0: i = 1 while i < player_2.velocity * SMOOTH_TURNING_FRAME_DELAY: i += 1 temp_block.rect.x += 1 if not pygame.sprite.spritecollide( temp_block, obsticles, False): player_2.go_right() break elif player_2.direction == 2 or player_2.prev_direction == 2: i = 1 while i < player_2.velocity * SMOOTH_TURNING_FRAME_DELAY: i += 1 temp_block.rect.x -= 1 if not pygame.sprite.spritecollide( temp_block, obsticles, False): player_2.go_left() break else: pass else: player_2.go_up() elif pygame.key.get_pressed()[pygame.K_a]: temp_block = TempBlock(player_2.rect.center, player_2.rect.size) temp_block.rect.x -= player_2.velocity if pygame.sprite.spritecollide(temp_block, obsticles, False): if player_2.direction == 1 or player_2.prev_direction == 1: i = 1 while i < player_2.velocity * SMOOTH_TURNING_FRAME_DELAY: i += 1 temp_block.rect.y += 1 if not pygame.sprite.spritecollide( temp_block, obsticles, False): player_2.go_down() break elif player_2.direction == 3 or player_2.prev_direction == 3: i = 1 while i < player_2.velocity * SMOOTH_TURNING_FRAME_DELAY: i += 1 temp_block.rect.y -= 1 if not pygame.sprite.spritecollide( temp_block, obsticles, False): player_2.go_up() break else: pass else: player_2.go_left() if pygame.key.get_pressed()[pygame.K_SPACE]: lst2 = player_2.attack() player_2_attacks.add(lst2) all_sprites.add(lst2) # Collisions handleling for box1 in pygame.sprite.spritecollide(player_1, box_sprites, False): temp_label = TempLabel( 15, (player_1.rect.centerx - 8, player_1.rect.top - 5), 3, FRAME_RATE) temp_label.set_msg(box1.__str__()) all_sprites.add(temp_label) box1.collide(player_1) for box2 in pygame.sprite.spritecollide(player_2, box_sprites, False): box2.collide(player_2) temp_label = TempLabel( 15, (player_2.rect.centerx - 8, player_2.rect.top - 5), 3, FRAME_RATE) temp_label.set_msg(box2.__str__()) all_sprites.add(temp_label) # Zombie hit player for zombie in pygame.sprite.spritecollide(player_1, zombie_group, False): zombie.collide(player_1) for zombie in pygame.sprite.spritecollide(player_2, zombie_group, False): zombie.collide(player_2) # Players hit zombies for zombie in zombie_group: for bullet in pygame.sprite.spritecollide( zombie, player_2_attacks, False): bullet.collide(zombie) for bullet in pygame.sprite.spritecollide( zombie, player_1_attacks, False): bullet.collide(zombie) # bullet_hit_walls for wall in obsticles: for bullet in pygame.sprite.spritecollide( wall, player_1_attacks, False): bullet.end() for bullet in pygame.sprite.spritecollide( wall, player_2_attacks, False): bullet.end() # Player_1 attacks for hit in pygame.sprite.spritecollide(player_2, player_1_attacks, False): hit.collide(player_2) # Player_2 attacks for hit in pygame.sprite.spritecollide(player_1, player_2_attacks, False): hit.collide(player_1) # Player hp bar player_2_bar.set_curr_stat(player_2.health) player_1_bar.set_curr_stat(player_1.health) # Player head p1_head.set_position( (player_1.rect.centerx - 8, player_1.rect.top - 5)) p2_head.set_position( (player_2.rect.centerx - 8, player_2.rect.top - 5)) p1_weapon.set_msg(str(player_1.weapon)) p2_weapon.set_msg(str(player_2.weapon)) if player_1.is_dead(): if flag.get_player() == player_1: flag.drop() player_1.respawn() if player_2.is_dead(): if flag.get_player() == player_2: flag.drop() player_2.respawn() for zombie in zombie_group: if zombie.is_dead(): zombie.kill() all_sprites.clear(self.screen, background) all_sprites.update() all_sprites.draw(self.screen) pygame.display.flip() lst = player_1.weapon.update() player_1_attacks.add(lst) all_sprites.add(lst) lst = player_2.weapon.update() player_2_attacks.add(lst) all_sprites.add(lst) end_msg = Label(60, (500, 350)) end_msg.set_color((255, 255, 0)) end_msg.set_msg(goal.get_wining_msg()) self.screen.blit(end_msg.image, end_msg) pygame.display.flip() pygame.time.wait(2000) return 2
def __init__(self, parent=None): # Main Window super(Ui_MainWindow, self).__init__(parent=parent) self.setObjectName("MainWindow") self.resize(1233, 883) font = QtGui.QFont() font.setBold(False) font.setWeight(50) self.setFont(font) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap("icon/logo.jpg"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.setWindowIcon(icon) self.setLayoutDirection(QtCore.Qt.LeftToRight) self.setWindowTitle("CHALK") # Tool bar tool_bar = QtWidgets.QToolBar('Toolbar', self) tool_bar.setObjectName("ToolBar") scanning = QtWidgets.QAction(QtGui.QIcon('icon/play.png'), 'Scan', self) scanning.setShortcut('Space') scanning.triggered.connect(self.__scan) scanning.setObjectName("Scanning") tool_bar.addAction(scanning) importing = QtWidgets.QAction(QtGui.QIcon('icon/import.png'), 'Import', self) importing.triggered.connect(self.__import) importing.setShortcut('Ctrl+O') importing.setObjectName("Importing") tool_bar.addAction(importing) exporting = QtWidgets.QAction(QtGui.QIcon('icon/export.png'), 'Export', self) exporting.triggered.connect(self.__export) exporting.setShortcut('Ctrl+S') exporting.setObjectName("Exporting") tool_bar.addAction(exporting) self.addToolBar(tool_bar) # Central Widget self.centralwidget = QtWidgets.QStackedWidget(self) self.centralwidget.setObjectName("centralwidget") self.setCentralWidget(self.centralwidget) # Welcome Widget self.welcomewidget = QtWidgets.QWidget() horizontallayout = QtWidgets.QHBoxLayout(self.welcomewidget) label = Label(self.welcomewidget) piximap = QtGui.QPixmap('icon/welcome.png') label.setPixmap(piximap) horizontallayout.addWidget(label) self.centralwidget.addWidget(self.welcomewidget) # Result widget self.result_widget = QtWidgets.QWidget() horizontalLayout = QtWidgets.QHBoxLayout(self.result_widget) horizontalLayout.setContentsMargins(0, 0, 0, 0) self.tabWidget = QtWidgets.QTabWidget(self.result_widget) horizontalLayout.addWidget(self.tabWidget) line = QtWidgets.QFrame(self.result_widget) line.setFrameShape(QtWidgets.QFrame.VLine) line.setFrameShadow(QtWidgets.QFrame.Sunken) horizontalLayout.addWidget(line) listView = QtWidgets.QListView(self.result_widget) horizontalLayout.addWidget(listView, 0, QtCore.Qt.AlignRight) self.centralwidget.addWidget(self.result_widget)
def get_new_label(self): new_label = Label(self.get_label_count(), self) self.labelList.append(new_label) return new_label
if event: if event.type == QUIT: pygame.quit() sys.exit() elif event.type == VIDEORESIZE: self.rect.size = event.dict["size"] self.screen = pygame.display.set_mode(self.screen_size, RESIZABLE) self.resize() else: self.layout.update(self, event=event) def draw(self): self.layout.draw(self) """ parent.grid(widget, ...) or widget.grid(...)? """ root = GUI(layout="grid") a = GridFrame.GridFrame(root) a.grid(row=0, column=0, sticky="nswe") root.config_column(0, weight=1) root.config_row(0, weight=1) b = Label(a, text="Hi! This is a label!", padding=[10, 10, 10, 10], fontsize=50, color=(150, 150, 0)) b.grid(row=0, column=0) a.config_column(0, weight=1) a.config_row(0, weight=1) while True: for event in pygame.event.get(): root.update(event=event) root.update() root.draw() pygame.display.update()