def __init__(self, Parent, Message, **properties): SIOInstance = Parent.Screen() sMCOL = SIOInstance.MAXCOL sMROW = SIOInstance.MAXROW MsgLen = len(Message) DialogWidth = MsgLen + 4 DialogHeight = 6 if DialogWidth < 12: DialogWidth = 18 r1 = (sMROW - DialogHeight) / 2 r2 = r1 + DialogHeight c1 = (sMCOL - DialogWidth) / 2 c2 = c1 + DialogWidth apply(Dialog.__init__, (self, Parent, r1, c1, r2, c2), properties) tCmdYes = Button(self, "YesBtn", 5, (DialogWidth - 7) / 4, 7, "Yes") tCmdYes.EXITFORM = 1 self.AddDialogControl(tCmdYes) tCmdNo = Button(self, "NoBtn", 5, 2 + (2 * ((DialogWidth - 7)) / 4), 7, "No") tCmdNo.EXITFORM = 1 self.AddDialogControl(tCmdNo) self.AddDialogControl(Label(self, "TheMsg", 1, 2, Message))
def __init__(self, Parent, Prompt, DefaultText="", **properties): SIOInstance = Parent.Screen() sMCOL = SIOInstance.MAXCOL sMROW = SIOInstance.MAXROW if len(Prompt) < 40: DialogWidth = 40 else: DialogWidth = len(Prompt) + 4 DialogHeight = 6 r1 = (sMROW - DialogHeight) / 2 r2 = r1 + DialogHeight c1 = (sMCOL - DialogWidth) / 2 c2 = c1 + DialogWidth apply(Dialog.__init__, (self, Parent, r1, c1, r2, c2), properties) tCmdOK = Button(self, "OKBtn", 5, (DialogWidth - 10) / 4, 10, "OK") tCmdOK.EXITFORM = 1 self.AddDialogControl(tCmdOK) tCmdCancel = Button(self, "CnclBtn", 5, 2 + (2 * ((DialogWidth - 10)) / 4), 10, "Cancel") tCmdCancel.EXITFORM = 1 self.AddDialogControl(tCmdCancel) self.AddDialogControl(Label(self, "lbl", 1, 2, Prompt)) self.tTextBox = TextBox(self, "txtBox", 2, 2, DialogWidth - 4, DefaultText) self.tTextBox.DEPTH = len(DefaultText) self.AddDialogControl(self.tTextBox) self.STARTPOINT = 3
def __init__(self, game): self.game = game self.font = game.font self.one_player_button = Button([300, 350], [200, 30], "1P VS AI", self.font) self.one_player_button2 = Button([300, 400], [200, 30], "AI VS 1P", self.font) self.two_player_button = Button([300, 450], [200, 30], "1P VS 2P", self.font)
def __init__(self, parent=None, rect=sf.Rectangle(), backgroundColor=sf.Color.BLACK,\ title=str(), backgroundImage=Image(), drawTitleButton = True,\ buttonTitleImage=None, \ characterSizeTitle=12): sf.RenderTexture.__init__(self, rect.size.x, rect.size.y) Render.__init__(self, parent, rect, backgroundColor, title, backgroundImage) self._buttonMoveFrame = None if type(title) == str: self._title = title self._buttonMoveFrame = Button(self, Label(None, self.title, font = sf.Font.from_file("DejaVuSans.ttf")), \ buttonTitleImage, sf.Rectangle(sf.Vector2(0,0),\ sf.Vector2(self.size.x, characterSizeTitle))) else: self._title = title.text.string self._buttonMoveFrame = Button(self, title, buttonTitleImage, \ sf.Rectangle(sf.Vector2(), sf.Vector2(self.size.x, \ title.size.y))) self._buttonMoveFrame.isStaticToView = True self.resetView() self._frameSprite = sf.Sprite(self.texture) if not drawTitleButton: self._buttonMoveFrame.isDrawing = False self._isMoving = False self._mousePosMoving = sf.Vector2(0, 0) self.rect = self.rect
def start(self): global actual_state clock = pygame.time.Clock() running_menu = True while running_menu: #fica checando se o estado == game pra mudar #se nao continua no menu (e so muda quando clicar clock.tick(120) buttonStart = Button([width/2,height/2]) for event in pygame.event.get(): if event.type==QUIT: running_menu = False elif event.type == MOUSEBUTTONDOWN: if buttonStart.pressed(pygame.mouse.get_pos()): actual_state = gamestate["game"] running_menu = False screen.fill(white) screen.blit(buttonStart.btn, buttonStart.btnrect) pygame.display.flip()
def __init__(self, Parent, Message, **properties): SIOInstance = Parent.Screen() sMCOL = SIOInstance.MAXCOL sMROW = SIOInstance.MAXROW MsgLen = len(Message) DialogWidth = MsgLen + 4 DialogHeight = 6 # adjust dialog, if need be, to hold OK btn comfortably if DialogWidth < 6: DialogWidth = 10 r1 = (sMROW - DialogHeight) / 2 r2 = r1 + DialogHeight c1 = (sMCOL - DialogWidth) / 2 c2 = c1 + DialogWidth apply(Dialog.__init__, (self, Parent, r1, c1, r2, c2), properties) tCmd = Button(self, "TheBtn", 5, (DialogWidth - 6) / 2, 6, "OK") tCmd.EXITFORM = 1 self.AddDialogControl(tCmd) self.AddDialogControl(Label(self, "TheMsg", 1, 2, Message))
def __init__(self, x, y, text, parent, c=(255,0,0)): Button.__init__(self, x, y, text, parent, c) self.font = pygame.font.SysFont('Calibri', 12) self.width -= 10 self.height = 20 self.surface = pygame.Surface((self.width, self.height)) self.render()
class WindowBar: def __init__(self, parent, absx, absy, title=None): self.x = 0 self.y = 0 self.absx = absx self.absy = absy self.parent = parent self.width = self.parent.get_width() self.height = 20 self.surface = pygame.Surface((self.width, self.height)) self.surface.fill((100,100,100)) self.title = title if self.title != None: self.button = Button(0, 0, self.title, self.surface, (100,100,100)) def is_clicked(self): # doesn't actually check if clicked, just mouse over mx, my = pygame.mouse.get_pos() if mx > self.absx and mx < self.absx + self.width and my > self.absy and my < self.absy + self.height: return True def draw(self): if self.title != None: self.button.draw(self.surface) self.parent.blit(self.surface, (self.x, self.y))
def draw(self): if self.left + self.max_width <= self.parent.width - self.parent.bd_width - \ 2 * self.parent.h_margin: self.visible = True else: self.visible = False Button.draw(self)
def searchSavedOthers(handler): handler.title('Saved Searches') requirePriv(handler, 'User') print tabs.where('others') undelay(handler) print "<style type=\"text/css\">" print ".other-search {padding-bottom: 4px; border-bottom: 1px dashed #000;}" print ".other-search h2 {margin-bottom: 4px;}" print ".other-search small {float: right; font-weight: normal; font-size: 12pt;}" print ".other-search code {font-size: 14pt;}" print "</style>" searches = filter(lambda search: search.user != handler.session['user'] and search.public, SavedSearch.loadAll(orderby = 'name')) if searches == []: print "No shared searches available" else: for search in searches: print "<div class=\"other-search\">" print "<h2>%s<small><img class=\"bumpdown\" src=\"%s\"> %s</small></h2>" % (search.safe.name, search.user.getAvatar(16), search.user.username) print "<code>%s</code><br><br>" % search.safe.query following = handler.session['user'] in search.followers print "<form method=\"post\" action=\"/search/saved/%d/%s\">" % (search.id, 'unfollow' if following else 'follow') print Button('Run', url = "/search/saved/%d/run" % search.id) btn = Button('Unfollow' if following else 'Follow', type = 'submit') if following: btn.negative() else: btn.positive() print btn print "</form>" print "</div>"
def __init__ (self, text): Button.__init__ (self, text) # Internal click handler self.__click = False self._active = False # The ToggleButton emits a 'toggled' event. self._signals[SIG_TOGGLED] = []
def __init__(self, parent, **kwargs): Button.__init__(self, parent) # data self.direction = ALIGN_N # del del self.text del self.icons # flags self.processKWArguments(kwargs) parent.registerWidget(self)
def __init__ (self, caption, _props={}): # Properties props = _props.copy() if 'class' in props: props['class'] += ' druid-button' else: props['class'] = 'druid-button' # Parent's constructor Button.__init__ (self, caption, props)
class Welcome(): def __init__(self, game): self.game = game self.font = game.font self.one_player_button = Button([300, 350], [200, 30], "1P VS AI", self.font) self.one_player_button2 = Button([300, 400], [200, 30], "AI VS 1P", self.font) self.two_player_button = Button([300, 450], [200, 30], "1P VS 2P", self.font) def draw(self): game = self.game screen = game.screen self.one_player_button.draw(screen) self.one_player_button2.draw(screen) self.two_player_button.draw(screen) def handle_key_event(self, e): game = self.game pos = e.pos if self.one_player_button.check(pos): game.window = 1 game.with_AI = True game.AI_first = True elif self.one_player_button2.check(pos): game.window = 1 game.with_AI = True game.AI_first = False elif self.two_player_button.check(pos): game.window = 1 game.with_AI = False
def __init__(self, pX, pY, pText, pColor=BLACK, pFontSize=36, pMethod=None, pName=None, pParams=None): ''' Constructor ''' if pName == None: name = pText else: name = pName Button.__init__(self, pX, pY, pName=name, pMethod=pMethod, pParams=pParams) font = pygame.font.Font(None, pFontSize) self.text = font.render(pText, 1, (pColor))
def set_text(self, text, fix_case=True): if fix_case: if self.upper_case: text = text.upper() else: text = text.lower() Button.set_text(self, text) self.label.set_v_align(Align.CENTER) self.label.set_h_align(Align.CENTER) if self.label.font: self.label.width = self.max_width self.width = self.label.get_rendered_size()[0] or self.max_width self.width += 4
class ButtonThread(GPIOThread): def __init__(self, pin): from Button import Button self.component = Button(pig, pin, callback=self.on_button_press) super(ButtonThread, self).__init__() def on_button_press(self, gpio, level, tick): print "PRESSED %s" % gpio super(ButtonThread, self).send("mapping/%d" % gpio) def terminate(self): super(ButtonThread, self).terminate() self.component.unlisten()
def notify (self, event): """T.notify (event) -> None Notifies the ToggleButton about an event. """ if not self.eventarea or not self.sensitive: return # Not completely realized or sensitive. elif event.signal == SIG_MOUSEDOWN: if self.eventarea.collidepoint (event.data.pos): if base.debug: print "ToggleButton.MOUSEDOWN" self.focus = True # The button only acts upon left clicks. if event.data.button == 1: self.__click = True self.state = STATE_ACTIVE self.run_signal_handlers (SIG_MOUSEDOWN) elif event.signal == SIG_MOUSEUP: if self.eventarea.collidepoint (event.data.pos): if base.debug: print "ToggleButton.MOUSEUP" self.run_signal_handlers (SIG_MOUSEUP) if event.data.button == 1: if self.__click: # The usual order for a ToggleButton: get a # click and toggle state upon it. if base.debug: print "ToggleButton.CLICKED" self.run_signal_handlers (SIG_CLICKED) self.set_active (not self.active) if base.debug: print "ToggleButton.TOGGLED" self.run_signal_handlers (SIG_TOGGLED) if not self.active: self.state = STATE_ENTERED elif (event.data.button == 1) and self.__click and not self.active: # Only a half click was made, reset the state of the # ToggleButton. self.state = STATE_NORMAL elif event.signal == SIG_MOUSEMOVE: # If the state was set in any way although the button's # not active, reset the state. if (not self.active) and (self.state == STATE_ACTIVE): self.state = STATE_NORMAL Button.notify (self, event) else: # Any other event will be escalated to the parent(s). Button.notify (self, event)
class Scoreboard(object): def __init__(self, main): self.main = main; self.highScores = []; self.highScoreDisplays = []; # populate the highscores and displays for i in range(0, 5): self.highScores.append(0); tScore = TextItem(400, 250 + i * 50, 400, 150, [str(i+1)+': ' + str(self.highScores[i])], showRect = False); self.highScoreDisplays.append(tScore); self.background_image = os.path.join('assets', 'startscreen', 'night_sunset_gradient.png'); self.background = Background(self.background_image); self.menuBtn = Button(500, 600, 200, 75, 'Menu'); self.playerScoreDisplay = TextItem(400, 100, 400, 150, [''], showRect = False, fontSize = 72); def listenForEvents(self): if 1 in pygame.mouse.get_pressed(): if self.menuBtn.is_under(pygame.mouse.get_pos()): self.main.set_mode('menu'); def renderScreen(self): self.background.draw(self.main.screen); self.menuBtn.draw(self.main.screen); self.playerScoreDisplay.draw(self.main.screen); for displays in self.highScoreDisplays: displays.draw(self.main.screen); def enter(self): print("entered Scoreboard"); self.playerScoreDisplay.setText(['You did it! Score: ' + self.main.score]); # append the player score to highScores print self.highScores self.highScores.append(int(self.main.score)); print self.highScores # sort highScore self.highScores.sort(); print self.highScores # remove the minimum and display the rest in sorted order self.highScores.pop(0); print self.highScores for i in range(0, 5): self.highScoreDisplays[i].setText([str(i+1)+': ' + str(self.highScores[5 - 1 - i])])
def __init__(self, question, parent, answer_var): self.width = 400 self.height = 200 self.parent = parent self.x = (parent.get_width() - self.width) / 2.0 self.y = (parent.get_height() - self.height) / 2.0 self.text = question answer_var = "LOL" Window.__init__(self, self.x, self.y, self.width, self.height, parent, "Ask", True) self.q_label = Button(20, 50, self.text, self.surface, (255, 255, 255), hpad=0) self.a_input = Input(20, 80, 360)
def __init__(self, game): self.font = game.font self.game = game self.grid_size = 26 # the width of grid self.start_x, self.start_y = 30, 50 # the coordinate of the left-up-most check grid self.edge_size = self.grid_size / 2 # the width of blank around the checkboard self.grid_count = 19 # the number of grid each column or row # init a return button self.return_to_welcome = Button([600, 500], [150, 30], "Return", self.font) self.win_num = 5
class Ask(Window): def __init__(self, question, parent, answer_var): self.width = 400 self.height = 200 self.parent = parent self.x = (parent.get_width() - self.width) / 2.0 self.y = (parent.get_height() - self.height) / 2.0 self.text = question answer_var = "LOL" Window.__init__(self, self.x, self.y, self.width, self.height, parent, "Ask", True) self.q_label = Button(20, 50, self.text, self.surface, (255, 255, 255), hpad=0) self.a_input = Input(20, 80, 360) def draw(self): self.q_label.draw(self.surface) self.a_input.draw(self.surface) Window.draw(self) def update(self, mouseclick, scrolldown=False, scrollup=False, keypressed=""): self.a_input.update(self.x + self.a_input.x, self.y + self.a_input.y, mouseclick, keypressed) Window.update(self, mouseclick, scrolldown=False, scrollup=False, keypressed="")
def __init__(self, parent=None, rect=sf.Rectangle(), select=False, active=False, \ alwaysUpdateSelection=True, alwaysUpdateActivation=True, \ permanentSelection=False, permanentActivation=False, step=1, \ values=sf.Vector2(0, 100), startValue=0, orientation=Direction.Horizontal, inStep=1): Widget.__init__(self, parent, rect) Active.__init__(self, select, active, alwaysUpdateSelection, alwaysUpdateActivation, \ permanentSelection, permanentActivation) if orientation == Direction.Horizontal: self._howActiveKeyboard = [sf.Keyboard.LEFT, sf.Keyboard.RIGHT] else: self._howActiveKeyboard = [sf.Keyboard.UP, sf.Keyboard.DOWN] self._currentValue = None self._limitValue=values self._step = step self._inStep = inStep self._background = None self._forground = None if orientation == Direction.Horizontal: self._background = Button(self, image=Image(None, \ sf.Image.create(rect.width, rect.height, sf.Color.WHITE))) self._forground = Button(self, image=Image(None, \ sf.Image.create(rect.width*inStep*step/(values.y - values.x), rect.height, sf.Color.CYAN))) else: self._background = Button(self, image=Image(None, \ sf.Image.create(rect.width, rect.height, sf.Color.WHITE))) self._forground = Button(self, image=Image(None, \ sf.Image.create(rect.width, rect.height*inStep*step/(values.y - values.x), sf.Color.CYAN))) self._isMoving=False self._mousePosMoving = sf.Vector2(0, 0) self._oldCurrentValue = 0 self._forground.posOrigin = Position.Center self._mousePos = sf.Vector2() self._orientation = orientation self.currentValue = startValue if orientation == Direction.Vertical: self.size = self.size
def startGame2(DISPLAYSURF): btn = Button('Start') clock = pygame.time.Clock() background=pygame.image.load('Images/1.png') run = True while run: DISPLAYSURF.blit(background,(0,0)) mouse = pygame.mouse.get_pos() for event in pygame.event.get(): if event.type == pygame.QUIT: run = False elif event.type == pygame.MOUSEBUTTONDOWN: if btn.obj.collidepoint(mouse): countInputs=1; m1 = inputbox.ask(DISPLAYSURF, "Mass, M",countInputs) m2 = float (m1) countInputs=countInputs+5; u1 = inputbox.ask(DISPLAYSURF, "Coefficient of Friction, u",countInputs) u2 = float (u1) countInputs=countInputs+5; f1 = inputbox.ask(DISPLAYSURF, "Force, F",countInputs) f2 = float (f1) v1 = u2 * f2 W = m2 * 9.8 if ( W > v1): font = pygame.font.Font(None, 36) text = font.render("The block will fall down.", 1, (10, 10, 10)) animation2(DISPLAYSURF,'down',text) else: res=pygame.image.load('Images/5.png') DISPLAYSURF.blit(res,(0,0)) errorScreen(DISPLAYSURF,"The block wont show any motion!") btn.draw(DISPLAYSURF, mouse, (200,300,100,20), (225,303)) pygame.display.update() clock.tick(60)
def __init__(self, parent, absx, absy, title=None): self.x = 0 self.y = 0 self.absx = absx self.absy = absy self.parent = parent self.width = self.parent.get_width() self.height = 20 self.surface = pygame.Surface((self.width, self.height)) self.surface.fill((100,100,100)) self.title = title if self.title != None: self.button = Button(0, 0, self.title, self.surface, (100,100,100))
def setup_menu_screen(self): title = TextBox(sf.Texture.from_file("res/title.png")) title.origin = title.local_bounds.center title.set_position((self.window.size.x / 2, (self.window.size.y / 3))) self.button_dict['title'] = title assaultgunbutton = Button(sf.Texture.from_file("res/AssaultGunButton.png")) assaultgunbutton.origin = assaultgunbutton.local_bounds.center assaultgunbutton.set_position(self.window.size / 2) self.button_dict['assaultgun'] = assaultgunbutton tankbutton = Button(sf.Texture.from_file("res/TankButton.png")) tankbutton.origin = tankbutton.local_bounds.center tankbutton.set_position((self.window.size.x / 2, (self.window.size.y / 3) * 2)) self.button_dict['tank'] = tankbutton
def __init__(self, main): self.main = main; self.highScores = []; self.highScoreDisplays = []; # populate the highscores and displays for i in range(0, 5): self.highScores.append(0); tScore = TextItem(400, 250 + i * 50, 400, 150, [str(i+1)+': ' + str(self.highScores[i])], showRect = False); self.highScoreDisplays.append(tScore); self.background_image = os.path.join('assets', 'startscreen', 'night_sunset_gradient.png'); self.background = Background(self.background_image); self.menuBtn = Button(500, 600, 200, 75, 'Menu'); self.playerScoreDisplay = TextItem(400, 100, 400, 150, [''], showRect = False, fontSize = 72);
def layoutWidgets(self): gx, gy = self.theme.getGridParams() r = self.rect self.bar.rect = Rect(r.width - gx, 0, gx, r.height) self.bar.visible = self.showSlider self.labels = [] bwidth, bheight = self.buttonSize self.rows = r.height / gy / bheight if self.showSlider: self.columns = (r.width - gx) / gx / bwidth else: self.columns = r.width / gx / bwidth for row in xrange(0, self.rows): for column in xrange(0, self.columns): x = column * gx * bwidth y = row * gy * bheight button = Button(self, action = 'onButtonPressed', rmbAction = 'onRButtonPressed', toggle = 1) button.subscribeAction('*', self) button.rect = Rect(x, y, bwidth * gx, bheight * gy) self.buttons.append(button) self.bar.slider.position = 0 self.bar.slider.min = 0 self.bar.slider.shown = self.rows self.itemsChanged()
def __init__(self, text=' ', x=None, y=None, width=35, height=35, bg_color=None, fg_color=None, selected_bg_color=None, selected_fg_color=None): self.upper_case = True self.max_width = width Button.__init__(self, text, None, x, y, width, height, bg_color, fg_color, selected_bg_color, selected_fg_color, border=None) self.h_margin = 0 self.v_margin = 0 self.h_spacing = 0 self.v_spacing = 0 self.set_v_align(Align.BOTTOM) self.set_h_align(Align.CENTER) self.label.set_v_align(Align.CENTER) self.label.set_h_align(Align.CENTER) for c in copy.copy(self.children): if isinstance(c, Border): self.children.remove(c) self.border = -1
def __init__(self, options, ypos, buttontextsize = variables.gettextsize()/variables.height): # a list of strings self.options = options self.current_option = 0 self.buttons = [] self.maxwidth = 0 for s in options: newb = Button(0, ypos, s, buttontextsize) self.buttons.append(newb) if newb.width()/variables.width > self.maxwidth: # devide by width because positions are multipliers of width self.maxwidth = newb.width()/variables.width spacing = self.maxwidth / 4 length = len(self.buttons) self.length = length centering = (1 - length * self.maxwidth - (length-1) * spacing) / 2 for i in range(self.length): self.buttons[i].screenwidthoverride = self.maxwidth self.buttons[i].x = i * (self.maxwidth + spacing) + centering self._freeze()
def loadStage(self, number): self.eraseStage() self.currentStage = [[] for i in range(0, len(self.mapData[number]))] self.blankList = [] self.step = 0 goalNum = 0 self.nextButton.setEnabled(False) if number == 0: self.backButton.setEnabled(False) else: self.backButton.setEnabled(True) gc.collect() self.stageText.setText('Stage: ' + str(number + 1)) self.stepText.setText('Step: ' + str(self.step)) self.currentLevel = number # 게임 화면을 중앙으로 x = (self.width - Object.size * len(self.mapData[number][0])) * 0.5 y = (self.height - Object.size * len(self.mapData[number])) * 0.5 Object.setPositionOffset(x, y + 40) for y in range(0, len(self.mapData[number])): for x in range(0, len(self.mapData[number][y])): # 일단 모든 맵을 공백으로 채운다. blankList에 blank를 추가한다. print(type(self.mapData[number][y][x]), type(EObjects.EPlayer), y, x) if self.mapData[number][y][x] != EObjects.EBlankWithNoGlass: if randomPercent(0.1): blank = Blank(x, y, self.blankPixmap1) elif randomPercent(0.05): blank = Blank(x, y, self.blankPixmap2) elif randomPercent(0.02): blank = Blank(x, y, self.blankPixmap3) else: blank = Blank(x, y, self.blankPixmap0) self.blankList.append(blank) blank.lower() # pass self.background.stackUnder(blank) if self.mapData[number][y][x] == EObjects.EBox: box = Box(x, y, self.boxPixmap) self.currentStage[y].append(box) box.raise_() elif self.mapData[number][y][x] == EObjects.EPlayer: playerStartX = x playerStartY = y print('Player found!') blank = Blank(x, y, self.blankPixmap0) self.currentStage[y].append(blank) blank.erase() elif self.mapData[number][y][x] == EObjects.EWall: self.currentStage[y].append(Wall(x, y, self.wallPixmap)) elif self.mapData[number][y][x] == EObjects.EButton: goalNum += 1 self.currentStage[y].append(Button(x, y, self.buttonPixmap)) elif self.mapData[number][y][ x] == EObjects.EBlank or self.mapData[number][y][ x] == EObjects.EBlankWithNoGlass: blank = Blank(x, y, self.blankPixmap0) self.currentStage[y].append(blank) blank.erase() self.goal = goalNum self.goalText.setText('Goal: ' + str(self.goal)) # ordering을 위해 player는 마지막에 생성한다! App.player = Player(playerStartX, playerStartY, self.playerPixmap)
def runGame(self): while 1: self.clock.tick(self.FPS) self.scoreLabel = self.myFont.render(str(self.newGame.score), 1, (0, 0, 0)) segundos = pygame.time.get_ticks() / 1000 self.timeLabel = self.myFont.render(str(segundos), 1, (0, 0, 0)) if self.newGame.gameState != 1: self.newGame.checkButton() self.newGame.redrawScreen(self.displayScreen, self.scoreLabel, self.timeLabel, self.width, self.height) for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONUP: self.newGame.processButton() self.playerGroup = self.newGame.playerGroup self.wallGroup = self.newGame.wallGroup self.ladderGroup = self.newGame.ladderGroup if self.newGame.gameState == 1: self.fireballGroup = self.newGame.fireballGroup self.coinGroup = self.newGame.coinGroup if self.fireballTimer == 0: self.newGame.CreateFireball( self.newGame.Enemies[0].getPosition(), 0) elif len(self.newGame.Enemies ) >= 2 and self.fireballTimer == 23: self.newGame.CreateFireball( self.newGame.Enemies[1].getPosition(), 1) elif len(self.newGame.Enemies ) >= 3 and self.fireballTimer == 46: self.newGame.CreateFireball( self.newGame.Enemies[2].getPosition(), 2) self.fireballTimer = (self.fireballTimer + 1) % 70 #Animacion del coin for coin in self.coinGroup: coin.animateCoin() self.newGame.Players[0].updateY(2) self.laddersCollidedBelow = self.newGame.Players[ 0].checkCollision(self.ladderGroup) self.wallsCollidedBelow = self.newGame.Players[ 0].checkCollision(self.wallGroup) self.newGame.Players[0].updateY(-2) self.newGame.Players[0].updateY(-2) self.wallsCollidedAbove = self.newGame.Players[ 0].checkCollision(self.wallGroup) self.newGame.Players[0].updateY(2) self.newGame.ladderCheck(self.laddersCollidedBelow, self.wallsCollidedBelow, self.wallsCollidedAbove) for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() if event.type == KEYDOWN: self.laddersCollidedExact = self.newGame.Players[ 0].checkCollision(self.ladderGroup) if event.key == K_q: self.newGame.gameState = 2 self.newGame.ActiveButtons[0] = 0 self.newGame.ActiveButtons[1] = 1 self.newGame.ActiveButtons[2] = 1 self.Button = Button( pygame.load.image("Assets/score.png"), (900, 400), "Score") if (event.key == K_SPACE and self.newGame.Players[0].onLadder == 0) or (event.key == K_w and self.laddersCollidedExact): self.direction = 2 if self.newGame.Players[ 0].isJumping == 0 and self.wallsCollidedBelow: self.newGame.Players[0].isJumping = 1 self.newGame.Players[0].currentJumpSpeed = 7 if event.key == K_SPACE: mixer.music.load('Assets/jump.wav') mixer.music.set_volume(2) pygame.mixer.music.play() self.newGame.Players[0].continuousUpdate( self.wallGroup, self.ladderGroup) keyState = pygame.key.get_pressed() if keyState[pygame.K_d]: if self.newGame.direction != 4: self.newGame.direction = 4 self.newGame.cycles = -1 self.newGame.cycles = (self.newGame.cycles + 1) % 10 if self.newGame.cycles < 5: self.newGame.Players[0].updateWH( pygame.image.load('Assets/right.png'), "H", self.newGame.Players[0].getSpeed(), 15, 15) else: self.newGame.Players[0].updateWH( pygame.image.load('Assets/right2.png'), "H", self.newGame.Players[0].getSpeed(), 15, 15) wallsCollidedExact = self.newGame.Players[ 0].checkCollision(self.wallGroup) if wallsCollidedExact: self.newGame.Players[0].updateWH( pygame.image.load('Assets/right.png'), "H", -self.newGame.Players[0].getSpeed(), 15, 15) if keyState[pygame.K_a]: if self.newGame.direction != 3: self.newGame.direction = 3 self.newGame.cycles = -1 self.newGame.cycles = (self.newGame.cycles + 1) % 10 if self.newGame.cycles < 5: self.newGame.Players[0].updateWH( pygame.image.load('Assets/left.png'), "H", -self.newGame.Players[0].getSpeed(), 15, 15) else: self.newGame.Players[0].updateWH( pygame.image.load('Assets/left2.png'), "H", -self.newGame.Players[0].getSpeed(), 15, 15) wallsCollidedExact = self.newGame.Players[ 0].checkCollision(self.wallGroup) if wallsCollidedExact: self.newGame.Players[0].updateWH( pygame.image.load('Assets/left.png'), "H", self.newGame.Players[0].getSpeed(), 15, 15) if keyState[pygame.K_w] and self.newGame.Players[0].onLadder: self.newGame.Players[0].updateWH( pygame.image.load('Assets/still.png'), "V", -self.newGame.Players[0].getSpeed() / 2, 15, 15) if len(self.newGame.Players[0].checkCollision( self.ladderGroup)) == 0 or len( self.newGame.Players[0].checkCollision( self.wallGroup)) != 0: self.newGame.Players[0].updateWH( pygame.image.load('Assets/still.png'), "V", self.newGame.Players[0].getSpeed() / 2, 15, 15) if keyState[pygame.K_s] and self.newGame.Players[0].onLadder: self.newGame.Players[0].updateWH( pygame.image.load('Assets/still.png'), "V", self.newGame.Players[0].getSpeed() / 2, 15, 15) self.newGame.redrawScreen(self.displayScreen, self.scoreLabel, self.timeLabel, self.width, self.height) self.newGame.fireballCheck() coinsCollected = pygame.sprite.spritecollide( self.newGame.Players[0], self.coinGroup, True) self.newGame.coinCheck(coinsCollected) self.newGame.checkVictory(self.clock) for enemy in self.newGame.Enemies: enemy.continuousUpdate(self.wallGroup, self.ladderGroup) pygame.display.update()
class Game: pygame.init() #display data WIDTH = 1200 HEIGHT = 800 CENTER_X = WIDTH//2 CENTER_Y = HEIGHT//2 SIDE_X = 1 SIDE_O = 2 BLACK = (0, 0, 0) WHITE = (255, 255, 255) RED = (255, 0, 0) GREEN = (0, 255, 0) BLUE = (0, 0, 255) SADDLEBROWN = (139, 69, 19) GRAY = (110, 110, 110) MELLOW_YELLOW = (248, 222, 126) NBOX_COLOR = RED CGRATS_COLOR = BLUE CGRATS_FONT = pygame.font.Font('../resources/SIFONN_PRO.otf', 90) BUTTON_FONT = pygame.font.Font('../resources/SIFONN_PRO.otf', 36) #board stats START_CORD = 40 END_CORD = 760 BOARD_SIZE = END_CORD-START_CORD BOARD_CENTER = (BOARD_SIZE/2)+40 #locations of the little boxes LBOX_SIZE = 80 LX_CORDS = list(range(START_CORD,END_CORD,LBOX_SIZE)) LY_CORDS = list(range(START_CORD,END_CORD,LBOX_SIZE)) LBOX_CORDS = [LX_CORDS, LY_CORDS] #locations of the big boxes BBOX_SIZE = 3*LBOX_SIZE BX_CORDS = list(range(START_CORD,END_CORD,BBOX_SIZE)) BY_CORDS = list(range(START_CORD,END_CORD,BBOX_SIZE)) BBOX_CORDS = [BX_CORDS, BY_CORDS] #different line widths GLINE_WIDTH = 2 BGLINE_WIDTH = 5 LXO_LINE_WIDTH = 9 BXO_LINE_WIDTH = 18 END_XO_LINE_WIDTH = 27 #X and O formatting offsets X_OFFSET = 10 O_OFFSET = 7 #end aesthetics variables CGRATS_CENTER_DISP = [200, 100] #[x disp rom center, y disp from center] def __init__(self, player1IsHuman, player2IsHuman): self.screen = pygame.display.set_mode((Game.WIDTH, Game.HEIGHT)) self.clock = pygame.time.Clock() # self.clock.tick(60) self.player1IsHuman = player1IsHuman self.player2IsHuman = player2IsHuman self.game_moves = 0 self.game_over = False self.game_drawn = False self.quit = False self.game_record = np.zeros([9,9]) #array keeping track of the whole game grid self.big_grid_record = np.zeros([3,3]) #array keeping track of the big boxes that are completed self.small_grid_record = np.zeros([3,3]) #array representing the big box that I've clicked into and the values of each of the 9 boxes within it self.nsmall_grid_record = np.zeros([3,3]) #array representing the big box that I should go into next and the values of each of the 9 boxes within it self.next_b_cords = [] self.next_box_list = [] self.cords = [] self.b_cords = [] #icon color self.X_color = Game.GRAY self.O_color = Game.GRAY #post game self.post_game_mouse_pos = None self.post_game_clicked = False def init(self): if (self.player1IsHuman): self.player1 = Player(Game.SIDE_X) else: self.player1 = AI(Game.SIDE_X) if (self.player2IsHuman): self.player2 = Player(Game.SIDE_O) else: self.player2 = AI(Game.SIDE_O) def draw_grid(self, box_cords, linewidth, screen): for i in range(2): for cord in box_cords[i][1:]: #Not drawing the first and last line so that the board doesn't look like a sudoku board if i == 0: self.start_pos = [cord, Game.START_CORD] self.end_pos = [cord, Game.END_CORD] elif i == 1: self.start_pos = [Game.START_CORD, cord] self.end_pos = [Game.END_CORD, cord] pygame.draw.line(screen, Game.BLACK, self.start_pos, self.end_pos, linewidth) # pygame.display.update() def draw_shapes(self, grid_record, size, linewidth, screen): if not self.next_b_cords or not self.b_cords: return for row in range(len(grid_record[:,1])): row_cord = row*size+Game.START_CORD for col in range(len(grid_record[1,:])): col_cord = col*size+Game.START_CORD if size == Game.BBOX_SIZE and grid_record[row,col] != 0 and (row_cord != self.next_b_cords[0] or col_cord != self.next_b_cords[1]): #covering up smaller shapes if a box has been won pygame.draw.rect(screen, Game.WHITE, [row_cord, col_cord, size, size]) elif size == Game.BBOX_SIZE and grid_record[row,col] != 0 and (row_cord == self.next_b_cords[0] and col_cord == self.next_b_cords[1]): pygame.draw.rect(screen, Game.NBOX_COLOR, [row_cord, col_cord, size, size]) if grid_record[row,col] == 1: pygame.draw.line(screen, Game.BLACK, [row_cord+Game.X_OFFSET, col_cord+Game.X_OFFSET], [row_cord+size-Game.X_OFFSET, col_cord+size-Game.X_OFFSET], linewidth) pygame.draw.line(screen, Game.BLACK, [row_cord+Game.X_OFFSET, col_cord+size-Game.X_OFFSET], [row_cord+size-Game.X_OFFSET, col_cord+Game.X_OFFSET], linewidth) elif grid_record[row,col] == 2: pygame.draw.ellipse(screen, Game.BLACK, [row_cord+Game.O_OFFSET, col_cord+Game.O_OFFSET, size-2*Game.O_OFFSET, size-2*Game.O_OFFSET], linewidth) # pygame.display.update() def draw_rects(self, big_grid_record, screen, size): if not self.next_b_cords or not self.b_cords: return for row in range(len(big_grid_record[:,1])): row_cord = row*size+Game.START_CORD for col in range(len(big_grid_record[1,:])): col_cord = col*size+Game.START_CORD if (row_cord == self.b_cords[0] and col_cord == self.b_cords[1]): #covering up the previously red boxes pygame.draw.rect(screen, Game.WHITE, [row_cord, col_cord, size, size]) if (row_cord == self.next_b_cords[0] and col_cord == self.next_b_cords[1]): #making the next box red pygame.draw.rect(screen, Game.NBOX_COLOR, [row_cord, col_cord, size, size]) # pygame.display.update() def side_panel_display(self): self.game_moves_display = Button(820, 40, 320, 80, Game.BLACK, Game.BUTTON_FONT, f"Game Moves: {self.game_moves}", self.screen) self.game_moves_display.draw_button() # self.resign_button = Button(820, 160, 320, 80, Game.GRAY, Game.BUTTON_FONT, "Resign", self.screen) # self.resign_button.draw_button() if self.game_moves % 2 == 0 and not self.game_over: self.X_color = Game.MELLOW_YELLOW self.O_color = Game.GRAY elif self.game_moves % 2 == 1 and not self.game_over: self.O_color = Game.MELLOW_YELLOW self.X_color = Game.GRAY else: self.X_color = Game.GRAY self.O_color = Game.GRAY self.X_icon = Button(860, 160, 80, 80, self.X_color, Game.BUTTON_FONT, "X", self.screen) self.X_icon.draw_button() self.O_icon = Button(1020, 160, 80, 80, self.O_color, Game.BUTTON_FONT, "O", self.screen) self.O_icon.draw_button() self.replay_button = Button(820, 540, 320, 80, Game.GREEN, Game.BUTTON_FONT, "Replay", self.screen) self.replay_button.draw_button() self.quit_to_title = Button(820, 660, 320, 80, Game.BLACK, Game.BUTTON_FONT, "Quit to Title", self.screen) self.quit_to_title.draw_button() pygame.display.update() def inform_and_input(self, obj): for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() if event.type == pygame.MOUSEBUTTONDOWN and isinstance(obj, Player): obj.mouse_pos = obj.get_mouse_pos() obj.clicked = True if self.replay_button.is_clicked(obj.mouse_pos) and obj.clicked: game_loop(flags) if self.quit_to_title.is_clicked(obj.mouse_pos) and obj.clicked: self.quit = True else: obj.clicked = False if isinstance(obj, AI): #sending the AI game info relevant to its moving obj.get_game_moves(self.game_moves) obj.get_info(self.game_over, self.next_b_cords, self.game_record) if obj.AI_turn: #if it's the AI's turn obj.mouse_pos = obj.get_mouse_pos() obj.clicked = True else: obj.clicked = False def update_objects(self, obj): if obj.mouse_pos is None: self.inform_and_input(obj) #take more input because no input was previously supplied return self.cords, self.cords_idx = self._find_box(obj.mouse_pos, Game.LBOX_CORDS, Game.LBOX_SIZE) #print("cords", self.cords) #print("cords_idx", self.cords_idx) self.b_cords, self.b_cords_idx = self._find_box(obj.mouse_pos, Game.BBOX_CORDS, Game.BBOX_SIZE) #print("b_cords", self.b_cords) #print("b_cords_idx", self.b_cords_idx) if (not self.cords or not self.b_cords): self.inform_and_input(obj) #take more input because an invalid input was previously supplied return if ((self.game_moves == 0) or (obj.mouse_pos[0] >= self.next_b_cords[0] and obj.mouse_pos[0] < self.next_b_cords[0]+Game.BBOX_SIZE and obj.mouse_pos[1] >= self.next_b_cords[1] and obj.mouse_pos[1] < self.next_b_cords[1]+Game.BBOX_SIZE and not np.all(self.nsmall_grid_record) and self.game_record[self.cords_idx[0], self.cords_idx[1]] == 0)): self.game_moves += 1 self._update_grid_record(obj, self.game_record, self.cords_idx) self._isolate_little_box(self.game_record, self.cords_idx) if self.big_grid_record[self.b_cords_idx[0], self.b_cords_idx[1]] == 0: self.winning_box_side = self._grid_win_check(self.small_grid_record) if self.winning_box_side and (self.winning_box_side == obj.side or self.winning_box_side == 3): self._update_grid_record(obj, self.big_grid_record, self.b_cords_idx) self.small_grid_record[self.small_grid_record == 0] = 3 # print(self.small_grid_record) # print(self.game_record) self._identify_next_big_box(self.small_grid_elems, self.game_record)#big grid must be updated before this method can be called self.winning_game_side = self._grid_win_check(self.big_grid_record) if self.winning_game_side: self.game_over = True if np.all(self.game_record): self.game_over = True self.game_drawn = True def _find_box(self, mouse_pos, box_cords, size): cords = [] cords_idx = [] for i in [0, 1]: for cord in reversed(box_cords[i]): if cord <= mouse_pos[i] and mouse_pos[i] < Game.END_CORD: cords.append(cord) cords_idx.append(int((cord-Game.START_CORD)/size)) break if len(cords) != 2: cords = [] cords_idx = [] return cords, cords_idx def _update_grid_record(self, obj, grid_record, cords_idx): grid_record[cords_idx[0], cords_idx[1]] = obj.side def _isolate_little_box(self, game_record, cords_idx): for x in [0, 3, 6]: if cords_idx[0] < x+3 and cords_idx[0] >= x: for y in [0, 3, 6]: if cords_idx[1] < y+3 and cords_idx[1] >= y: self.small_grid_record = self.game_record[x:x+3, y:y+3] self.small_grid_elems = [cords_idx[0]-x, cords_idx[1]-y] def _identify_next_big_box(self, small_grid_elems, game_record): if self.big_grid_record[self.small_grid_elems[0], self.small_grid_elems[1]] == 0: #if the proposed next big box has room for other shapes... self.next_cords = [small_grid_elems[0]*3, small_grid_elems[1]*3] self.next_box_list.append(self.next_cords) self.next_b_cords = [(small_grid_elems[0]*Game.BBOX_SIZE)+Game.START_CORD, (small_grid_elems[1]*Game.BBOX_SIZE)+Game.START_CORD] # print(self.next_box_list) else: # print("entered else clause of _identify_next_big_box") for prev_next_cords in reversed(self.next_box_list): if self.big_grid_record[int(prev_next_cords[0]/3), int(prev_next_cords[1]/3)] == 0: self.next_cords = prev_next_cords self.next_box_list.append(self.next_cords) self.next_b_cords = [(int(prev_next_cords[0]/3*Game.BBOX_SIZE)+Game.START_CORD), (int(prev_next_cords[1]/3*Game.BBOX_SIZE)+Game.START_CORD)] #setting the next box cords to the location of the newly proposed next box # print(self.next_cords) break else: if not np.all(self.game_record): raise Exception("No empty big box for the next shape to go into") self.nsmall_grid_record = game_record[self.next_cords[0]:self.next_cords[0]+3, self.next_cords[1]:self.next_cords[1]+3] # print("nsmall_grid_record ", self.nsmall_grid_record) def _grid_win_check(self, grid_record): for winning_side in [1, 2]: for row_or_col in [0, 1, 2]: if np.all(grid_record[row_or_col, :] == winning_side): return winning_side if np.all(grid_record[:, row_or_col] == winning_side): return winning_side if grid_record[0,0] == winning_side and grid_record[0,0] == grid_record[1,1] and grid_record[0,0] == grid_record[2,2]: return winning_side if grid_record[0,2] == winning_side and grid_record[0,2] == grid_record[1,1] and grid_record[0,2] == grid_record[2,0]: return winning_side elif np.all(grid_record): return 3 #drawn else: return 0 def end(self, winning_game_side): pygame.draw.rect(self.screen, Game.WHITE, [Game.START_CORD, Game.START_CORD, Game.BOARD_SIZE, Game.BOARD_SIZE]) if self.winning_game_side == 1: pygame.draw.line(self.screen, Game.BLACK, [Game.START_CORD+Game.X_OFFSET, Game.START_CORD+Game.X_OFFSET], [Game.END_CORD-Game.X_OFFSET, Game.END_CORD-Game.X_OFFSET], Game.END_XO_LINE_WIDTH) #drawing big X pygame.draw.line(self.screen, Game.BLACK, [Game.START_CORD+Game.X_OFFSET, Game.END_CORD-Game.X_OFFSET], [Game.END_CORD-Game.X_OFFSET, Game.START_CORD+Game.X_OFFSET], Game.END_XO_LINE_WIDTH) elif self.winning_game_side == 2: pygame.draw.ellipse(self.screen, Game.BLACK, [Game.START_CORD+Game.O_OFFSET, Game.START_CORD+Game.O_OFFSET, Game.BOARD_SIZE-2*Game.O_OFFSET, Game.BOARD_SIZE-2*Game.O_OFFSET], Game.END_XO_LINE_WIDTH) #drawing big O elif self.game_drawn: pygame.draw.line(self.screen, Game.BLACK, [Game.START_CORD+Game.X_OFFSET, Game.START_CORD+Game.X_OFFSET], [Game.END_CORD-Game.X_OFFSET, Game.END_CORD-Game.X_OFFSET], Game.END_XO_LINE_WIDTH) #drawing big X pygame.draw.line(self.screen, Game.BLACK, [Game.START_CORD+Game.X_OFFSET, Game.END_CORD-Game.X_OFFSET], [Game.END_CORD-Game.X_OFFSET, Game.START_CORD+Game.X_OFFSET], Game.END_XO_LINE_WIDTH) pygame.draw.ellipse(self.screen, Game.BLACK, [Game.START_CORD+Game.O_OFFSET, Game.START_CORD+Game.O_OFFSET, Game.BOARD_SIZE-2*Game.O_OFFSET, Game.BOARD_SIZE-2*Game.O_OFFSET], Game.END_XO_LINE_WIDTH) pygame.display.update() def end_aesthetics(self, winning_game_side, game_drawn): if winning_game_side == 1: congrats = Button(Game.BOARD_CENTER-Game.CGRATS_CENTER_DISP[0], Game.BOARD_CENTER-Game.CGRATS_CENTER_DISP[1], Game.CGRATS_CENTER_DISP[0]*2, Game.CGRATS_CENTER_DISP[1]*2, Game.CGRATS_COLOR, Game.CGRATS_FONT, "X WINS!", self.screen) congrats.draw_button() elif winning_game_side == 2: congrats = Button(Game.BOARD_CENTER-Game.CGRATS_CENTER_DISP[0], Game.BOARD_CENTER-Game.CGRATS_CENTER_DISP[1], Game.CGRATS_CENTER_DISP[0]*2, Game.CGRATS_CENTER_DISP[1]*2, Game.CGRATS_COLOR, Game.CGRATS_FONT, "O WINS!", self.screen) congrats.draw_button() elif game_drawn: congrats = Button(Game.BOARD_CENTER-Game.CGRATS_CENTER_DISP[0], Game.BOARD_CENTER-Game.CGRATS_CENTER_DISP[1], Game.CGRATS_CENTER_DISP[0]*2, Game.CGRATS_CENTER_DISP[1]*2, Game.CGRATS_COLOR, Game.CGRATS_FONT, "DRAW!", self.screen) congrats.draw_button() pygame.display.update()
def compSbyNLM(DISPLAY_SURF): print("INSIDE SbyNLM.py") btn_s1 = pygame.image.load('Images/buttons/parameters/s1.png') btn_s2 = pygame.image.load('Images/buttons/parameters/s2.png') btn_s3 = pygame.image.load('Images/buttons/parameters/s3.png') btn_s4 = pygame.image.load('Images/buttons/parameters/s4.png') btn_back = Button('Back') btn_back.setColor(RED) btn_back.setHoverColor(LIME) btn_back.setFontColor(BLUE) clock = pygame.time.Clock() background = pygame.image.load('Images/game1/input_values.png') run = True while run: DISPLAY_SURF.blit(background, SCREEN_TOPLEFT) mouse = pygame.mouse.get_pos() for event in pygame.event.get(): if event.type == pygame.QUIT: run = False pygame.quit() sys.exit() elif event.type == pygame.MOUSEBUTTONDOWN: if rect_s1.collidepoint(mouse): countInputs = 1 # countInputs is related to the y coordinate of the input text boxes initial_velocity = inputbox.ask(DISPLAY_SURF, "Initial velocity, u", countInputs) initial_velocity = float(initial_velocity) countInputs = countInputs + 5 acceleration = inputbox.ask(DISPLAY_SURF, "Acceleration, a", countInputs) acceleration = float(acceleration) countInputs = countInputs + 5 time = inputbox.ask(DISPLAY_SURF, "Time, t", countInputs) time = float(time) if (time < 0): errorScreen.errorScreen(DISPLAY_SURF, "Negative time entered") run = False displacement = initial_velocity * time + acceleration * time * time / 2 final_velocity = initial_velocity + acceleration * time font = pygame.font.Font(None, 36) text = font.render( "The Displacement hence calculated is " + str(displacement) + "metre", 1, WHITE) path = "Images/game1/Explanation/Calculate_S/G1/" anim1(DISPLAY_SURF, text, final_velocity, initial_velocity, acceleration, time, displacement, path) run = False elif rect_s2.collidepoint(mouse): countInputs = 1 # countInputs is related to the y coordinate of the input text boxes final_velocity = inputbox.ask(DISPLAY_SURF, "Final velocity, v", countInputs) final_velocity = float(final_velocity) countInputs = countInputs + 5 acceleration = inputbox.ask(DISPLAY_SURF, "Acceleration, a", countInputs) acceleration = float(acceleration) countInputs = countInputs + 5 time = inputbox.ask(DISPLAY_SURF, "Time, t", countInputs) time = float(time) if (time < 0): errorScreen.errorScreen(DISPLAY_SURF, "Negative time entered") run = False displacement = final_velocity * time - acceleration * time * time / 2 initial_velocity = final_velocity - acceleration * time font = pygame.font.Font(None, 36) text = font.render( "The Displacement hence calculated is " + str(displacement) + "metre", 1, WHITE) path = "Images/game1/Explanation/Calculate_S/G2/" anim1(DISPLAY_SURF, text, final_velocity, initial_velocity, acceleration, time, displacement, path) run = False elif rect_s3.collidepoint(mouse): countInputs = 1 # countInputs is related to the y coordinate of the input text boxes initial_velocity = inputbox.ask(DISPLAY_SURF, "Initial velocity, u", countInputs) initial_velocity = float(initial_velocity) countInputs = countInputs + 5 final_velocity = inputbox.ask(DISPLAY_SURF, "Final velocity, v", countInputs) final_velocity = float(final_velocity) countInputs = countInputs + 5 time = inputbox.ask(DISPLAY_SURF, "Time, t", countInputs) time = float(time) if (time < 0): errorScreen.errorScreen(DISPLAY_SURF, "Negative time entered") run = False if (time == 0): displacement = 0 acceleration = 0 else: acceleration = (final_velocity - initial_velocity) / time if (acceleration == 0): displacement = initial_velocity * time else: displacement = (final_velocity * final_velocity - initial_velocity * initial_velocity ) / 2 / acceleration font = pygame.font.Font(None, 36) text = font.render( "The Displacement hence calculated is " + str(displacement) + "metre", 1, WHITE) path = "Images/game1/Explanation/Calculate_S/G3/" anim1(DISPLAY_SURF, text, final_velocity, initial_velocity, acceleration, time, displacement, path) run = False elif rect_s4.collidepoint(mouse): countInputs = 1 # countInputs is related to the y coordinate of the input text boxes initial_velocity = inputbox.ask(DISPLAY_SURF, "Initial velocity, u", countInputs) initial_velocity = float(initial_velocity) countInputs = countInputs + 5 final_velocity = inputbox.ask(DISPLAY_SURF, "Final Velocity, v", countInputs) final_velocity = float(final_velocity) countInputs = countInputs + 5 acceleration = inputbox.ask(DISPLAY_SURF, "Acceleration, a", countInputs) acceleration = float(acceleration) if (acceleration == 0): displacement = 0 time = 0 else: displacement = (final_velocity * final_velocity - initial_velocity * initial_velocity) / 2 / acceleration time = (final_velocity - initial_velocity) / acceleration if (time < 0): errorScreen.errorScreen( DISPLAY_SURF, "Inconsistent data entered.(results to Negative time)" ) run = False font = pygame.font.Font(None, 36) text = font.render( "The Displacement hence calculated is " + str(displacement) + "metre", 1, WHITE) path = "Images/game1/Explanation/Calculate_S/G4/" anim1(DISPLAY_SURF, text, final_velocity, initial_velocity, acceleration, time, displacement, path) run = False elif btn_back.obj.collidepoint(mouse): run = False rect_s1 = DISPLAY_SURF.blit(btn_s1, (125, 103)) rect_s2 = DISPLAY_SURF.blit(btn_s2, (125, 153)) rect_s3 = DISPLAY_SURF.blit(btn_s3, (125, 203)) rect_s4 = DISPLAY_SURF.blit(btn_s4, (125, 253)) btn_back.draw(DISPLAY_SURF, mouse, (550, 10, 45, 20), (560, 13)) pygame.display.update() clock.tick(60) print("Exit from SbyNLM")
def create_button(self, size, position, color, text, hover_func, click_func): button = Button(size, position, color, text, self._display_surf, hover_func, click_func) self.app_objects.append(button)
def main():# 你可能没学过,但不难理解,这是一个主函数,整个程序的入口 # pygame init # it is a start of game pygame.init() # define size of font themeFont = pygame.font.Font(GL.cusFontAddress, 100) themeName = themeFont.render("姑姑咕咕", True, GL.BLACK) # try centered themeRec = themeName.get_rect() themeRec.center = (GL.scrLength/2, GL.scrWidth/4) # define size of item # itemFont = pygame.font.Font(cusFontAddress, 30) from Button import Button btItem = [0]*5 # ???我也不知道怎么办 btItem[0] = Button("src/itemImage/开始游戏up.png", "src/itemImage/开始游戏down.png", (GL.scrLength/2, 300)) btItem[1] = Button("src/itemImage/继续游戏up.png", "src/itemImage/继续游戏down.png", (GL.scrLength/2, 370)) btItem[2] = Button("src/itemImage/帮助up.png", "src/itemImage/帮助down.png", (GL.scrLength/2, 440)) btItem[3] = Button("src/itemImage/关于up.png", "src/itemImage/关于down.png", (GL.scrLength/2, 510)) btItem[4] = Button("src/itemImage/退出up.png", "src/itemImage/退出down.png", (GL.scrLength/2, 580)) # define screen background picture bg = pygame.image.load("src/bgpicture.png") GL.screen.blit(bg, (0,0)) # load game name to screen GL.screen.blit(themeName, themeRec) # load item for i in range(0,5): btItem[i].render() # keep running of program while True: # monitor events for event in pygame.event.get(): # quit event if event.type in (QUIT, ): # quit the game but I don't know why need two statement pygame.quit() sys.exit() for i in range(0,5): flag = btItem[i].render() if flag and event.type == MOUSEBUTTONDOWN: if i == 0: from mainGame import run run() elif i == 1: print("读档中。。。") print("继续游戏~") elif i == 2: print("帮助~") print("反正也没人看/") elif i == 3: print("开发人员:") print("孙Sir") print("张Sir") print("杨头子") elif i == 4: pygame.quit() sys.exit() else: print("Bug!!!") pygame.display.update()
class PauseMenu: def __init__(self, map_objects, map_background): self.result = -1 # переменная для отслеживания состояния экрана self.map_keys = map_objects[0] # изображения клавиш self.map_objects = map_objects[1:] # изображений нот self.map_background = map_background # изображений заднего фона self.map_background.set_alpha(100) self.continue_btn = Button(455, 200, 238, 72, '', continue_button_image, self.continue_map) self.restart_btn = Button(455, 350, 238, 72, '', restart_button_image, self.restart) self.back_btn = Button(455, 500, 238, 72, '', back_button_image, self.back) def get_result(self): return self.result def continue_map(self): self.result = 0 def restart(self): self.result = 1 def back(self): self.result = 2 def render_pause(self): # отрисовка экрана паузы display.blit(background_image, (0, 0)) self.continue_btn.draw(0, 0) self.restart_btn.draw(0, 0) self.back_btn.draw(0, 0) def render_map(self): # отрисовка карты во время обратного отсчета display.fill((0, 0, 0)) display.blit(self.map_background, (0, 0)) display.blit(self.map_keys[0], (st_x, 0)) for notes in self.map_objects[0]: # отрисовка одиночных нот if len(notes) == 1: sprite = notes[0][0] display.blit(sprite.image, sprite.rect) elif len(notes) > 1: for note in notes: sprite = note[0] display.blit(sprite.image, sprite.rect) for slider in self.map_objects[1]: # отрисовка длинных нот for obj in slider: try: sprite = obj[0] display.blit(sprite.image, sprite.rect) except (AttributeError, TypeError): pass key0d_image, key1d_image = self.map_keys[1:] display.blit(key0d_image, (st_x + 30, 617)) display.blit(key1d_image, (st_x + 30 + 45, 617)) display.blit(key1d_image, (st_x + 30 + 45 * 2, 617)) display.blit(key0d_image, (st_x + 30 + 45 * 3, 617))
def Render(self): render = Button.Render(self) render.js += FORCE_SUBMIT_JS % ({'id': self.id}) return render
def __init__(self, caption="Submit"): Button.__init__(self, caption)
# the following assumes that an LED is run from VCC to xio-p0 with its cathode in the latter # ie: pulling pin low turns LED on, setting high turns it off # it also assums a normally-open pushbutton is connected between ground and xio-p1 # when the pushbutton is pressed the LED should light. when it is released the # LED should be extinguished import time from Button import Button import CHIP_IO.GPIO as GPIO buttons = [ Button("RED", "LCD-D3", "LCD-D4"), Button("YELLOW", "LCD-D5", "LCD-D6"), Button("BLUE", "LCD-D7", "LCD-D10"), Button("GREEN", "LCD-D11", "LCD-D12"), Button("WHITE", "LCD-D13", "LCD-D14") ] isPressed = False while True: time.sleep(3.00) # sleep 50 milliseconds before checking again print("----------------------") for btn in buttons: print("checking: " + btn.color + " - on: " + str(btn.isLedOn())) if btn.isLedOn(): btn.turnOff()
def run_game(): # Get access to our game configuration configuration = Config() # initialize game pygame.init() screen = pygame.display.set_mode((configuration.screen_width, configuration.screen_height), 0, 32) clock = pygame.time.Clock() scoreboard = Scoreboard(screen, configuration) play_button = Button(screen, configuration.screen_width/2-configuration.button_width/2, configuration.screen_height/2-configuration.button_height/2, configuration, "Play", None, None, None) game_over_button = Button(screen, play_button.x_position, play_button.y_position-3*configuration.button_height, configuration, "Game Over!", None, None, (160,0,0)) score_button = Button(screen, play_button.x_position, play_button.y_position-2*configuration.button_height, configuration, "Score:", None, None, (255,69,0)) highest_score_button = Button(screen, play_button.x_position, play_button.y_position-configuration.button_height, configuration, "Highest Score:" + str(configuration.highest_score), None, None, (255,69,0)) heading_button = Button(screen, 0, 0, configuration, "Bows and Balloons", 800, None, (160,0,160)) home_page = HomePage(screen, configuration) balloons = [] demons = [] arrows = [] # Create our dagger # sword = Sword(screen, configuration.scoreboard_height) archer = Archer(screen, configuration.scoreboard_height) configuration.set_archer_width(archer.image_w) # Create our game game_play, with access to appropriate game parameters: game_play = GamePlay(screen, configuration, scoreboard, balloons, demons, archer, arrows) # main event loop while True: # Advance our game clock, get the current mouse position, and check for new events time_passed = clock.tick(50) mouse_x, mouse_y = pygame.mouse.get_pos()[0], pygame.mouse.get_pos()[1] game_play.check_events(play_button, mouse_x, mouse_y) # Redraw the empty screen before redrawing any game objects screen.fill(configuration.bg_color) if configuration.game_active: # Update the sword's position and check for popped or disappeared balloons game_play.update_archer(mouse_x, mouse_y, time_passed) game_play.check_balloons(time_passed) game_play.check_demons() game_play.check_arrows() scoreboard.update_time(time_passed) # If all balloons have disappeared, either through popping or rising, # release a new batch of balloons. if len(balloons) == 0: # If we are not just starting a game, increase the balloon speed and points per balloon, # and increment batches_finished if scoreboard.balloons_popped > 0: # Increase the balloon speed, and other factors, for each new batch of balloons. configuration.balloon_speed *= configuration.speed_increase_factor configuration.points_per_balloon = int(round(configuration.points_per_balloon * configuration.speed_increase_factor)) scoreboard.batches_finished += 1 # If player has completed required batches, increase batch_size if scoreboard.batches_finished % configuration.batches_needed == 0 and scoreboard.batches_finished > 0: configuration.batch_size += 1 game_play.release_batch() scoreboard.blitme() else: # Game is not active, so... # Show play button score_button.msg = "Score: " + str(scoreboard.score) score_button.prep_msg() play_button.blitme() # Show instructions for first few games. # if configuration.games_played < 3: home_page.blitme() # If a game has just ended, show Game Over button if configuration.games_played > 0: game_over_button.blitme() score_button.blitme() configuration.check_score(scoreboard.score) highest_score_button.msg = "Highest Score: " + str(configuration.highest_score) highest_score_button.prep_msg() highest_score_button.blitme() heading_button.blitme() # Display updated scoreboard # Show the redrawn screen pygame.display.flip()
def __init__(self): super().__init__() self.background = load_texture(ANOTHER_PIC) button = Button(BUTTON_POS_X, BUTTON_POS_Y, RESULT_BUTTON_WIDTH, RESULT_BUTTON_HEIGHT, BUTTON_MESSAGE, "", FONT_SIZE) self.button_list.append(button)
def __init__(self, *args, **kwargs): button = Button(_('Upload')) AjaxUpload_Generic.__init__(self, button, *args, **kwargs)
from Button import Button button1 = Button(18, "PULLUP") button2 = Button(23, "PULLUP") button3 = Button(24, "PULLUP") while True: button1state = button1.isPressed() button2state = button2.isPressed() button3state = button3.isPressed() if (button1state): print("Button 1 Pressed") if (button2state): print("Button 2 Pressed") if (button3state): print("Button 3 Pressed")
class TicTacToeView: def __init__(self,GRID_SIZE): pygame.init() self.SQUARESIZE = 300//GRID_SIZE self.RADIUS = int(self.SQUARESIZE/2.1) self.width = GRID_SIZE * self.SQUARESIZE self.height = (GRID_SIZE + 1) * self.SQUARESIZE self.size = (self.width, self.height) self.screen = pygame.display.set_mode(self.size) self.myfont = pygame.font.SysFont("monospace", self.SQUARESIZE//3) self.BackButton = None def draw_board(self,board): GRIDSIZE = len(board[0]) SQUARESIZE = self.SQUARESIZE RADIUS = self.RADIUS self.BackButton = Button(self.screen, self.width-80, 0, 80, 50, 75, 45, "Back") self.BackButton.draw_button(YELLOW) print("!!") for c in range(GRIDSIZE): for r in range(GRIDSIZE): pygame.draw.rect(self.screen, BLUE, (c*SQUARESIZE,(r+1)*SQUARESIZE, SQUARESIZE, SQUARESIZE )) if( board[r][c] == 1): color = YELLOW if( board[r][c] == -1): color = RED if( board[r][c] == 0): color = WHITE pygame.draw.circle(self.screen, color, (int(c*SQUARESIZE+SQUARESIZE/2),int((r+1)*SQUARESIZE+SQUARESIZE/2)), RADIUS) pygame.display.update() def draw_turn(self,name): pygame.draw.rect(self.screen, BLACK, (0,0,self.width,self.SQUARESIZE)) self.headline(name) self.BackButton.draw_button(YELLOW) pygame.display.update() def gameover(self): for event in pygame.event.get(): if (event.type == pygame.QUIT): sys.exit() def WAIT(self,duration): pygame.time.wait(duration) def WaitForAClick(self): while(True): for event in pygame.event.get(): if (event.type == pygame.MOUSEBUTTONDOWN): if(self.BackButton.isClicked(event)): return 1000 return 0 if (event.type == pygame.QUIT): sys.exit() def isBackButtonClicked(self): for event in pygame.event.get(): if (event.type == pygame.MOUSEBUTTONDOWN): if(self.BackButton.isClicked(event)): return True return False def headline(self,headline): pygame.draw.rect(self.screen, BLACK, (0,0,self.width,self.SQUARESIZE)) self.BackButton.draw_button(YELLOW) print(headline) label = self.myfont.render(headline, 1 , YELLOW) self.screen.blit(label, (25, 10)) pygame.display.update() def getPYGAME(self): return pygame
class AlienInvasion: """Alien Game""" def __init__(self): """"Initialize game and settings""" pygame.init() self.settings = Settings() #self.screen = pygame.display.set_mode((self.settings.screen_width,self.settings.screen_height)) self.screen = pygame.display.set_mode((0,0),pygame.FULLSCREEN) self.settings.screen_width = self.screen.get_rect().width self.settings.screen_height = self.screen.get_rect().height pygame.display.set_caption('Alien Invasion') self.stats = GameStats(self) self.sb = Scoreboard(self) self.ship = Ship(self) self.bullets = pygame.sprite.Group() self.aliens = pygame.sprite.Group() self._create_fleet() self.play_button = Button(self,"Play!!!") def run_game(self): """begin the game""" while True: self.CheckEvents() if self.stats.game_active == True: self.ship.Update() self._update_bullets() self._update_aliens() self.UpdateScreen() def _check_play_button(self, mouse_pos): """start a new game if play is clicked""" if self.play_button.rect.collidepoint(mouse_pos) and self.stats.game_active == False: self.settings.initialize_dynamic_settings() self.stats.reset_stats() self.stats.game_active = True self.sb.prep_score() self.sb.prep_level() self.sb.prep_level() self.sb.prep_ships() #clear any remaining aliens or bullets and create brand new one self.aliens.empty() self.bullets.empty() self._create_fleet() self.ship.center_ship() #hide mouse pygame.mouse.set_visible(False) def CheckEvents(self): for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: self._check_keydown_events(event) elif event.type == pygame.KEYUP: self._check_keyup_events(event) elif event.type == pygame.MOUSEBUTTONDOWN: mouse_pos = pygame.mouse.get_pos() self._check_play_button(mouse_pos) def _check_keydown_events(self, event): if event.key == pygame.K_RIGHT: # move the ship to the right self.ship.moving_right = True if event.key == pygame.K_LEFT: # move the ship to the right self.ship.moving_left = True if event.key == pygame.K_UP: # move the ship to the right self.ship.moving_up = True if event.key == pygame.K_DOWN: # move the ship to the right self.ship.moving_down = True if event.key == pygame.K_SPACE: if len(self.bullets) < self.settings.bullets_allowed: self._fire_bullet() if event.key == pygame.K_q: sys.exit() def _check_keyup_events(self, event): """key release events""" if event.key == pygame.K_RIGHT: self.ship.moving_right = False if event.key == pygame.K_LEFT: self.ship.moving_left = False if event.key == pygame.K_UP: self.ship.moving_up = False if event.key == pygame.K_DOWN: self.ship.moving_down = False def _fire_bullet(self): new_bullet = Bullet(self) self.bullets.add(new_bullet) def _update_bullets(self): self.bullets.update() # draw bullets at new positions #delete bullets that are above the screen for bullet in self.bullets.copy(): if bullet.rect.bottom <= 0: self.bullets.remove(bullet) self._check_bullet_alien_collisions() def _check_bullet_alien_collisions(self): #check for collissions with alien #all objects that have collided are deleted. for high powered bullet set the first bool to true collisions = pygame.sprite.groupcollide(self.bullets,self.aliens,True,True) if collisions: # each dictionary value contains a list of all aliens hit by 1 bullet. for aliens in collisions.values(): self.stats.score += self.settings.alien_points * len(aliens) self.sb.prep_score() self.sb.check_high_score() if not self.aliens: self.bullets.empty() self._create_fleet() self.settings.increase_speed() #increase level self.stats.level += 1 self.sb.prep_level() def _update_aliens(self): """Check if fleet is on an edge and then if necessary update all alien positions""" self._check_fleet_edges() self.aliens.update() if pygame.sprite.spritecollideany(self.ship,self.aliens): self._ship_hit() self._check_aliens_bottom() def _create_fleet(self): """create the fleet of aliens""" alien = Alien(self) alien_width,alien_height = alien.rect.size available_space_x = self.settings.screen_width - 2 * alien_width number_aliens_x = available_space_x//(2*alien_width) #determine number of rows for screen ship_height = self.ship.rect.height available_space_y = self.settings.screen_height - 3 * alien_height - ship_height number_rows = available_space_y // (2 * alien_height) #add row of aliens for row_number in range(number_rows): for alien_number in range(number_aliens_x): self._create_alien(alien_number, row_number) def _create_alien(self,alien_number,row_number): alien = Alien(self) alien_width,alien_height = alien.rect.size alien.x = alien_width + 2 * alien_width * alien_number alien.rect.x = alien.x alien.rect.y = alien.rect.height + 2 * alien.rect.height * row_number self.aliens.add(alien) def _check_fleet_edges(self): """respond appropriately if an alien has reached the edge""" for alien in self.aliens.sprites(): if alien.check_edges(): self._change_fleet_direction() break def _change_fleet_direction(self): """drop whole fleet and change direction""" for alien in self.aliens.sprites(): alien.rect.y += self.settings.fleet_drop_speed self.settings.fleet_direction *=-1 def _ship_hit(self): """respond to ship being hit by alien""" if self.stats.ships_left > 0: self.stats.ships_left -= 1 self.sb.prep_ships() #erase all aliens and bullets self.aliens.empty() self.bullets.empty() self._create_fleet() self.ship.center_ship() # chill out for a second sleep(1.5) else: self.stats.game_active = False pygame.mouse.set_visible(True) def _check_aliens_bottom(self): """look and respond if any aliens are at the bottom of the screen""" screen_rect = self.screen.get_rect() for alien in self.aliens.sprites(): if alien.rect.bottom >= screen_rect.bottom: #Same functionality as when the ship is hit self._ship_hit() def UpdateScreen(self): self.screen.fill(self.settings.bg_color) #background color to gray self.ship.DrawShip() # draw ship for bullet in self.bullets.sprites(): # draw bullets bullet.draw_bullet() self.aliens.draw(self.screen) #draw aliens self.sb.show_score() if not self.stats.game_active: self.play_button.draw_button() pygame.display.flip()
def __init__(self): super().__init__() # 이미지를 로드한다. self.boxPixmap = QPixmap('Resource/CatBox.png') self.buttonWithBoxPixmap = QPixmap('Resource/ButtonWithBox.png') self.buttonWithBoxPixmap0 = QPixmap('Resource/ButtonWithBox0.png') self.buttonPixmap = QPixmap('Resource/Button.png') self.playerPixmap = QPixmap('Resource/Player1.png') self.blankPixmap0 = QPixmap('Resource/Blank0.png') self.blankPixmap1 = QPixmap('Resource/Blank1.png') self.blankPixmap2 = QPixmap('Resource/Blank2.png') self.blankPixmap3 = QPixmap('Resource/Blank3.png') self.wallPixmap = QPixmap('Resource/Wall.png') self.backgroundPixmap = QPixmap('Resource/Background.png') # 박스 default Pixmap 설정 Button.setButtonPixmap(self.buttonPixmap) Button.setButtonWithBoxPixmap(self.buttonWithBoxPixmap) # 상태 설정 self.status = EGameStatus.EPlaying # 윈도우 제목 설정 및 화면 크기 설정 self.title = '고양이는 박스가 필요해' self.setWindowTitle(self.title) self.width = 640 self.height = 640 self.setFixedHeight(self.height) self.setFixedWidth(self.width) # 배경 출력 Object.setQWidget(self) Object.setSize(self.width) # 배경의 크기는 화면의 길이와 같음 self.background = Object(0, 0, self.backgroundPixmap) self.background.draw() Object.setSize(64) # 버튼 만들기 self.backButton = QPushButton('Back', self) resetButton = QPushButton('Reset', self) self.nextButton = QPushButton('Next', self) self.nextButton.setEnabled(False) self.backButton.setFocusPolicy(Qt.NoFocus) resetButton.setFocusPolicy(Qt.NoFocus) self.nextButton.setFocusPolicy(Qt.NoFocus) # 버튼 위치 이동 self.backButton.move(0, 610) resetButton.move(self.width / 3 * 1 + 45, 610) self.nextButton.move(self.width / 3 * 2 + 100, 610) # 버튼 크기 조절 self.backButton.setFixedHeight(30) resetButton.setFixedHeight(30) self.nextButton.setFixedHeight(30) # 함수 연결 self.backButton.clicked.connect(self.onClickBack) resetButton.clicked.connect(self.onClickReset) self.nextButton.clicked.connect(self.onClickNext) # 폰트 만들기 font = QFont('Times', 20, QFont.Bold) # text 만들기 self.stageText = QLabel('Stage: ', self) self.stageText.setFont(font) self.stageText.setStyleSheet('color: white') self.stageText.setFixedWidth(200) self.goalText = QLabel('Goal:', self) self.goalText.setFont(font) self.goalText.setStyleSheet('color: white') self.goalText.setFixedWidth(200) self.goalText.move(240, 0) self.stepText = QLabel('Step:', self) self.stepText.setFont(font) self.stepText.setStyleSheet('color: white') self.stepText.setFixedWidth(200) self.stepText.move(475, 0) # 피클을 통해 로드해야 하는 mapData self.mapData = None # 데이터 로딩 self.loadData() # 현재 화면의 오브젝트들이 들어있는 리스트(blank를 저장하기 위해 사용) self.blankList = [] # 게임 데이터로부터 복사받을 리스트. 배열 내의 위치는 실제 위치와 같음 self.currentStage = [] self.step = 0 # 움직인 횟수 self.currentLevel = 0 # 현재 스테이지 self.maxStage = len(self.mapData) self.goal = 0 self.show() # 게임 데이터를 복사받음(깊은 복사로 해야되는데 일단 앝을 복사로 함) self.loadStage(self.currentLevel)
def __init__(self, maps): settings_values = load_settings() self.result = -1 # переменная для отслеживания состояния экрана self.maps = maps # создание кнопок self.exit_btn = Button(-30, 615, 222, 92, '', exit_button_image, self.back, glow=glow_left) self.chr_btn = Button(-30, -30, 223, 92, '', chr_button_image, self.chr_menu, glow=glow_left) self.play_btn = Button(908, 650, 222, 92, '', play_button_image, self.start_game, glow=glow_right) self.settings_btn = Button(908, 0, 223, 92, '', settings_button_image, self.open_settings, glow=glow_right) self.active_map = 0 self.maps[0][0] -= 30 self.menu_background = self.maps[self.active_map][2].background # загрузка аудиофайла map = f'maps/{self.maps[0][2].dir}/{self.maps[0][2].general["AudioFilename"]}' pygame.mixer.music.load(map) pygame.mixer.music.set_volume(0.1 * int(settings_values['music_volume'])) pygame.mixer.music.play(-1) # загрузка рекордов для всех карт self.records = {} con = sqlite3.connect('records.db') cur = con.cursor() result = cur.execute("SELECT * FROM Records") for elem in result: # преобразование элементов словаря с рекордами # из текста в изображения с текстом elem = list(elem) elem[6] = 'Сыграно ' + elem[6] + ', ' + elem[7] elem[3] = 'Score: ' + str(elem[3]) elem[5] = 'Combo: ' + str(elem[5]) + 'x' elem[4] = str('%.2f' % elem[4]) + '%' for i in range(3, 8): elem[i] = drawing_text(str(elem[i]), (-100, -100), font_color=(255, 255, 255), font_size=15) if elem[1] in self.records: self.records[elem[1]].append(elem) else: self.records[elem[1]] = [elem] for i in self.records: self.records[i] = list(reversed(self.records[i])) self.cache = {} # кеш для быстрой отрисовки текста
def runTwoCardFlipGame(surface, board): pygame.display.set_caption("두카드 뒤집기 게임") pygame.display.set_icon(pygame.image.load("images/twoCardFlipImages/back.png")) pygame.mixer.init() pygame.mixer.music.load("musics/twocardgamemusic.mp3") pygame.mixer.music.play(-5, 0.0) pygame.mixer.music.set_volume(0.01) mouseX = 0 mouseY = 0 # 마우스 이벤트 발생 좌표 board.setRandomBoard() first_selection = None # 첫 클릭 좌표 저장 surface.fill(WHITE) board.startGameAnimation() while True: # game loop mouseClicked = False surface.fill(WHITE) # draw window board.drawBoard() again_button = Button(surface, "다시시작", 20, BLACK, (board.surface_width - 140, board.surface_height - 200), (120, 50), (0, 255, 0), (0, 255, 200), 5) again_button.onClickListener(initTwoCardFlipGame) back_button = Button(surface, "뒤로가기", 20, BLACK, (board.surface_width - 140, board.surface_height - 130), (120, 50), (0, 0, 255), (0, 200, 255), 5) back_button.onClickListener(selectGame) quit_button = Button(surface, "게임종료", 20, BLACK, (board.surface_width - 140, board.surface_height - 60), (120, 50), (255, 0, 0), (255, 200, 0), 5) quit_button.onClickListener(sys.exit) for event in pygame.event.get(): # 이벤트 처리 루프 if event.type == QUIT or (event.type == KEYUP and event.key == K_ESCAPE): pygame.quit() sys.exit() elif event.type == MOUSEMOTION: mouseX, mouseY = event.pos elif event.type == MOUSEBUTTONUP: mouseX, mouseY = event.pos mouseClicked = True boxX, boxY = board.getMousePositionOnBoard(mouseX, mouseY) if boxX is not None and boxY is not None: # 마우스가 현재 박스 위에 있다. if not board.revealed_cards[boxX][boxY]: # 닫힌 상자라면 하이라이트만 board.drawHighLightCard(boxX, boxY) if not board.revealed_cards[boxX][boxY] and mouseClicked: board.revealCardsAnimation([(boxX, boxY)]) board.revealed_cards[boxX][boxY] = True # 닫힌 상자 + 클릭 -> 박스 열기 if first_selection is None: # 1번 박스 > 좌표 기록 first_selection = (boxX, boxY) else: # 1번 박스 아님 > 2번 박스 > 짝 검사 icon1shape, icon1color = board.getCardAndNum(first_selection[0], first_selection[1]) icon2shape, icon2color = board.getCardAndNum(boxX, boxY) if icon1shape is not icon2shape or icon1color is not icon2color: # 서로 다름이면 둘 다 닫기 pygame.time.wait(1000) # 1초 board.coverCardsAnimation([(first_selection[0], first_selection[1]), (boxX, boxY)]) board.revealed_cards[first_selection[0]][first_selection[1]] = False board.revealed_cards[boxX][boxY] = False # 다 오픈되었으면 elif board.hasWon(): board.gameWonAnimation() pygame.time.wait(1000) first_selection = None # 화면을 다시 그린 다음 시간 지연을 기다린다... pygame.display.update()
pygame.init() width = 800 height = 900 dimension = 5 win = pygame.display.set_mode((width, height)) pygame.display.set_caption("Client") map = Map().map font = pygame.font.SysFont("monospace", 20) buttonColor = pygame.Color("grey") buttonStartX = 25 buttonStartY = 720 buttonW = 150 buttonH = 50 buttons = [Button(buttonColor, buttonStartX, buttonStartY, buttonW, buttonH), Button(buttonColor, buttonStartX + 200, buttonStartY, buttonW, buttonH), Button(buttonColor, buttonStartX + 400, buttonStartY, buttonW, buttonH), Button(buttonColor, buttonStartX + 600, buttonStartY, buttonW, buttonH), Button(buttonColor, buttonStartX, buttonStartY + 100, buttonW, buttonH), Button(buttonColor, buttonStartX + 200, buttonStartY + 100, buttonW, buttonH), Button(buttonColor, buttonStartX + 400, buttonStartY + 100, buttonW, buttonH), Button(buttonColor, buttonStartX + 600, buttonStartY + 100, buttonW, buttonH)] buttonTitles = ['', '', '', '', '', '', '', ''] menu_btns = [MenuButton("Three Players", 355, 200, (135,206,250)), MenuButton("Four Players", 355, 275, (135,206,250)), MenuButton("Five Players", 355, 350, (135,206,250)), MenuButton("Six Players", 355, 425, (135,206,250))] def redraw_window(board):
def generate_button(self): data = self.btn_data button = Button((data['x'], data['y']), (data['w'], data['h']), data['font_color'], data['text'], data['bg_color'], data['font_size']) return button
def __init__(self, parent, **kwargs): Button.__init__(self, parent) # data # flags self.processKWArguments(kwargs) parent.registerWidget(self)
def statMenu(self, screen, p): mousePos = None buttDict = {} click = False buttDict["atk"] = Button(330, 174, 40, 40, screen, color=(0, 205, 0), label=pygame.font.SysFont( "Microsoft Yahei UI Light", 40).render("+", 1, (255, 255, 255))) buttDict["hp"] = Button(330, 222, 40, 40, screen, color=(0, 205, 0), label=pygame.font.SysFont( "Microsoft Yahei UI Light", 40).render("+", 1, (255, 255, 255))) buttDict["regen"] = Button(330, 270, 40, 40, screen, color=(0, 205, 0), label=pygame.font.SysFont( "Microsoft Yahei UI Light", 40).render("+", 1, (255, 255, 255))) buttDict["speed"] = Button(330, 318, 40, 40, screen, color=(0, 205, 0), label=pygame.font.SysFont( "Microsoft Yahei UI Light", 40).render("+", 1, (255, 255, 255))) buttDict["reload"] = Button(330, 366, 40, 40, screen, color=(0, 205, 0), label=pygame.font.SysFont( "Microsoft Yahei UI Light", 40).render("+", 1, (255, 255, 255))) buttDict["reset"] = Button(140, 434, 120, 50, screen, color=(205, 0, 0), label=pygame.font.SysFont( "Microsoft Yahei UI Light", 40).render("Reset", 1, (255, 255, 255))) buttDict["back"] = Button(30, 550, 200, 70, screen, color=(180, 50, 0), label=pygame.font.SysFont( "Microsoft Yahei UI Light", 45).render("Back", 1, (255, 255, 255))) itemDict = {} itemDict["vampeggs"] = Item(410, 70, 180, 200, screen, p.items["vampeggs"], 50, label=pygame.font.SysFont( "Microsoft Yahei UI Light", 40).render("VampEggs", 1, (255, 255, 255)), description="Heal for 25% of egg damage", img="vampeggicon.png") itemDict["eggpen"] = Item(600, 70, 180, 200, screen, p.items["eggpen"], 50, label=pygame.font.SysFont( "Microsoft Yahei UI Light", 40).render("EggPen", 1, (255, 255, 255)), description="Eggs pierce through enemies", img="eggpenicon.png") itemDict["doubegg"] = Item(790, 70, 180, 200, screen, p.items["doubegg"], 100, label=pygame.font.SysFont( "Microsoft Yahei UI Light", 40).render("DoubEgg", 1, (255, 255, 255)), description="Shoot another egg out yo butt", img="doubeggicon.png") itemDict["eggsplit"] = Item( 980, 70, 180, 200, screen, p.items["eggsplit"], 200, label=pygame.font.SysFont("Microsoft Yahei UI Light", 40).render("EggSplit", 1, (255, 255, 255)), description="Eggs split into 4 upon collision", img="eggspliticon.png") itemDict["eggshield"] = Item( 410, 280, 180, 200, screen, p.items["eggshield"], 60, label=pygame.font.SysFont("Microsoft Yahei UI Light", 40).render("EggShield", 1, (255, 255, 255)), description="2 eggs permanently revolve the duck, dealing 3x ATK", img="eggshieldicon.png") myFont = pygame.font.SysFont("Microsoft Yahei UI Light", 70) shopLbl = myFont.render("Shop", 1, (255, 255, 255)) while True: screen.fill((100, 100, 150)) mousePos = pygame.mouse.get_pos() for event in pygame.event.get(): click = False if event.type == pygame.QUIT: sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: click = True if event.type == pygame.KEYDOWN and event.key == pygame.K_p: return myFont = pygame.font.SysFont("Microsoft Yahei UI Light", 40) pygame.draw.rect(screen, (75, 75, 200), (0, 0, 400, 100)) pygame.draw.rect(screen, (0, 0, 0), (0, 0, 400, 100), 10) skillLbl = myFont.render("Skill Points: " + str(p.pts), 1, (255, 255, 255)) screen.blit(skillLbl, (10, 10)) screen.blit( myFont.render("Gold: " + str(p.gold), 1, (255, 255, 255)), (10, 20 + skillLbl.get_height())) myFont = pygame.font.SysFont("Microsoft Yahei UI Light", 60) pygame.draw.rect(screen, (75, 75, 200), (0, 100, 400, 400)) pygame.draw.rect(screen, (0, 0, 0), (0, 100, 400, 400), 10) statsLbl = myFont.render("Stats", 1, (255, 255, 255)) screen.blit(statsLbl, (int(200 - statsLbl.get_width() / 2), 110)) myFont = pygame.font.SysFont("Microsoft Yahei UI Light", 40) screen.blit( myFont.render("Attack: " + str(p.atk) + " (+0.5)", 1, (255, 255, 255)), (10, 182)) screen.blit( myFont.render("Health: " + str(p.maxhp) + " (+2)", 1, (255, 255, 255)), (10, 230)) screen.blit( myFont.render("Regen: " + str(p.regen) + " (-0.3)", 1, (255, 255, 255)), (10, 278)) screen.blit( myFont.render("Speed: " + str(p.speed) + " (+2)", 1, (255, 255, 255)), (10, 326)) screen.blit( myFont.render("Reload: " + str(p.reload) + " (-0.05)", 1, (255, 255, 255)), (10, 374)) screen.blit(shopLbl, (800 - shopLbl.get_width() / 2, 10)) pygame.draw.rect(screen, (75, 75, 200), (400, 500, 800, 150)) pygame.draw.rect(screen, (0, 0, 0), (400, 500, 800, 150), 10) for i in buttDict: val = buttDict[i].tick(mousePos, click) if val: if i == "reset": p.pts += (p.atk - 1) / 0.5 p.atk = 1 p.pts += (p.maxhp - 10) / 2 p.hp -= p.maxhp - 10 p.maxhp = 10 p.pts += (5 - p.regen) / 0.3 p.regen = 5 p.pts += (p.speed - 9) / 2 p.speed = 9 p.pts += (1 - p.reload) / 0.05 p.reload = 1 p.pts = int(round(p.pts)) elif i == "back": return elif p.pts > 0: if i == "atk": p.atk += 0.5 if i == "hp": p.hp += 2 p.maxhp += 2 if i == "regen" and p.regen > 0.5: p.regen -= 0.3 p.regen = round(p.regen * 10) / 10 elif i == "regen": p.pts += 1 if i == "speed": p.speed += 2 if i == "reload" and p.reload > 0.1: p.reload -= 0.05 p.reload = round(p.reload * 100) / 100 elif i == "reload": p.pts += 1 p.pts -= 1 click = False for i in itemDict: val = itemDict[i].tick(mousePos, click) if val >= 1: screen.blit( myFont.render(itemDict[i].description, 1, (255, 255, 255)), (410, 510)) if val == 2 and not p.items[ i] and p.gold >= itemDict[i].price: itemDict[i].bought = True p.items[i] = True p.gold -= itemDict[i].price pygame.display.update() pygame.time.Clock().tick(30)
class Risk(): def __init__(self, screen, player1_name, player2_name): self.screen = screen self.surface = pygame.Surface((WIDTH, HEIGHT)).convert() self.img = pygame.transform.scale( pygame.image.load('assets/2000px-Risk_board.svg.png'), (1000, 692)) self.locations = {} # Locations below are in the format: # location_id, center_x, center_y, name, neighbors # North America self.locations[1] = Location(self, 1, 80, 112, "Alaska", [2, 3, 32]) self.locations[2] = Location(self, 2, 168, 112, "NW Territory", [1, 3, 4, 6]) self.locations[3] = Location(self, 3, 158, 161, "Alberta", [1, 2, 4, 7]) self.locations[4] = Location(self, 4, 222, 160, "Ontario", [2, 3, 5, 6, 7, 8]) self.locations[5] = Location(self, 5, 294, 165, "Quebec", [4, 6, 8]) self.locations[6] = Location(self, 6, 345, 71, "Greenland", [2, 4, 5, 15]) self.locations[7] = Location(self, 7, 161, 233, "Western US", [3, 4, 8, 9]) self.locations[8] = Location(self, 8, 237, 247, "Eastern US", [4, 5, 7, 9]) self.locations[9] = Location(self, 9, 170, 321, "Central America", [7, 8, 10]) # South America self.locations[10] = Location(self, 10, 237, 378, "Venezuela", [9, 11, 12]) self.locations[11] = Location(self, 11, 227, 450, "Peru", [10, 12, 13]) self.locations[12] = Location(self, 12, 315, 437, "Brazil", [10, 11, 13, 25]) self.locations[13] = Location(self, 13, 260, 554, "Argentina", [11, 12]) # Europe self.locations[14] = Location(self, 14, 405, 213, "Great Britain", [15, 16, 17, 20]) self.locations[15] = Location(self, 15, 433, 143, "Iceland", [6, 14, 17]) self.locations[16] = Location(self, 16, 499, 230, "Northern Europe", [14, 17, 18, 19, 20]) self.locations[17] = Location(self, 17, 504, 139, "Scandinavia", [14, 15, 16, 19]) self.locations[18] = Location(self, 18, 512, 290, "Southern Europe", [16, 19, 20, 23, 25, 33]) self.locations[19] = Location(self, 19, 584, 195, "Ukraine", [16, 17, 18, 27, 33, 37]) self.locations[20] = Location(self, 20, 429, 319, "Western Europe", [14, 16, 18, 25]) # Africa self.locations[21] = Location(self, 21, 542, 502, "Congo", [22, 25, 26]) self.locations[22] = Location(self, 22, 585, 451, "East Africa", [21, 23, 24, 25, 26, 33]) self.locations[23] = Location(self, 23, 542, 389, "Egypt", [18, 22, 25, 33]) self.locations[24] = Location(self, 24, 639, 593, "Madagascar", [22, 26]) self.locations[25] = Location(self, 25, 464, 424, "North Africa", [12, 18, 20, 21, 22, 23]) self.locations[26] = Location(self, 26, 546, 590, "South Africa", [21, 22, 24]) # Asia self.locations[27] = Location(self, 27, 673, 257, "Afghanistan", [19, 28, 29, 33, 37]) self.locations[28] = Location(self, 28, 782, 300, "China", [27, 29, 34, 35, 36, 37]) self.locations[29] = Location(self, 29, 724, 350, "India", [27, 28, 33, 35]) self.locations[30] = Location(self, 30, 801, 180, "Irkutsk", [32, 34, 36, 38]) self.locations[31] = Location(self, 31, 916, 245, "Japan", [32, 34]) self.locations[32] = Location(self, 32, 892, 104, "Kamchatka", [1, 30, 31, 34, 38]) self.locations[33] = Location(self, 33, 611, 347, "Middle East", [18, 19, 22, 23, 27, 29]) self.locations[34] = Location(self, 34, 814, 240, "Mongolia", [28, 30, 31, 32, 36]) self.locations[35] = Location(self, 35, 804, 378, "Siam", [28, 29, 41]) self.locations[36] = Location(self, 36, 735, 119, "Siberia", [27, 28, 30, 34, 37, 38]) self.locations[37] = Location(self, 37, 685, 165, "Ural", [19, 27, 28, 36]) self.locations[38] = Location(self, 38, 815, 95, "Yakutsk", [30, 32, 36]) # Australia self.locations[39] = Location(self, 39, 922, 544, "Eastern Australia", [40, 42]) self.locations[40] = Location(self, 40, 855, 589, "Western Australia", [39, 41, 42]) self.locations[41] = Location(self, 41, 820, 485, "Indonesia", [35, 40, 42]) self.locations[42] = Location(self, 42, 910, 462, "New Guinea", [39, 40, 41]) # Set up players, 2 for now self.players = {} self.players[1] = Risk_Player(self, 1, player1_name, LIGHTBLUE, 150, 771) self.players[2] = Risk_Player(self, 2, player2_name, RED, 850, 771) self.current_player = 1 self.game_phase = "Pick Starting Countries" self.attacker = None self.defender = None # Text that can be used in the bottom-middle display self.situational_text = None # Create the game state display self.game_state_display = Risk_Game_State_Display(self) # Blank RPS game that will get created on the fly during battle self.rps = None # End turn and undo buttons self.end_turn_button = Button(self, "End Turn", 100, 50, WHITE, str("End Turn"), "tahoma", BLACK, 50, 667) self.undo_button = Button(self, "Undo", 100, 50, WHITE, str("Undo"), "tahoma", BLACK, 200, 667) # Placable armies that gets populated for each new turn self.placable_armies = 0 def process_keydown(self, key): # When a key is pressed during Risk if key == pygame.K_r: # Check the game phase , if during setup then randomize things if self.game_phase == "Pick Starting Countries" and self.players[ 1].total_locations == 0: # Rancomly pick starting countries for each player # First, make a shuffled list of locations locations_list = [] for key, value in self.locations.items(): locations_list.append(value) random.shuffle(locations_list) # Iterate the shuffled list and pick the next one for the current player for location in locations_list: self.locations[ location.location_id].bg_color = self.players[ self.current_player].color self.players[self.current_player].total_locations += 1 self.players[ self.current_player].controlled_locations.append( location.location_id) self.locations[ location.location_id].owner = self.current_player self.locations[location.location_id].armies += 1 self.players[self.current_player].total_armies += 1 self.next_player() self.situational_text = "Starting locations randomized" self.next_phase() elif self.game_phase == "Allocate All Armies": # Randomly allocate the rest of the armies for each player while (self.players[2].total_armies < 50): # Pick a random location from this player's list random_location = random.choice( self.players[self.current_player].controlled_locations) # Increment that location and the player's total armies self.locations[random_location].armies += 1 self.players[self.current_player].total_armies += 1 self.next_player() self.situational_text = "Armies randomly allocated" self.next_phase() elif self.rps: self.rps.process_keydown(key) def next_player(self): if self.current_player == 1: self.current_player = 2 else: self.current_player = 1 def check_if_game_over(self): if self.players[1].total_locations == 0: return True elif self.players[2].total_locations == 0: return True else: return False def update_armies_count(self): for key, player in self.players.items(): armies = 0 for location in player.controlled_locations: armies += self.locations[location].armies player.total_armies = armies def next_phase(self): if self.game_phase == "Pick Starting Countries": self.game_phase = "Allocate All Armies" elif self.game_phase == "Allocate All Armies": self.game_phase = "Choose Attacker" elif self.game_phase == "Choose Attacker": self.game_phase = "Choose Defender" elif self.game_phase == "Choose Defender": self.game_phase = "RPS" elif self.game_phase == "RPS" and self.rps == None: if self.check_if_game_over(): self.game_phase = "Victory!" else: self.update_armies_count() self.game_phase = "Choose Attacker" elif self.game_phase == "Place New Armies": self.game_phase = "Choose Attacker" # Always clean out the situational text when changing phases? # self.situational_text = None def new_turn(self): self.next_player() self.placable_armies = 5 self.game_phase = "Place New Armies" self.situational_text = None def process_mouseclick(self, mouse_pos): # mouse was clicked, do something # Logic during different phases if self.game_phase == "Pick Starting Countries": for key, location in self.locations.items(): if location.is_hovered(mouse_pos[0], mouse_pos[1]): if location.owner == None: location.bg_color = self.players[ self.current_player].color self.players[self.current_player].total_locations += 1 self.players[ self.current_player].controlled_locations.append( location.location_id) location.owner = self.current_player location.armies += 1 self.players[self.current_player].total_armies += 1 self.next_player() if len(self.players[1].controlled_locations) + len( self.players[2].controlled_locations) == 42: # All countries taken, start next phase self.next_phase() elif self.game_phase == "Allocate All Armies": for key, location in self.locations.items(): if location.is_hovered(mouse_pos[0], mouse_pos[1]): if location.owner == self.current_player: location.armies += 1 self.players[self.current_player].total_armies += 1 self.next_player() else: self.situational_text = "Not your territory!" if self.players[2].total_armies == 50: self.next_phase() elif self.game_phase == "Choose Attacker": for key, location in self.locations.items(): if location.is_hovered(mouse_pos[0], mouse_pos[1]): if location.owner == self.current_player and location.armies > 1: self.attacker = location location.is_chosen = True self.next_phase() elif location.owner != self.current_player: self.situational_text = "Not your territory!" elif location.armies <= 1: self.situational_text = "Not enough armies to attack!" if self.end_turn_button.is_hovered(mouse_pos[0], mouse_pos[1]): self.new_turn() elif self.game_phase == "Choose Defender": self.situational_text = None for key, location in self.locations.items(): if location.is_hovered(mouse_pos[0], mouse_pos[1]): if location.owner != self.current_player: if location.location_id in self.attacker.neighbors: self.defender = location self.next_phase() if self.current_player == 1: self.rps = RPS(self.screen, self.attacker.name, self.attacker.armies, self.defender.name, self.defender.armies) else: self.rps = RPS(self.screen, self.defender.name, self.defender.armies, self.attacker.name, self.attacker.armies) else: self.situational_text = "Not a connected territory" else: self.situational_text = "Can't attack yourself!" if self.undo_button.is_hovered(mouse_pos[0], mouse_pos[1]): self.game_phase = "Choose Attacker" self.attacker.is_chosen = False self.attacker = None elif self.game_phase == "RPS": # Time to play RPS to see who wins pass elif self.game_phase == "Place New Armies": for key, location in self.locations.items(): if location.is_hovered(mouse_pos[0], mouse_pos[1]): if location.owner == self.current_player: location.armies += 1 self.players[self.current_player].total_armies += 1 self.placable_armies -= 1 if self.placable_armies == 0: self.next_phase() def is_rps_game_over(self): # Check if the RPS game is over if self.current_player == 1: if self.rps.player_one.lives < 2: # Player two wins as defender self.attacker.armies = self.rps.player_one.lives self.defender.armies = self.rps.player_two.lives self.rps = None self.situational_text = "P1 attack fails" elif self.rps.player_two.lives < 1: # Player one wins as attacker self.attacker.armies = 1 self.defender.armies = self.rps.player_one.lives - 1 self.defender.owner = self.current_player self.defender.bg_color = self.players[1].color self.players[1].total_locations += 1 self.players[2].total_locations -= 1 self.players[1].controlled_locations.append( self.defender.location_id) self.players[2].controlled_locations.remove( self.defender.location_id) self.rps = None self.situational_text = "P1 attack successful" else: if self.rps.player_one.lives < 1: # Player two wins as attacker self.attacker.armies = 1 self.defender.armies = self.rps.player_two.lives - 1 self.defender.owner = self.current_player self.defender.bg_color = self.players[2].color self.players[2].total_locations += 1 self.players[1].total_locations -= 1 self.players[2].controlled_locations.append( self.defender.location_id) self.players[1].controlled_locations.remove( self.defender.location_id) self.rps = None self.situational_text = "P2 attack successful" elif self.rps.player_two.lives < 2: # Player one wins as defender self.attacker.armies = self.rps.player_two.lives self.defender.armies = self.rps.player_one.lives self.rps = None self.situational_text = "P2 attack fails" if not self.rps: # RPS game finished, do some cleanup self.attacker.is_chosen = False self.attacker = None self.defender = None self.next_phase() return True else: return False def draw(self): if self.rps and not self.is_rps_game_over(): self.rps.draw() else: # Fill in background color self.surface.fill(SHADOW) # Draw risk map self.surface.blit(self.img, (0, 0)) # Draw each location square for key, location in self.locations.items(): location.draw() # Draw player stats for key, player in self.players.items(): player.draw() # Draw current game state self.game_state_display.draw() # Draw buttons mouse_pos = pygame.mouse.get_pos() self.end_turn_button.is_hovered(mouse_pos[0], mouse_pos[1]) self.end_turn_button.draw() self.undo_button.is_hovered(mouse_pos[0], mouse_pos[1]) self.undo_button.draw() self.screen.blit(self.surface, (0, 0))
def end_aesthetics(self, winning_game_side, game_drawn): if winning_game_side == 1: congrats = Button(Game.BOARD_CENTER-Game.CGRATS_CENTER_DISP[0], Game.BOARD_CENTER-Game.CGRATS_CENTER_DISP[1], Game.CGRATS_CENTER_DISP[0]*2, Game.CGRATS_CENTER_DISP[1]*2, Game.CGRATS_COLOR, Game.CGRATS_FONT, "X WINS!", self.screen) congrats.draw_button() elif winning_game_side == 2: congrats = Button(Game.BOARD_CENTER-Game.CGRATS_CENTER_DISP[0], Game.BOARD_CENTER-Game.CGRATS_CENTER_DISP[1], Game.CGRATS_CENTER_DISP[0]*2, Game.CGRATS_CENTER_DISP[1]*2, Game.CGRATS_COLOR, Game.CGRATS_FONT, "O WINS!", self.screen) congrats.draw_button() elif game_drawn: congrats = Button(Game.BOARD_CENTER-Game.CGRATS_CENTER_DISP[0], Game.BOARD_CENTER-Game.CGRATS_CENTER_DISP[1], Game.CGRATS_CENTER_DISP[0]*2, Game.CGRATS_CENTER_DISP[1]*2, Game.CGRATS_COLOR, Game.CGRATS_FONT, "DRAW!", self.screen) congrats.draw_button() pygame.display.update()
def __init__(self, screen, player1_name, player2_name): self.screen = screen self.surface = pygame.Surface((WIDTH, HEIGHT)).convert() self.img = pygame.transform.scale( pygame.image.load('assets/2000px-Risk_board.svg.png'), (1000, 692)) self.locations = {} # Locations below are in the format: # location_id, center_x, center_y, name, neighbors # North America self.locations[1] = Location(self, 1, 80, 112, "Alaska", [2, 3, 32]) self.locations[2] = Location(self, 2, 168, 112, "NW Territory", [1, 3, 4, 6]) self.locations[3] = Location(self, 3, 158, 161, "Alberta", [1, 2, 4, 7]) self.locations[4] = Location(self, 4, 222, 160, "Ontario", [2, 3, 5, 6, 7, 8]) self.locations[5] = Location(self, 5, 294, 165, "Quebec", [4, 6, 8]) self.locations[6] = Location(self, 6, 345, 71, "Greenland", [2, 4, 5, 15]) self.locations[7] = Location(self, 7, 161, 233, "Western US", [3, 4, 8, 9]) self.locations[8] = Location(self, 8, 237, 247, "Eastern US", [4, 5, 7, 9]) self.locations[9] = Location(self, 9, 170, 321, "Central America", [7, 8, 10]) # South America self.locations[10] = Location(self, 10, 237, 378, "Venezuela", [9, 11, 12]) self.locations[11] = Location(self, 11, 227, 450, "Peru", [10, 12, 13]) self.locations[12] = Location(self, 12, 315, 437, "Brazil", [10, 11, 13, 25]) self.locations[13] = Location(self, 13, 260, 554, "Argentina", [11, 12]) # Europe self.locations[14] = Location(self, 14, 405, 213, "Great Britain", [15, 16, 17, 20]) self.locations[15] = Location(self, 15, 433, 143, "Iceland", [6, 14, 17]) self.locations[16] = Location(self, 16, 499, 230, "Northern Europe", [14, 17, 18, 19, 20]) self.locations[17] = Location(self, 17, 504, 139, "Scandinavia", [14, 15, 16, 19]) self.locations[18] = Location(self, 18, 512, 290, "Southern Europe", [16, 19, 20, 23, 25, 33]) self.locations[19] = Location(self, 19, 584, 195, "Ukraine", [16, 17, 18, 27, 33, 37]) self.locations[20] = Location(self, 20, 429, 319, "Western Europe", [14, 16, 18, 25]) # Africa self.locations[21] = Location(self, 21, 542, 502, "Congo", [22, 25, 26]) self.locations[22] = Location(self, 22, 585, 451, "East Africa", [21, 23, 24, 25, 26, 33]) self.locations[23] = Location(self, 23, 542, 389, "Egypt", [18, 22, 25, 33]) self.locations[24] = Location(self, 24, 639, 593, "Madagascar", [22, 26]) self.locations[25] = Location(self, 25, 464, 424, "North Africa", [12, 18, 20, 21, 22, 23]) self.locations[26] = Location(self, 26, 546, 590, "South Africa", [21, 22, 24]) # Asia self.locations[27] = Location(self, 27, 673, 257, "Afghanistan", [19, 28, 29, 33, 37]) self.locations[28] = Location(self, 28, 782, 300, "China", [27, 29, 34, 35, 36, 37]) self.locations[29] = Location(self, 29, 724, 350, "India", [27, 28, 33, 35]) self.locations[30] = Location(self, 30, 801, 180, "Irkutsk", [32, 34, 36, 38]) self.locations[31] = Location(self, 31, 916, 245, "Japan", [32, 34]) self.locations[32] = Location(self, 32, 892, 104, "Kamchatka", [1, 30, 31, 34, 38]) self.locations[33] = Location(self, 33, 611, 347, "Middle East", [18, 19, 22, 23, 27, 29]) self.locations[34] = Location(self, 34, 814, 240, "Mongolia", [28, 30, 31, 32, 36]) self.locations[35] = Location(self, 35, 804, 378, "Siam", [28, 29, 41]) self.locations[36] = Location(self, 36, 735, 119, "Siberia", [27, 28, 30, 34, 37, 38]) self.locations[37] = Location(self, 37, 685, 165, "Ural", [19, 27, 28, 36]) self.locations[38] = Location(self, 38, 815, 95, "Yakutsk", [30, 32, 36]) # Australia self.locations[39] = Location(self, 39, 922, 544, "Eastern Australia", [40, 42]) self.locations[40] = Location(self, 40, 855, 589, "Western Australia", [39, 41, 42]) self.locations[41] = Location(self, 41, 820, 485, "Indonesia", [35, 40, 42]) self.locations[42] = Location(self, 42, 910, 462, "New Guinea", [39, 40, 41]) # Set up players, 2 for now self.players = {} self.players[1] = Risk_Player(self, 1, player1_name, LIGHTBLUE, 150, 771) self.players[2] = Risk_Player(self, 2, player2_name, RED, 850, 771) self.current_player = 1 self.game_phase = "Pick Starting Countries" self.attacker = None self.defender = None # Text that can be used in the bottom-middle display self.situational_text = None # Create the game state display self.game_state_display = Risk_Game_State_Display(self) # Blank RPS game that will get created on the fly during battle self.rps = None # End turn and undo buttons self.end_turn_button = Button(self, "End Turn", 100, 50, WHITE, str("End Turn"), "tahoma", BLACK, 50, 667) self.undo_button = Button(self, "Undo", 100, 50, WHITE, str("Undo"), "tahoma", BLACK, 200, 667) # Placable armies that gets populated for each new turn self.placable_armies = 0
from Board import Board pygame.init() screen_size = (1600, 800) screen = pygame.display.set_mode(screen_size) screen.fill(BLACK) # Set background color # Screen title pygame.display.set_caption("Colorindo Cenarios") # Create an object to help track time clock = pygame.time.Clock() # All buttons draw_button = Button(STANDARD_COLOR, 815, 5, 225, 400, "DRAW") clear_button = Button(GREY, 815, 410, 225, 400, "CLEAR") gold_button = Button(GOLD, 1095, 5, 225, 200, "GOLD") brown_button = Button(BROWN, 1330, 5, 225, 200, "BROWN") red_button = Button(RED, 1095, 210, 225, 200, "RED") green_button = Button(GREEN, 1330, 210, 225, 200, "GREEN") yellow_button = Button(YELLOW, 1095, 410, 225, 200, "YELLOW") blue_button = Button(BLUE, 1330, 410, 225, 200, "BLUE") purple_button = Button(PURPLE, 1095, 610, 225, 200, "PURPLE") pink_button = Button(PINK, 1330, 610, 225, 200, "PINK") buttons = [ draw_button, clear_button, brown_button, gold_button, green_button, red_button, yellow_button, blue_button, purple_button, pink_button ]
class ScrollingPlane(AbstractDrawable): def __init__(self, x, y, w, h, tabs=2, vec2_pos=None, size=None, parent=None): super(ScrollingPlane, self).__init__(x=x, y=y, w=w, h=h, vec2_pos=vec2_pos, size=size) self.parent = parent self.tabs = tabs self.items = [] self.clicked = None self.plateitems = [ ] # Ez egy lista ami listákat tárol majd #Listaception self.currentActivePlane = 0 self.InitBefore() self.GenerateWindow() self.InitAfter() self.selectedCommand = None self.loopend = None self.sidepanel_active = True self.base = { 'height': self.h, 'x': self.x, 'y': self.y, 'width': self.w } self.counter = 0 def __del__(self): print "Scrollong plane destruktor lefutott" def IsInside(self, position): if self.sidepanel_active: self.sidepanel.IsInside(position) for item in self.grid: if item.IsInside(position): self.clicked = item return True if self.clearCommandsButton.IsInside(position): if self.plateitems[self.currentActivePlane]: self.clicked = self.clearCommandsButton return True for item in self.plateitems[self.currentActivePlane]: if item.IsInside(position): self.clicked = item return True for item in self.items: if item.IsInside(position): self.clicked = item return True return False def DrawObject(self, screen): for elem in self.items: elem.DrawObject(screen) for elem in self.plateitems[self.currentActivePlane]: elem.DrawObject(screen) for elem in self.plateitems[self.currentActivePlane]: if isinstance(elem, Loop): elem.DrawLoopend(screen) if self.sidepanel_active: self.sidepanel.DrawObject(screen) for elem in self.grid: elem.DrawObject(screen) if self.plateitems[self.currentActivePlane]: self.clearCommandsButton.DrawObject(screen) if self.selectedCommand: self.selectedCommand.DrawObject(screen) def GenerateWindow(self): tabwidth = self.w / self.tabs tabhight = 30 for i in range(self.tabs): tab = Tab(self.x + i * tabwidth, self.y, tabwidth, tabhight, id=i, width=1, transparent=False) self.Add(tab) self.sidepanel = Rect(vec2_pos=Vector2(700, 75), size=(121, 520), width=1, transparent=False) self.clearCommandsButton = Button(771, 594, 50, 50, keycode=fa.ROUND_X, padding=4) self.clearCommandsButton.bind(self.ClearCurrentSource) self.clearCommandsButton.SetTextIconColor(Color.RED) self.PrepareSidePanelForLogo() self.mainpanel = Rect(self.x, self.y + tabhight, self.w, self.h, width=1, transparent=False) self.Add(self.mainpanel) #rect1 = Rect(self.x+10, self.y + tabhight + 20, 20, 30, width=1) #self.AddItemToCurrentPlane(rect1) def Add(self, elem): self.items.append(elem) def OnDrag(self, event): adjustment_needed = False if self.selectedCommand: self.selectedCommand.drag(event.pos) if self.selectedCommand not in self.plateitems[ self.currentActivePlane] and self.mainpanel.IsInside( (event.pos)): if isinstance(self.selectedCommand, Loop): self.selectedCommand.loopend.SetPosition( self.selectedCommand.x, self.selectedCommand.y + 55) self.AddItemToCurrentPlane(self.loopend) self.AddItemToCurrentPlane(self.selectedCommand) self.RearrangeCommands(ignore=self.selectedCommand) if self.selectedCommand in self.plateitems[ self.currentActivePlane] and not self.mainpanel.IsInside( (event.pos)): self.plateitems[self.currentActivePlane].remove( self.selectedCommand) if isinstance(self.selectedCommand, Loop): if self.selectedCommand.loopend in self.plateitems[ self.currentActivePlane]: self.plateitems[self.currentActivePlane].remove( self.selectedCommand.loopend) if isinstance(self.selectedCommand, LoopEnd): for item in self.plateitems[self.currentActivePlane]: if isinstance(item, Loop): if item.loopend == self.selectedCommand: self.plateitems[ self.currentActivePlane].remove(item) self.selectedCommand = None adjustment_needed = True break self.RearrangeCommands() self.ResizeSourceBlock() if self.selectedCommand in self.plateitems[ self.currentActivePlane]: for item in self.plateitems[self.currentActivePlane]: if self.selectedCommand is not item and item is not None: if item.y - item.h / 2 < self.selectedCommand.y: MoveListElement( self.plateitems[self.currentActivePlane], self.selectedCommand, self.plateitems[ self.currentActivePlane].index(item)) self.RearrangeCommands(ignore=self.selectedCommand) if self.mainpanel.x < event.pos[0] and event.pos[ 0] < self.mainpanel.x + self.mainpanel.w: if event.pos[1] < 20: self.MoveSourcePanel(1) if event.pos[1] > 700: self.MoveSourcePanel(-1) if adjustment_needed: while self.mainpanel.y + self.mainpanel.h < 700 and self.mainpanel.h > 700: self.MoveSourcePanel(1) def OnRelease(self, event): if self.selectedCommand: if self.mainpanel.IsInside(event.pos): self.SetCommandPosition() if not self.selectedCommand in self.plateitems[ self.currentActivePlane]: self.AddItemToCurrentPlane(self.selectedCommand) if isinstance(self.selectedCommand, Loop): self.AddItemToCurrentPlane( self.selectedCommand.loopend) else: while self.mainpanel.y + self.mainpanel.h < 700 and self.mainpanel.h > 700: self.MoveSourcePanel(1) if self.mainpanel.h < 700: self.ResetPosition() self.ResizeSourceBlock() if self.selectedCommand in self.plateitems[ self.currentActivePlane]: self.plateitems[self.currentActivePlane].remove( self.selectedCommand) for item in self.plateitems[self.currentActivePlane]: if item is None: self.plateitems[self.currentActivePlane].remove(item) del self.selectedCommand self.RearrangeCommands() self.selectedCommand = None def OnClick(self, event): if event.button in [Mouse.LMB, Mouse.RMB, Mouse.MMB]: if isinstance(self.clicked, Tab): id = self.clicked.GetId() self.currentActivePlane = id self.ResetPosition() self.RepaintTabs(id) self.ResizeSourceBlock() elif isinstance(self.clicked, Command): if event.button == Mouse.MMB or self.parent.button_down[ "a"] and event.button == Mouse.LMB: if not isinstance(self.clicked, LoopEnd): self.CreateACommandCopy() self.AddItemToCurrentPlane(self.selectedCommand) if isinstance(self.selectedCommand, Loop): self.AddItemToCurrentPlane( self.selectedCommand.loopend) self.selectedCommand = None self.RearrangeCommands() self.ResizeSourceBlock() elif event.button == Mouse.RMB or self.parent.button_down[ "s"] and event.button == Mouse.LMB: if isinstance(self.clicked, PenColor): self.clicked.ChangeColor() elif isinstance(self.clicked, PenWidth): self.clicked.Extend() elif isinstance(self.clicked, Loop): self.clicked.ChangeCycleNumber() elif event.button == Mouse.LMB and self.parent.button_down["d"]: if self.mainpanel.IsInside(event.pos): self.selectedCommand = self.clicked if isinstance(self.selectedCommand, Loop): self.loopend = self.selectedCommand.loopend self.plateitems[self.currentActivePlane].remove( self.selectedCommand) if self.loopend: self.plateitems[self.currentActivePlane].remove( self.loopend) self.selectedCommand = None self.loopend = None self.RearrangeCommands() self.ResizeSourceBlock() while self.mainpanel.y + self.mainpanel.h < 700 and self.mainpanel.h > 700: self.MoveSourcePanel(1) if self.mainpanel.h < 700: self.ResetPosition() self.ResizeSourceBlock() elif event.button == Mouse.LMB: if not self.mainpanel.IsInside(event.pos): if not isinstance(self.clicked, LoopEnd): self.CreateACommandCopy() else: self.selectedCommand = self.clicked if isinstance(self.selectedCommand, Loop): self.loopend = self.selectedCommand.loopend self.selectedCommand.setDelta(event.pos) elif isinstance(self.clicked, Button): self.clicked.OnClick() else: print "Clicked element: ", self.clicked elif event.button in [Mouse.SCROLLDOWN, Mouse.SCROLLUP]: if self.mainpanel.IsInside(event.pos): if self.mainpanel.h > 600: if event.button == Mouse.SCROLLDOWN: self.MoveSourcePanel(-1) else: self.MoveSourcePanel(1) def MoveSourcePanel(self, direction=1, reset=True): if self.items[0].y >= 20 and direction > 0: return if self.mainpanel.y + self.mainpanel.h <= 700 and direction < 0: return for item in self.items: if item is self.sidepanel: continue position_y = item.y + 20 * direction item.SetPosition(item.x, position_y) if isinstance(item, Tab): item.UpdatePoints() self.RearrangeCommands(needreset=reset) def ResetPosition(self): for item in self.items: if item is self.sidepanel: continue item.ResetPosition() self.RearrangeCommands() def SetCommandPosition(self): if not self.selectedCommand in self.plateitems[ self.currentActivePlane]: self.selectedCommand.SetPosition( self.mainpanel.x + self.mainpanel.w / 2 - 25, self.mainpanel.y + 5 + len(self.plateitems[self.currentActivePlane]) * 55) else: self.selectedCommand.SetPosition( self.mainpanel.x + self.mainpanel.w / 2 - 25, self.mainpanel.y + 5 + self.plateitems[self.currentActivePlane].index( self.selectedCommand) * 55) def RearrangeCommands(self, ignore=None, needreset=True): if needreset: self.parent.NeedCompile() self.ResetCompileInfos() self.parent.reset = True for item in self.plateitems[self.currentActivePlane]: if item: if item is not ignore: item.SetPosition( self.mainpanel.x + self.mainpanel.w / 2 - 25, self.mainpanel.y + 5 + self.plateitems[self.currentActivePlane].index(item) * 55) #Calculate inner loop count for item in self.plateitems[self.currentActivePlane]: if isinstance(item, Loop): item.ark_level = 0 active_que = [] for i in range(len(self.plateitems[self.currentActivePlane])): item = self.plateitems[self.currentActivePlane][i] if isinstance(item, Loop): start = self.plateitems[self.currentActivePlane].index(item) end = self.plateitems[self.currentActivePlane].index( item.loopend) if start < end: active_que.append((start, end, item)) else: active_que.append((end, start, item)) for item in active_que: for elem in active_que: if item == elem: continue if item[0] < elem[0] and item[1] > elem[1]: item[2].ark_level += 1 def AddItemToCurrentPlane(self, item, plane=None): if plane: self.plateitems[plane].append(item) else: self.plateitems[self.currentActivePlane].append(item) def ResizeSourceBlock(self): self.mainpanel.h = max([ len(self.plateitems[self.currentActivePlane]) * 55 + 5, self.base['height'] ]) def InitBefore(self): for i in range(self.tabs): self.plateitems.append([]) self.runpointer = RunPointer(0, 0, 40, 40) def RepaintTabs(self, id): for item in self.items: if isinstance(item, Tab): if id == item.GetId(): item.selected = True else: item.selected = False def InitAfter(self): self.RepaintTabs(0) def PrepareSidePanelForLogo(self): self.grid = [] # Sidepanel elemei command = logo.Forward(vec2_pos=Vector2(0, 0), size=(50, 50)) self.grid.append(command) command = logo.Backward(vec2_pos=Vector2(0, 0), size=(50, 50)) self.grid.append(command) command = logo.Forward(vec2_pos=Vector2(0, 0), size=(50, 50), mul=2) self.grid.append(command) command = logo.Backward(vec2_pos=Vector2(0, 0), size=(50, 50), mul=2) self.grid.append(command) command = logo.Left(vec2_pos=Vector2(0, 0), size=(50, 50)) self.grid.append(command) command = logo.Right(vec2_pos=Vector2(0, 0), size=(50, 50)) self.grid.append(command) command = logo.Left(vec2_pos=Vector2(0, 0), size=(50, 50), mul=6) self.grid.append(command) command = logo.Right(vec2_pos=Vector2(0, 0), size=(50, 50), mul=6) self.grid.append(command) command = logo.Home(vec2_pos=Vector2(0, 0), size=(50, 50)) self.grid.append(command) command = logo.FloodFill(vec2_pos=Vector2(0, 0), size=(50, 50)) self.grid.append(command) command = logo.PenWidth(vec2_pos=Vector2(0, 0), size=(50, 50)) self.grid.append(command) command = logo.PenColor(vec2_pos=Vector2(0, 0), size=(50, 50)) self.grid.append(command) command = logo.PenDown(vec2_pos=Vector2(0, 0), size=(50, 50)) self.grid.append(command) command = logo.PenUp(vec2_pos=Vector2(0, 0), size=(50, 50)) self.grid.append(command) command = logo.ShowTurtle(vec2_pos=Vector2(0, 0), size=(50, 50)) self.grid.append(command) command = logo.HideTurtle(vec2_pos=Vector2(0, 0), size=(50, 50)) self.grid.append(command) ''' command = logo.Reset(vec2_pos=Vector2(0, 0), size=(50, 50)) self.grid.append(command) command = logo.Clear(vec2_pos=Vector2(0, 0), size=(50, 50)) self.grid.append(command) ''' command = logo.Loop(vec2_pos=Vector2(0, 0), size=(105, 50)) self.grid.append(command) self.DrawGrid() #self.items.extend(self.grid) def DrawGrid(self): from math import ceil base_x = 708 base_y = 88 delta_x = delta_y = 55 for i in range(int(ceil(len(self.grid) / 2.))): for j in range(2): counter = i * 2 + j if counter == len(self.grid): return self.grid[counter].SetPosition(base_x + delta_x * j, base_y + delta_y * i) def Play(self, counter): i = self.plateitems[self.currentActivePlane][counter] self.MoveSourceToShowPointer(i) self.runpointer.SetPosition(i.x + 25 - 70, i.y + 25) if isinstance(i, Forward): self.parent.parent.logoCore.forward(distance=i.mul * 20) elif isinstance(i, Backward): self.parent.parent.logoCore.backward(distance=i.mul * 20) elif isinstance(i, Left): self.parent.parent.logoCore.left(angle=15 * i.mul) elif isinstance(i, Right): self.parent.parent.logoCore.right(angle=15 * i.mul) elif isinstance(i, PenDown): self.parent.parent.logoCore.pendown() elif isinstance(i, PenUp): self.parent.parent.logoCore.penup() elif isinstance(i, PenWidth): self.parent.parent.logoCore.width((i.pen_width + 1) * 2 + 1) elif isinstance(i, PenColor): self.parent.parent.logoCore.color(i.pen_color) elif isinstance(i, Home): self.parent.parent.logoCore.home() elif isinstance(i, FloodFill): self.parent.parent.logoCore.fill() elif isinstance(i, ShowTurtle): self.parent.parent.logoCore.showturtle() elif isinstance(i, HideTurtle): self.parent.parent.logoCore.hideturtle() elif isinstance(i, Reset): self.parent.parent.logoCore.reset() elif isinstance(i, Clear): self.parent.parent.logoCore.clear() elif isinstance(i, Loop): i.running = True if i.compile_information["pre_test"]: if i.remaining_cycle == 0: counter = i.compile_information["loopend_index"] i.ResetCycleCounter() else: i.CountDown() else: if i.remaining_cycle == 0: i.ResetCycleCounter() else: counter = i.compile_information["loopend_index"] i.CountDown() elif isinstance(i, LoopEnd): if i.compile_information["pre_test"]: counter = i.compile_information["loopbase_index"] - 1 counter += 1 return counter def HasNext(self, counter): return counter < len(self.plateitems[self.currentActivePlane]) def EnableSidepanel(self, state): self.sidepanel_active = state def FindLoopBase(self, loopend): for elem in self.plateitems[self.currentActivePlane]: if isinstance(elem, Loop): if elem.loopend == loopend: return elem def FindLoopEnd(self, loopbase): for elem in self.plateitems[self.currentActivePlane]: if isinstance(elem, LoopEnd): if loopbase.loopend == elem: return elem def CompileLoops(self): for elem in self.plateitems[self.currentActivePlane]: if isinstance(elem, Loop): if not elem.compile_information["compiled"]: loopend = self.FindLoopEnd(elem) loopend_index = self.plateitems[ self.currentActivePlane].index(loopend) loopstart_index = self.plateitems[ self.currentActivePlane].index(elem) pre_test = loopend_index > loopstart_index elem.SetCompileInfo(pre_test=pre_test, loopend_index=loopend_index) loopend.SetCompileInfo(pre_test, loopstart_index) if isinstance(elem, LoopEnd): if not elem.compile_information["compiled"]: loop_base = self.FindLoopBase(elem) loopstart_index = self.plateitems[ self.currentActivePlane].index(loop_base) loopend_index = self.plateitems[ self.currentActivePlane].index(elem) pre_test = loopend_index > loopstart_index elem.SetCompileInfo(pre_test, loopstart_index) loop_base.SetCompileInfo(pre_test, loopend_index) def ResetCompileInfos(self): for elem in self.plateitems[self.currentActivePlane]: if isinstance(elem, Loop) or isinstance(elem, LoopEnd): elem.ResetCompileInfo() def StopRunning(self): for elem in self.plateitems[self.currentActivePlane]: if isinstance(elem, Loop): elem.running = False elem.ResetCycleCounter() elif isinstance(elem, LoopEnd): elem.running = False def DrawRunPointer(self, screen): self.runpointer.DrawObject(screen) def MoveSourceToShowPointer(self, i): flag = False t = False while i.y + i.h > 700 and not t: flag = True self.MoveSourcePanel(-1, False) t = flag while i.y < 20 and not t: self.MoveSourcePanel(1, False) def ClearCurrentSource(self): self.plateitems[self.currentActivePlane] = [] self.ResetPosition() self.ResizeSourceBlock() def CreateACommandCopy(self): self.clicked.UnloadIcon() self.selectedCommand = copy.deepcopy(self.clicked) self.clicked.LoadSprite() # DeepCopy Eseten muszaj ujra betolteni a kepet!!! self.selectedCommand.LoadSprite() if isinstance(self.selectedCommand, Loop): self.selectedCommand.RollColor() self.loopend = LoopEnd(vec2_pos=Vector2( self.selectedCommand.x, self.selectedCommand.y + 55), size=(50, 50)) self.loopend.SetLoopStart(self.selectedCommand) self.selectedCommand.SetLoopend(self.loopend) def SetCurrentActiveCommandList(self, list): self.plateitems[self.currentActivePlane] = list def GetCurrentActiveCommandList(self): return self.plateitems[self.currentActivePlane] def GetCommandLists(self): return self.plateitems def SetCommandLists(self, list_of_lists): self.plateitems = list_of_lists
class SelectMenu: def __init__(self, maps): settings_values = load_settings() self.result = -1 # переменная для отслеживания состояния экрана self.maps = maps # создание кнопок self.exit_btn = Button(-30, 615, 222, 92, '', exit_button_image, self.back, glow=glow_left) self.chr_btn = Button(-30, -30, 223, 92, '', chr_button_image, self.chr_menu, glow=glow_left) self.play_btn = Button(908, 650, 222, 92, '', play_button_image, self.start_game, glow=glow_right) self.settings_btn = Button(908, 0, 223, 92, '', settings_button_image, self.open_settings, glow=glow_right) self.active_map = 0 self.maps[0][0] -= 30 self.menu_background = self.maps[self.active_map][2].background # загрузка аудиофайла map = f'maps/{self.maps[0][2].dir}/{self.maps[0][2].general["AudioFilename"]}' pygame.mixer.music.load(map) pygame.mixer.music.set_volume(0.1 * int(settings_values['music_volume'])) pygame.mixer.music.play(-1) # загрузка рекордов для всех карт self.records = {} con = sqlite3.connect('records.db') cur = con.cursor() result = cur.execute("SELECT * FROM Records") for elem in result: # преобразование элементов словаря с рекордами # из текста в изображения с текстом elem = list(elem) elem[6] = 'Сыграно ' + elem[6] + ', ' + elem[7] elem[3] = 'Score: ' + str(elem[3]) elem[5] = 'Combo: ' + str(elem[5]) + 'x' elem[4] = str('%.2f' % elem[4]) + '%' for i in range(3, 8): elem[i] = drawing_text(str(elem[i]), (-100, -100), font_color=(255, 255, 255), font_size=15) if elem[1] in self.records: self.records[elem[1]].append(elem) else: self.records[elem[1]] = [elem] for i in self.records: self.records[i] = list(reversed(self.records[i])) self.cache = {} # кеш для быстрой отрисовки текста def back(self): self.result = 1 def chr_menu(self): self.result = 2 def start_game(self): self.result = 3 def open_settings(self): self.result = 4 def get_result(self): return self.result def get_map(self): return self.maps[self.active_map] def render(self): mouse = pygame.mouse.get_pos() click = pygame.mouse.get_pressed() display.blit(self.menu_background, (0, 0)) display.blit(back_mask, (0, 0)) for i, elem in enumerate(self.maps): x, y, map = elem if 1020 >= y >= -60: # отрисовка карты на экране if 500 <= mouse[0] and y <= mouse[1] <= y + 80 and mouse[ 1] <= 720 - 96: # отрисовка, если на карту наведен курсор # сдвиг прямоугольника карты влево self.maps[i][0] -= shift_v / fps self.maps[i][0] = min(self.maps[i][0], 500) self.maps[i][0] = max(470, self.maps[i][0]) display.blit(song_rect_active, (x, y)) if click[0]: # если курсор нажали # смена активной карты self.maps[self.active_map][0] += 30 self.active_map = i map = self.maps[self.active_map][2] self.menu_background = map.background self.maps[i][0] -= 30 self.maps[i][0] = min(self.maps[i][0], 500) self.maps[i][0] = max(470, self.maps[i][0]) pygame.mixer.music.load( f'maps/{map.dir}/{map.general["AudioFilename"]}') pygame.mixer.music.set_volume( 0.1 * int(settings_values['music_volume'])) pygame.mixer.music.play(-1) else: # отрисовка карты если курсор на нее не наведен if i != self.active_map: # сдвиг карты влево self.maps[i][0] += shift_v / fps self.maps[i][0] = min(self.maps[i][0], 500) self.maps[i][0] = max(470, self.maps[i][0]) display.blit(song_rect, (x, y)) song_background = map.small_background display.blit(song_background, (x, y)) title, artist, creator, version = map.title, map.artist, map.creator, map.version # отрисовка текста об карте с сохранением изображений текста if title in self.cache: display.blit(self.cache[title], (x + 130, y + 10)) else: self.cache[title] = drawing_text(title, (x + 130, y + 10), font_color=pygame.Color( 255, 255, 255), font_size=20) if artist in self.cache: display.blit(self.cache[artist], (x + 130, y + 32)) else: self.cache[artist] = drawing_text(artist, (x + 130, y + 32), font_color=pygame.Color( 200, 200, 200), font_size=15, italic=True) if version in self.cache: display.blit(self.cache[version], (x + 130, y + 50)) else: self.cache[version] = drawing_text(version, (x + 130, y + 50), font_color=pygame.Color( 255, 255, 255), font_size=23) # отрисовка кнопок, полосок меню display.blit(menu_back_plus, (0, 620)) display.blit(menu_plus, (0, 0)) self.play_btn.draw(0, 0) self.exit_btn.draw(0, 0) self.play_btn.draw(0, 0) self.chr_btn.draw(0, 0) self.settings_btn.draw(0, 0) # удаление из словаря с рекордами рекорда, если для какой-то карты их больше 6 if int(self.maps[self.active_map][2].map_id) in self.records: while len(self.records[int( self.maps[self.active_map][2].map_id)]) > 6: self.records[int(self.maps[self.active_map][2].map_id)].pop() records = self.records[int(self.maps[self.active_map][2].map_id)] else: records = [] for y, elem in enumerate(records): # отрисовка рекорда elem_id, map_id, mapset_id, score, accuracy, combo, date, time = elem y *= 90 y += 100 display.blit(records_rect, (-200, y)) display.blit(date, (10, y + 10)) display.blit(score, (10, y + 30)) display.blit(accuracy, (300, y + 60)) display.blit(combo, (10, y + 50))
Wall([427, 554], [574, 574]), Wall([554, 427], [574, 574]), Wall([554, 227], [574, 373]), Wall([427, 227], [574, 246]), Wall([427, 502], [525, 524]), Wall([502, 427], [525, 524]), Wall([427, 275], [525, 298]), Wall([502, 275], [525, 373]), Wall([276, 275], [372, 298]), Wall([276, 275], [298, 373]), Wall([276, 427], [298, 524]), Wall([276, 502], [373, 524]) ] startButton = Button([width / 2, height - 550], "Resources/Objects/startButton.png", "Resources/Objects/startButtonClicked.png") while True: while not run and not options: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_RETURN: run = True if event.type == pygame.MOUSEBUTTONDOWN: startButton.click(event.pos) if event.type == pygame.MOUSEBUTTONUP: if startButton.release(event.pos): run = True bgColor = r, g, b