def gameover_screen(self): exitLoop = False while not exitLoop: for event in pygame.event.get(): if event.type == pygame.QUIT: exitLoop = True self.done = True if event.type == pygame.MOUSEBUTTONDOWN: for i in range(0, len(self.platform.gameover_button_list), 1): if self.platform.gameover_button_list[i].is_mouse_over(mouse.get_pos()): if i == constants.GAMEOVER_BUTTON_TYPE["mute"]: self.sfx.play_mouseover() if self.sfx.is_muted == True: self.sfx.set_unmute() else: self.sfx.set_mute() elif i == constants.GAMEOVER_BUTTON_TYPE["replay"]: self.sfx.play_mouseover() exitLoop = True self.scoreboard.reset_score() self.start(False) elif i == constants.GAMEOVER_BUTTON_TYPE["exit"]: self.sfx.play_mouseover() exitLoop = True self.done = True self.platform.gameover_screen(mouse.get_pos(), pygame.event.get(), self.scoreboard.scores) pygame.display.update() GameManager.clock.tick(constants.FPS)
def update(self, topmost): """ Route Callbacks """ oldMousedown = self.mousedown CContainer.update(self, topmost) CWidget.update(self, topmost) if self.moving: mx,my = mouse.get_pos() mx = mx - self.moving[0] my = my - self.moving[1] xpos = self.position[0] + mx ypos = self.position[1] + my xpos = xpos if xpos >= 0 else 0 ypos = ypos if ypos >= 0 else 0 self.position = (xpos, ypos) self.moving = mouse.get_pos() if not oldMousedown and self.mousedown and self.enabled: #Start moving self.moving = mouse.get_pos() if self.onmove: self.onmove(self) elif oldMousedown and not self.mousedown: #Stop moving self.moving = False if self.onmovestop: self.onmovestop(self) if self.mousedown and self.enabled: self.parent.bringToFront(self)
def start_screen(self): exitLoop = False self.sfx.play_start_screen() while not exitLoop: # for i in range(0, len(self.platform.gamestart_button_list), 1): # if self.platform.gamestart_button_list[i].is_mouse_over(mouse.get_pos()) and i is not constants.GAMESTART_BUTTON_TYPE["mute"]: # self.sfx.play_mouseover() for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() if event.type == pygame.MOUSEBUTTONDOWN: for i in range(0, len(self.platform.gamestart_button_list), 1): if self.platform.gamestart_button_list[i].is_mouse_over(mouse.get_pos()): if i == constants.GAMESTART_BUTTON_TYPE["mute"]: self.sfx.play_mouseover() self.platform.gamestart_mute_button.toggle_frame() if self.sfx.is_muted == True: self.sfx.set_unmute() else: self.sfx.set_mute() elif i == constants.GAMESTART_BUTTON_TYPE["play"]: self.sfx.play_mouseover() exitLoop = True self.sfx.stop_start_screen() self.scoreboard.reset_score() self.start(False) elif i == constants.GAMESTART_BUTTON_TYPE["exit"]: self.sfx.play_mouseover() exitLoop = True self.done = True self.platform.gamestart_screen(mouse.get_pos(), pygame.event.get()) pygame.display.update() GameManager.clock.tick(constants.FPS)
def update(self, topmost): oldMousedown = self.mousedown Container.update(self, topmost) Widget.update(self, topmost) if self.moving: mx,my = mouse.get_pos() mx = mx - self.moving[0] my = my - self.moving[1] self.position = (self.position[0] + mx, self.position[1] + my) self.moving = mouse.get_pos() if not oldMousedown and self.mousedown and self.enabled: #Start moving self.moving = mouse.get_pos() if self.onMove: self.onMove(self) elif oldMousedown and not self.mousedown: #Stop moving self.moving = False if self.onMoveStop: self.onMoveStop(self) if self.mousedown and self.enabled: self.parent.bringToFront(self)
def update(self, topmost): """ Route Callbacks """ oldMousedown = self.mousedown CContainer.update(self, topmost) CWidget.update(self, topmost) ## handle Displacement of the drawer if click and drag if self.dragging_drawer: mx, my = mouse.get_pos() my = my - self.moving[1] ypos = self.drawerpos + my self.drawerpos = ypos if self.drawerpos < 0: self.drawerpos = 0 dnbut_size_y = self.dn_button.size[1] dwbut_size_y = self.dw_button.size[1] if self.drawerpos >= self.size[1] - 2 * dnbut_size_y - dwbut_size_y: self.drawerpos = self.size[1] - 2 * dnbut_size_y - dwbut_size_y self.moving = mouse.get_pos() if self.onmovedrawer: self.onmovedrawer(self) self.refresh()
def main(): screen, background, font = initPygame(WIDTH, HEIGHT) tree, deck, trash = initTriPeaks() lostGame = False deckRect = Rect(DECKLOCATION[0], DECKLOCATION[1], CARDW, CARDH) # Set background screen.blit(background, (0, 0)) pygame.display.flip() backsideImage = loadCardImage("deck") cards = initCards(backsideImage) rects = [] for card in cards: rects.append(cards[card][0]) trash.add(deck.get_next()) refreshCards(tree, cards) clock = pygame.time.Clock() while 1: clock.tick(60) for event in pygame.event.get(): if event.type == QUIT: return elif event.type == MOUSEBUTTONDOWN: for rect in rects: if rect.collidepoint(mouse.get_pos()): checkCard(tree, trash, cards, rects, rect) refreshCards(tree, cards) print len(cards) if deckRect.collidepoint(mouse.get_pos()): if loseCondition(tree, deck): lostGame = True break drawCard(deck, trash) refreshCards(tree, cards) if lostGame: while(True): for event in pygame.event.get(): if event.type == QUIT: return screen.blit(background, (0, 0)) screen.blit(backsideImage, DECKLOCATION) cardsLeft = font.render(str(deck.count()), 0, (0, 0, 0)) screen.blit(cardsLeft, DECFONTLOCATION) trashTop = trash.peek() screen.blit(loadCardImage(trashTop), TRASHLOCATION) for card in cards: screen.blit(cards[card][1], cards[card][0].topleft) pygame.display.flip() if winCondition(tree): print "JEI"
def handle(self, e): if e.type == KEYDOWN: pressed = key.get_pressed() shifted = pressed[K_LSHIFT] or pressed[K_RSHIFT] scroll = 10 if shifted else 1 if e.key == K_UP: self._scroll(1, -scroll) return True elif e.key == K_DOWN: self._scroll(1, scroll) return True elif e.key == K_LEFT: self._scroll(0, -scroll) return True elif e.key == K_RIGHT: self._scroll(0, scroll) return True elif e.unicode == '>': self._zscroll(-1) return True elif e.unicode == '<': self._zscroll(1) return True elif e.key == K_TAB: self._select(self.cursor) mouse.set_visible(False) return True elif (e.type == MOUSEBUTTONDOWN and self.background and self.background.get_rect().collidepoint(e.pos) and e.button == 1): self._select(self._absolutetile(mouse.get_pos())) return True elif (e.type == MOUSEBUTTONUP and self.background and self.background.get_rect().collidepoint(e.pos) and e.button == 1): self._dragging = False return True elif (e.type == MOUSEMOTION and self.background and self.background.get_rect().collidepoint(e.pos) and 1 in e.buttons): self._expandselection(self._absolutetile(mouse.get_pos())) self._dragging = True return False
def update(self, time): # Move position self.x, self.y = self.x + (self.velocity[0] * time), self.y + (self.velocity[1] * time) # Check new rotation mouse_pos = mouse.get_pos() facing = mouse_pos[0] - self.x, mouse_pos[1] - self.y length = math.hypot(*facing) self.facing = facing[0] / length, facing[1] / length # Rotate Image self.image = pygame.transform.rotate(player_image, math.degrees(math.atan2(*self.facing))) self.rect = self.image.get_rect() self.rect.center = int(self.x), int(self.y) # If off screen, move to other side if self.rect.bottom < self.screen.top: self.rect.top = self.screen.bottom elif self.rect.top > self.screen.bottom: self.rect.bottom = self.screen.top if self.rect.right < self.screen.left: self.rect.left = self.screen.right elif self.rect.left > self.screen.right: self.rect.right = self.screen.left self.x, self.y = self.rect.center # Accelerate key = keyboard.get_pressed() if key[self.thruster]: x = self.velocity[0] + (self.facing[0] * self.acceleration * time) y = self.velocity[1] + (self.facing[1] * self.acceleration * time) self.velocity = x, y
def getPos(self): """Returns the current position of the mouse, in the same units as the :class:`~visual.Window` (0,0) is at centre """ if usePygame: # for pygame top left is 0,0 lastPosPix = numpy.array(mouse.get_pos()) # set (0,0) to centre lastPosPix[1] = self.win.size[1] / 2 - lastPosPix[1] lastPosPix[0] = lastPosPix[0] - self.win.size[0] / 2 else: # for pyglet bottom left is 0,0 # use default window if we don't have one if self.win: w = self.win.winHandle else: defDisplay = pyglet.window.get_platform().get_default_display() w = defDisplay.get_windows()[0] # get position in window lastPosPix = numpy.array([w._mouse_x, w._mouse_y]) # set (0,0) to centre if self.win.useRetina: lastPosPix = lastPosPix*2 - numpy.array(self.win.size) / 2 else: lastPosPix = lastPosPix - numpy.array(self.win.size) / 2 self.lastPos = self._pix2windowUnits(lastPosPix) return copy.copy(self.lastPos)
def MouseClicks(collisionrects, screen, button, filled, bgc=(255, 255, 255), sq=0): """Handles mouse clicks""" i = 1 mpos = mouse.get_pos() count = filled.count sort = filled.sort if button == 1: append = filled.append for sqrect in collisionrects: #Test each rectangle if sqrect.collidepoint(mpos): #If there is collision with the mouse pointer if count(i) == 0: append(i) sort() screen.fill((0, 0, 0), sqrect) i += 1 elif button == 2: remove = filled.remove for sqrect in collisionrects: if sqrect.collidepoint(mpos): if count(i): remove(i) sort() screen.fill(bgc, sqrect) i += 1 elif button == 3: remove = filled.remove for sqrect in collisionrects: if sqrect.collidepoint(mpos): if count(i): remove(i) sort() screen.fill(bgc, sqrect) screen.blit(sq, sqrect) i += 1 return filled
def _blockUnderCursor(self, center=False): """ returns a point in 3d space that was determined by reading the depth buffer value """ try: GL.glReadBuffer(GL.GL_BACK) except Exception: logging.exception('Exception during glReadBuffer') ws = self.root.size if center: x, y = ws x //= 2 y //= 2 else: x, y = mouse.get_pos() if (x < 0 or y < 0 or x >= ws[0] or y >= ws[1]): return 0, 0, 0 y = ws[1] - y try: pixel = GL.glReadPixels(x, y, 1, 1, GL.GL_DEPTH_COMPONENT, GL.GL_FLOAT) newpoint = unproject(x, y, pixel[0]) except Exception: return 0, 0, 0 return newpoint
def event(self, event): # self.direction = STOP # create STOP event to make it work if event.type == KEYDOWN: self.control_mode = "arrows" self.__update_direction(event.key) if event.key == 280: # PgUp self.speed += 1 elif event.key == 281: # PgDown self.speed -= 1 if event.type == MOUSEBUTTONDOWN: self.control_mode = "mouse" self.goal = s2c(mouse.get_pos()) self.screen_goal = mouse.get_pos() self.is_new_goal = True print "mouse %s %s" % (self.position, self.goal)
def mouseLookOn(self): self.root.capture_mouse(self) self.focus_switch = None self.startingMousePosition = mouse.get_pos() if self.avoidMouseJumpBug == 1: self.avoidMouseJumpBug = 2
def update(self, topmost): Widget.update(self, topmost) oldSelectedIndex = self.selectedIndex if self.mouseover: my = mouse.get_pos()[1] screenPos = self.parent.getScreenPosition(self.position)[1] tempIndex = max(0, (my - screenPos - self.style['padding'] + self._scrolling) / self.style['item-height']) if tempIndex != self.overedIndex: self.overedIndex = tempIndex self.needsRefresh = True if self.mousedown: if tempIndex != self.selectedIndex: self.selectedIndex = self.overedIndex self.needsRefresh = True if self.hasFocus: for e in events: if e.type == pygame.KEYDOWN: if e.key == pygame.K_DOWN: self.moveDown() elif e.key == pygame.K_UP: self.moveUp() if e.type == pygame.MOUSEBUTTONDOWN: if e.button == 4 and self.mouseover: self._scrolling = max(0, self._scrolling - self.style['item-height']) if e.button == 5 and self.mouseover: self._scrolling = min(self.style['item-height'] * len(self.items) - self.size[1] + self.style['padding'] * 2, self._scrolling + self.style['item-height']) self.needsRefresh = True if self.needsRefresh: self.needsRefresh = False self.refresh() if oldSelectedIndex != self.selectedIndex: if self.onItemSelected: self.onItemSelected(self)
def start_editor(self): glyph = self.editor_info glyph_rect = glyph.rect glyph.input(PAGES['editor']) glyph.update() editor = self.editor editor_rect = editor.rect SCREEN.blit(EDITOR_BKGSCREEN, (0, 0)) SCREEN.blit(glyph.image, glyph_rect) SCREEN.blit(editor.image, editor_rect) editor_focus = False while 1: mouse_pos = mouse.get_pos() link = glyph.get_collisions(mouse_pos) if link: mouse.set_cursor(*HAND_CURSOR) else: mouse.set_cursor(*DEFAULT_CURSOR) for ev in event.get(): if ev.type == MOUSEBUTTONDOWN: if link: pass if editor.rect.collidepoint(mouse_pos): editor_focus = True else: editor_focus = False if ev.type == KEYDOWN: if ev.key == K_ESCAPE: exit() if editor_focus == True: editor.input(ev) cursor = editor.get_cursor() editor.image.fill((255, 205, 0), cursor) SCREEN.blit(editor.image, editor_rect) display.update()
def update(self, time): self.time += time if self.time < Menu.FADEINTIME: ratio = self.time / Menu.FADEINTIME value = int(ratio * 255) self.color = PC.Color(value, value, value) position = PM.get_pos() if self.inrange(self.new_game, position): self.hover[0] = True else: self.hover[0] = False if self.inrange(self.volume, position): self.hover[1] = True else: self.hover[1] = False if self.inrange(self.brightness, position): self.hover[2] = True else: self.hover[2] = False if self.inrange(self.score, position): self.hover[3] = True else: self.hover[3] = False if self.inrange(self.exit, position): self.hover[4] = True else: self.hover[4] = False
def input(self, event): self.x_speed = 0.0 self.y_speed = 0.0 x, y = mouse.get_pos() if event.type == MOUSEBUTTONDOWN and event.button == MOUSE.MIDDLE: self.x_first = x self.y_first = y elif event.type == MOUSEBUTTONUP and event.button == MOUSE.MIDDLE: self.x_first = None self.y_first = None elif event.type == MOUSEMOTION and mouse.get_pressed()[1] and \ self.x_first and self.y_first: self.x_delta = x - self.x_first self.y_delta = y - self.y_first else: if mouse.get_focused(): if x > self.w - self.scroll_width and x < self.w: self.x_speed = self.speed elif x < self.scroll_width: self.x_speed = -self.speed if y > self.h - self.scroll_width: self.y_speed = self.speed elif y < self.scroll_width: self.y_speed = -self.speed if key.get_focused(): if key.get_pressed()[K_RIGHT]: self.x_speed = self.speed elif key.get_pressed()[K_LEFT]: self.x_speed = -self.speed if key.get_pressed()[K_DOWN]: self.y_speed = self.speed elif key.get_pressed()[K_UP]: self.y_speed = -self.speed
def event(self, event): if event.type == PG.KEYDOWN and event.key == PG.K_ESCAPE: G.Globals.STATE = Menu.Menu() if event.type == PG.MOUSEBUTTONDOWN: pos = PM.get_pos() if pos[0] >= 0 and pos[0] <= self.back_x: if pos[1] >= 0 and pos[1] <= self.back_y: G.Globals.STATE = Menu.Menu()
def mouse_hovering(self, mouse_pos=None): # pygame gets pissy if it's not initialized so we can't have x and # y in the initializer if not mouse_pos: mouse_pos = mouse.get_pos() # srsly??? return self.surface.get_rect().move(self.x, self.y).collidepoint( mouse_pos)
def get_tile(self): x, y = mouse.get_pos() x += self.camera.rect.x y += self.camera.rect.y for t in self.tilemgr.tiles: if t.rect.collidepoint(x, y): self.current_tile = t.kind break
def render(self): self.viewingFrustum = frustum.Frustum.fromViewingMatrix() if self.superSecretSettings: self.editor.drawStars() if self.drawSky: self.drawSkyBackground() if self.drawFog: self.enableFog() self.drawFloorQuad() self.editor.renderer.viewingFrustum = self.viewingFrustum self.editor.renderer.draw() if self.showCeiling and not self.editor.renderer.inSpace(): self.drawCeiling() if self.editor.level: if pygame.key.get_focused(): try: self.updateBlockFaceUnderCursor() except (EnvironmentError, pymclevel.ChunkNotPresent) as e: logging.debug("Updating cursor block: %s", e) self.blockFaceUnderCursor = (None, None) self.root.update_tooltip() (blockPosition, faceDirection) = self.blockFaceUnderCursor if None != blockPosition: self.editor.updateInspectionString(blockPosition) if self.find_widget(mouse.get_pos()) == self: ct = self.editor.currentTool if ct: ct.drawTerrainReticle() ct.drawToolReticle() else: self.editor.drawWireCubeReticle() for t in self.editor.toolbar.tools: t.drawTerrainMarkers() t.drawToolMarkers() if self.drawFog: self.disableFog() if self._compass is None: self._compass = CompassOverlay() self._compass.yawPitch = self.yaw, 0 with gl.glPushMatrix(GL.GL_PROJECTION): GL.glLoadIdentity() GL.glOrtho(0., 1., float(self.height) / self.width, 0, -200, 200) self._compass.draw()
def check_mouse(self, x, y, width, height): pos = PM.get_pos() if pos[0] >= x and pos[0] <= (x + width): pass else: return False if pos[1] >= y and pos[1] <= (y + height): return True else: return False
def MouseClicksMain(buttons): """Handles mouse clicks""" mpos = mouse.get_pos() i = 1 a = 0 for rect in buttons: if rect.collidepoint(mpos): a = i i += 1 return a
def poll(self): p = mouse.get_pos() changed = False for i in range(len(self._buttons)): if self._rects[i]: if self._buttons[i].poll((p[0]-self._rects[i].left, p[1]-self._rects[i].top)): changed = True return changed
def _mouse(self, pos = None): if pos is None: pos = mouse.get_pos() else: mouse.set_pos(pos) tile = self._screentile(pos) if not (0 <= tile[0] < self.dimensions[0] and 0 <= tile[1] < self.dimensions[1]): tile = None return pos, tile
def draw_universe(self): self.ssSprites.clear(self.view, self.viewClear) for ss in self.ssSprites.sprites(): ss.update_pos(self.xbound, self.ybound) ss.update_focus(mouse.get_pos()) self.ssSprites.update(self.CoU, self.collSet) self.ssSprites.draw(self.view) self.screen.blit(self.view, self.viewrect)
def _checkClick(self): for actualEvent in event.get(): if actualEvent.type == QUIT: quit() sys.exit() # overenie kliknutia, ak klikol overim, ci klikol na tlacidlo if actualEvent.type == MOUSEBUTTONUP: position = mouse.get_pos() self._checkIfInButton(position)
def main(): global inputmanager,screen,board #init graphics init() size = (150,150) screen = set_mode(size) #init game data nr_of_rectangles = 9 board = TicTacToeBoard(nr_of_rectangles) #board.paint(screen) #init input inputmanager = InputManager([ ("Mouse", 1, "Press", (lambda: board.make_turn(Point(get_pos()[0],get_pos()[1])))), ("Key", K_UP, "Press", (lambda: print("Hello Keyboard!"))), ]) loop()
def update(self, topmost): CWidget.update(self, topmost) oldSelectedIndex = self.selectedIndex if self.mouseover: my = mouse.get_pos()[1] screenPos = self.parent.getScreenPosition(self.position)[1] tempIndex = max(0,((my - screenPos - self.style['padding'] + \ self._scrolling) / self.style['item-height'])) if tempIndex != self.overedIndex: self.overedIndex = tempIndex self.needsRefresh = True if self.mousedown: if tempIndex != self.selectedIndex: self.selectedIndex = self.overedIndex self.needsRefresh = True if self.hasFocus: events = self.desktop.getEvents() for e in events: if e.type == pygame.KEYDOWN: if e.key == pygame.K_DOWN: self.moveDown() elif e.key == pygame.K_UP: self.moveUp() elif e.key == pygame.K_RETURN : if self.onitemlaunched: self.onitemlaunched(self) if e.type == pygame.MOUSEBUTTONDOWN: if e.button == 4 and self.mouseover: #Wheel-UP self._scrolling = max(0, self._scrolling - \ self.style['item-height']) if e.button == 5 and self.mouseover: #Wheel-down self._scrolling = min(self.style['item-height'] * \ len(self.items) - self.size[1] + \ self.style['padding'] * 2, \ self._scrolling + self.style['item-height']) self.needsRefresh = True if self.needsRefresh: self.needsRefresh = False self.refresh() #Checks if selected index has changed if oldSelectedIndex != self.selectedIndex: if self.onitemselected: self.onitemselected(self)
def update(self): """Uses move_to_target to follow the mouse. Counts cooldown and respawn to 0 when needed and checks its point total for extra lives. """ self.move_to_target(mouse.get_pos()) self.cooldown -= 1 if self.cooldown > 0 else 0 self.respawn -= 1 if self.respawn > 0 else 0 if self.score >= (self.nextlife * self.next_extra_guy): self.lives += 1 self.next_extra_guy += 1 self.pub('got_1up', self)
def check_click(self): # check if the button is being click mouse = get_pos() click = get_pressed() x, y, w, h = self.rect return x + w > mouse[0] > x and y + h > mouse[1] > y and click[0] == 1
def is_mouse_on(self): u = unit_size[0] x = cws[0]/u + self.x y = cws[1]/u + self.y pos_x, pos_y = mouse.get_pos() return x < pos_x/u < x + self.width and y < pos_y/u < y + self.height
def __init__(self): x, y = mouse.get_pos() mouse.set_visible(False) super().__init__(sword_image, x, y)
triangle = Polygon([(0, 70), (110, 0), (110, 70)]) rhombus = Polygon([(0, 80), (20, 0), (80, 0), (60, 80)]) triangle.move_ip(200, 200) rhombus.move_ip(300, 300) font = Font(None, 24) r = mouse.get_rel() grab, other = None, None while True: SCREEN.fill((0, 0, 0)) draw.polygon(SCREEN, (255, 0, 0), triangle.P, 1) draw.polygon(SCREEN, (0, 0, 255), rhombus.P, 1) mouse_pos = mouse.get_pos() for ev in event.get(): if ev.type == KEYDOWN: if ev.key == K_q: exit() if ev.type == MOUSEBUTTONDOWN: if grab: grab, other = None, None elif rhombus.collidepoint(mouse_pos): grab = rhombus other = triangle elif triangle.collidepoint(mouse_pos): grab = triangle other = rhombus Y_triangle = triangle.project((0, 1)) Y_rhombus = rhombus.project((0, 1)) draw.line(SCREEN, (255, 0, 0), (2, Y_triangle[0]), (2, Y_triangle[1]),
def onClick(self, mouse_click=False): mx, my = get_pos() if self.rect.x < mx and self.rect.x + self.PL_W > mx and self.rect.y < my and self.rect.y + self.PL_H > my and mouse_click: return 1 else: return 0
def loop_events(self): if (self.turn % 2 == 1 and self.move and self.pause > 0): self.pause -= 1 elif (self.turn % 2 == 1 and self.move): self.move = False self.turn += 1 self.robot() pygame.mixer.music.play() self.timer_start = time.get_ticks() self.a = False self.b = True self.moveset = 0 hit = False miss = False clicked = False #表示是否有按键的动作 #system function pos = mouse.get_pos() # Handle PyGame events for e in event.get(): # Handle quit if e.type == QUIT: self.loop = False break gameTime, endGame = self.timerData if not endGame: # Handle click if e.type == MOUSEBUTTONDOWN and e.button == Constants.LEFTMOUSEBUTTON: # Start timer if not started if self.timer is not None and self.timer_start == 0: self.timer_start = time.get_ticks() else: # Handle hit/miss clicked = True miss = True flag = False print(pos[0], pos[1]) base_row = Constants.GAMEHEIGHT // Constants.HOLEROWS base_column = Constants.GAMEWIDTH // Constants.HOLECOLUMNS for column in range(Constants.HOLECOLUMNS): thisX = base_column * column thisX += (base_column - Constants.HOLEWIDTH) / 2 for row in range(Constants.HOLEROWS): rowY = base_row * row rowY += (base_row - Constants.HOLEHEIGHT) / 2 if (self.judge(pos, thisX, rowY) and self.vis[row][column] == False and self.turn % 2 == 0): self.process(row, column) print(row, column) #self.get.play(1) pygame.mixer.music.load("assets/get.ogg") pygame.mixer.music.play() self.timer_start = time.get_ticks() flag = True self.turn += 1 if (self.turn % 2): self.a = True self.b = False if (self.tot_stone > 0): self.move = True self.pause = 100 else: self.a = False self.b = True self.moveset = 0 break if (flag): break if hit: self.score.hit() if miss: self.score.miss() if e.type == KEYDOWN: # Allow escape to abort attempt if e.key == K_ESCAPE: self.reset() break # Handle cheats (for dev work) if Constants.DEBUGMODE: if e.key == K_e: hit = True miss = False self.score.hit() if e.key == K_r: hit = False miss = True self.score.miss() if e.key == K_t: self.score.misses = 0 if e.key == K_y: self.score.misses += 5 if e.key == K_u: self.score.misses -= 5 if e.key == K_i: self.score.hits = 0 if e.key == K_o: self.score.hits += 5 if e.key == K_p: self.score.hits -= 5 # End game screen else: if (pos[0] > 120 and pos[0] < 320 and pos[1] > 600 and pos[1] < 660): self.back_on = True else: self.back_on = False if e.type == MOUSEBUTTONDOWN: if (pos[0] > 120 and pos[0] < 300 and pos[1] > 600 and pos[1] < 660): self.out = True if e.type == KEYDOWN: if e.key == K_SPACE: # Restart self.reset() break return (clicked, hit, miss)
def main(): init() running = True size = 1000, 1000 # these are the width and height of the simulation grid grid_x, grid_y = int(argv[1]), int(argv[2]) # this is how many pixels per cell in the simulation grid # We need to use the grid factor because the pygame window is not # the same width and height of the simulation grid size. Therefore, # we scale the pygame window down to fit the simulation size grid_factor_x, grid_factor_y = 1000 / grid_x, 1000 / grid_y screen = display.set_mode(size) # used to track either the setting of the topleft of a rectangle, # or the bottom right (if bottom right, the rectangle is completed) num_clicks_patch = 0 num_clicks_patch_temp = 0 num_clicks_exit = 0 num_clicks_exit_temp = 0 # the position of the mouse when the left or right mouse button is clicked mouse_pos_patch = () mouse_pos_exit = () # the position of the patch's top left corner in pixels patch_tl = () # the position of the patch's bottom right corner in pixels patch_br = () # the position of the exits's top left corner in pixels exit_tl = () # the position of the exits's bottom right corner in pixels exit_br = () patch_temp = Rect(-1, -1, 0, 0) exit_temp = Rect(-1, -1, 0, 0) # a list of patches as pygame rectangles that are being displayed # on screen patch_list = [] # a list of patches removed from the screen. The user can recall these # with a keybind patch_discard_list = [] # a list of exits as pygame rectangles that are being displayed # on screen exit_list = [] # a list of exits removed from the screen. The user can recall these # with a keybind exit_discard_list = [] # a list of 1 pixel-wide pygame rectangles that are drawn to the screen # to create grid lines gridline_list = [] # populate `gridline_list` gridline_list = populate_gridline_list(gridline_list, grid_x, grid_y, grid_factor_x, grid_factor_y) # main game loop will run until the user clicks the exit button in the top right corner (Windows) while running: # event loop for pygame_event in event.get(): # if the user hits the window's exit button, stop the app if pygame_event.type == QUIT: running = False # if the user hits the mouse button in the app window if pygame_event.type == MOUSEBUTTONDOWN and mouse.get_focused(): # return a list of booleans for the three major buttons on a mouse: # left mouse, right mouse, and middle mouse. If an element is True, # the corresponding button is pressed mouse_depressed = mouse.get_pressed(num_buttons=3) # if the user clicks ONLY the left mouse button, they are creating # a patch. if mouse_depressed[0] and not mouse_depressed[2]: # get the mouse's position with respect to the window mouse_pos_patch = mouse.get_pos() num_clicks_patch += 1 num_clicks_patch_temp = num_clicks_patch # if the user clicks ONLY the right mouse button, they are creating # an exit. if mouse_depressed[2] and not mouse_depressed[0]: mouse_pos_exit = mouse.get_pos() num_clicks_exit += 1 num_clicks_exit_temp = num_clicks_exit if pygame_event.type == KEYDOWN and key.get_focused(): # return a list of booleans for all the keys on the keyboard # If an element is True, the corresponding key is pressed keys_depressed = key.get_pressed() # if the user presses CTRL+Z, remove the previously added patches # from most recent to least recent if keys_depressed[K_LCTRL] and keys_depressed[ K_z] and not keys_depressed[K_LSHIFT]: # if the user has begun to create a new patch, they can # cancel it by hitting CTRL+Z. Otherwise, CTRL+Z removes a # patch that has already been drawn if patch_list and num_clicks_patch == 0: patch_discard_list.append(patch_list.pop()) print("Number of patches:", len(patch_list)) else: patch_tl = () num_clicks_patch = 0 num_clicks_patch_temp = 0 print("Undid patch topleft!") # if the user pressed CTRL+SHIFT+Z, remove the previously added exits # from most recent to least recent elif keys_depressed[K_LSHIFT] and keys_depressed[ K_LCTRL] and keys_depressed[K_z]: # if the user has begun to create a new exit, they can # cancel it by hitting CTRL+SHIFT+Z. Otherwise, CTRL+SHIFT+Z removes a # exit that has already been drawn if exit_list and num_clicks_exit == 0: exit_discard_list.append(exit_list.pop()) print("Number of exits:", len(exit_list)) else: exit_tl = () num_clicks_exit = 0 num_clicks_exit_temp = 0 print("Undid exit topleft!") # if the user presses CTRL+Y, restore the previously removed patch # from the discard patch list from most recent to least recent if keys_depressed[K_LCTRL] and keys_depressed[ K_y] and not keys_depressed[K_LSHIFT]: # the user can only restore a deleted patch if they haven't # started drawing another one. Easy fix for this: press CTRL+Z # to undo the topleft of the already-begun patch, then do CTRL+Y if patch_discard_list and num_clicks_patch == 0: patch_list.append(patch_discard_list.pop()) print("Number of patches:", len(patch_list)) # if the user pressed CTRL+SHIFT+Y, restore the previously removed exit # from the discard exit list from most recent to least recent elif keys_depressed[K_LSHIFT] and keys_depressed[ K_LCTRL] and keys_depressed[K_y]: # the user can only restore a deleted exit if they haven't # started drawing another one. Easy fix for this: press CTRL+SHIFT+Z # to undo the topleft of the already-begun exit, then do CTRL+SHIFT+Y if exit_discard_list and num_clicks_exit == 0: exit_list.append(exit_discard_list.pop()) print("Number of exits:", len(exit_list)) # if the user has clicked the mouse once, store the mouse position # as the top left of the rectangle to be drawn if num_clicks_patch_temp == 1: patch_tl = mouse_pos_patch num_clicks_patch_temp = 0 patch_temp.topleft = patch_tl print("Patch topleft set at", patch_tl) # if the user has clicked the mouse for the second time, elif num_clicks_patch_temp == 2: patch_br = mouse_pos_patch patch_list.append( Rect(patch_tl[0], patch_tl[1], patch_br[0] - patch_tl[0], patch_br[1] - patch_tl[1])) num_clicks_patch = 0 num_clicks_patch_temp = 0 print("Number of patches:", len(patch_list)) # if the user has clicked the mouse once, store the mouse position # as the top left of the rectangle to be drawn if num_clicks_exit_temp == 1: exit_tl = mouse_pos_exit num_clicks_exit_temp = 0 exit_temp.topleft = exit_tl print("Exit topleft set at", exit_tl) # if the user has clicked the mouse for the second time, elif num_clicks_exit_temp == 2: exit_br = mouse_pos_exit exit_list.append( Rect(exit_tl[0], exit_tl[1], exit_br[0] - exit_tl[0], exit_br[1] - exit_tl[1])) num_clicks_exit = 0 num_clicks_exit_temp = 0 print("Number of exits:", len(exit_list)) # first blacken the screen screen.fill("black") # draw the grid lines for gridline in gridline_list: draw.rect(screen, "blue", gridline) # draw the patches on top of the grid lines for patch in patch_list: patch.normalize() draw.rect(screen, "white", patch, width=1) # then draw the exits over the grid lines and patches for exit in exit_list: exit.normalize() draw.rect(screen, "red", exit) # if the user has clicked to begin drawing either a patch # or an exit, display the box growing and shrinking as they # move their mouse so they can see what the patch/exit will look # like when it's drawn if num_clicks_patch == 1: patch_temp.size = tuple( map(sub, mouse.get_pos(), patch_temp.topleft)) # we'll use `patch_temp_copy` to display a proper rectangle if the user defines # `patch_temp`'s topleft and then moves the mouse above or farther left than # that point. Doing so creates a negative width/height in the rectangle which # does not draw to the screen without glitching. Normalizing the rectangle # removes the negative width/height and reassigns the topleft point in the process. # Without using a copy of `patch_temp`, its top left would change every game loop, # and the rectangle would not change with mouse movement correctly. If this # description doesn't make sense, just trust me. If you're the kind of person # who likes to define the bottom right corner first, this code lets you see # that normalized (looks like a rectangle, not a cross road) rectangle change # size as your mouse moves around :D patch_temp_copy = Rect(-1, -1, 0, 0) # I have to define `patch_temp_copy` like this instead of `patch_temp_copy = patch_temp` # since that would just make `patch_temp_copy` an alias of `patch_temp` patch_temp_copy.topleft = patch_temp.topleft patch_temp_copy.size = patch_temp.size patch_temp_copy.normalize() draw.rect(screen, "white", patch_temp_copy, width=1) print(patch_temp_copy.size, " ", end='\r') if num_clicks_exit == 1: # same theory as with `patch_temp_copy` so I'm not gonna repeat it... exit_temp.size = tuple(map(sub, mouse.get_pos(), exit_temp.topleft)) exit_temp_copy = Rect(-1, -1, 0, 0) exit_temp_copy.topleft = exit_temp.topleft exit_temp_copy.size = exit_temp.size exit_temp_copy.normalize() draw.rect(screen, "red", exit_temp_copy) print(exit_temp_copy.size, " ", end='\r') # this updates the contents of the surface display.flip() # if the user has clicked the exit button, ask them if they either want to create # the terrain or completely exit the editor. Give them a second chance if they # want to quit. That way they don't accidentally lose their progress. if not running: response = input( "Would you like to create the terrain with this model? (y/n) ") if response == 'y': # create the terrain grid from the rectangles drawn in the pygame window terrain_grid = create_terrain_grid(patch_list, exit_list, grid_x, grid_y, grid_factor_x, grid_factor_y) # draw converted rectangles to the .txt file output_to_file(grid_x, grid_y, terrain_grid) # save the pygame screen as a .png to use as the background image of the simulation # visualization .gif save_screen_as_bkgr(screen) # update the patches document in the `params.json` file update_patches(patch_list, grid_factor_x, grid_factor_y) elif response == 'n': second_response = input("Are you sure? (Y/N) ") if second_response == "Y": print("Quitting terrain editor.") elif second_response == "N": running = True print("Continuing terrain editor.") else: running = True print( "Invalid response ('Y' or 'N' only, please). Continuing terrain editor." ) else: running = True print( "Invalid response ('y' or 'n' only, please). Continuing terrain editor." ) quit()
def Update(self): if not self.Running: return False eventList = [] for event in pygame.event.get(): if event.type == pygame.QUIT: self.Quit() return False elif event.type == pygame.VIDEORESIZE: self.UpdateWindowSize(event.w, event.h) elif event.type == pygame.KEYDOWN: if event.key == pygame.K_RETURN: piece = self.PieceList[self.Selectable[self.SelectIndex]] piece.TriggerOnClick(False) self.SelectIndex += 1 if self.SelectIndex >= len(self.Selectable): self.SelectIndex = 0 if self.DebugMode: print("Enter pressed index: " + str(self.SelectIndex) + " ->" + str(self.Selectable[self.SelectIndex])) else: eventList += [event] else: eventList += [event] deltaTime = self.Clock.get_rawtime() deltaTime /= 1000 # to make it seconds loop = 0 for piece in self.PieceList: if piece.Update(self.Window, self.DebugMode, deltaTime, self.ScaleFactor): index = self.Selectable.index(loop) if index != self.SelectIndex: self.SelectIndex = index if self.DebugMode: print("piece pressed index: " + str(self.SelectIndex) + " ->" + str(self.Selectable[self.SelectIndex])) piece.UpdateLabel(eventList, self.DebugMode) loop += 1 if len(self.Selectable) > 0: loop = 0 for piece in self.PieceList: piece.Selected = loop == self.Selectable[self.SelectIndex] loop += 1 if self.DebugMode: font = pygame.font.SysFont("monospace", 20) text = "FPS: " text += str(round(self.Clock.get_fps())) text += " LastFrame: " text += str(round(deltaTime / 1000, 3)) label = font.render(text, 1, (255, 0, 0)) self.Window.blit(label, [8, 8]) if mouse.get_pressed()[0]: if self.MouseStartPos == None: self.MouseStartPos = list(mouse.get_pos()) size = [ mouse.get_pos()[0] - self.MouseStartPos[0], mouse.get_pos()[1] - self.MouseStartPos[1] ] print("mouse Pos / Size: " + str(self.MouseStartPos) + ", " + str(size)) else: self.MouseStartPos = None display.update() self.Clock.tick() self.SolarCovered = False return True
def main(): time_need_begin = None game_end = None game_begin = None budget_need = True global Card_List, select_card, card, budget, prev_diff InGameCards = [] pygame.init() windowWidth = 360 windowHeight = 640 Giant = Card("GiantCard copy.png") Giant.id = 1 Witch = Card("WitchCard copy.png") Witch.id = 2 Fireball = Card("FireballCard copy.png") Fireball.id = 4 Wizard = Card("WizardCard copy.png") Wizard.id = 3 Bomber = Card("BomberCard copy.png") Bomber.id = 5 Balloon = Card("BalloonCard copy.png") Balloon.id = 6 Archer = Card("archers copy.png") Archer.id = 7 Lava = Card("LavaHoundCard copy.png") Lava.id = 8 screen = pygame.display.set_mode((windowWidth, windowHeight)) while select_card: screen.fill((255, 255, 255)) get_event(Giant, Witch, Wizard, Fireball, Archer, Bomber, Balloon) screen.blit(Giant.picture, (25, 220)) screen.blit(Wizard.picture, (105, 220)) screen.blit(Witch.picture, (185, 220)) screen.blit(Fireball.picture, (265, 220)) screen.blit(Archer.picture, (70, 360)) screen.blit(Balloon.picture, (150, 360)) screen.blit(Bomber.picture, (230, 360)) if Giant in Card_List: screen.blit(pygame.image.load("CheckMark.png"), (45, 190)) if Wizard in Card_List: screen.blit(pygame.image.load("CheckMark.png"), (120, 190)) if Witch in Card_List: screen.blit(pygame.image.load("CheckMark.png"), (200, 190)) if Fireball in Card_List: screen.blit(pygame.image.load("CheckMark.png"), (280, 190)) if Archer in Card_List: screen.blit(pygame.image.load("CheckMark.png"), (88, 330)) if Balloon in Card_List: screen.blit(pygame.image.load("CheckMark.png"), (165, 330)) if Bomber in Card_List: screen.blit(pygame.image.load("CheckMark.png"), (245, 330)) if not (130 < pygame.mouse.get_pos()[0] < 230 and 500 < pygame.mouse.get_pos()[1] < 550 and pygame.mouse.get_pressed()[0]): pygame.draw.rect(screen, (0, 255, 0), (130, 500, 100, 50)) elif 130 < pygame.mouse.get_pos()[0] < 230 and 500 < pygame.mouse.get_pos()[1] < 550 and \ pygame.mouse.get_pressed()[0]: pygame.draw.rect(screen, (0, 200, 0), (130, 500, 100, 50)) pygame.display.update() intial() game_begin = time.time() while True: game_end = time.time() if int(game_end - game_begin) == 120: break main_get_event() screen.fill((255, 255, 255)) screen.blit(pygame.image.load("background.jpg"), (0, 0)) ShowCards(Card_List, screen) if budget_need and budget != 10: time_need_begin = time.time() budget_need = False budget_need = deposit(time_need_begin) if m.get_pressed()[0] and m.get_pos()[1] > 400 and not card: card = chosen_card(m.get_pos(), Card_List) if card: card.set_position(m.get_pos()) pygame.display.update()
size = (width, height) screen = pygame.display.set_mode(size) pygame.display.set_caption("Starfield") # -------------------- create a bunch of stars -------------------------------- stars = [] for i in range(400): stars.append(little_star(width, height)) # -------------------- main loop ---------------------------------------------- done = False while not done: # get mouse coordinate mouseX, mouseY = get_pos() # erase everything on screen into full blackness screen.fill((0, 0, 0)) # draw those stars!!! speed = remap(mouseX, 0, size[0], 0, 50) for star in stars: # update star star.update(speed) # show star sx = remap(star.x / star.z, 0, 1, 0, size[0]) + size[0] / 2 sy = remap(star.y / star.z, 0, 1, 0, size[1]) + size[1] / 2 px = remap(star.x / star.pz, 0, 1, 0, size[0]) + size[0] / 2 py = remap(star.y / star.pz, 0, 1, 0, size[1]) + size[1] / 2
def main(): # initialize the pygame module pygame.init() # load and set the logo logo = pygame.image.load(sys.path[0] + "/logo32x32.png") pygame.display.set_icon(logo) sysfont = font.SysFont(None, 24) screen = pygame.display.set_mode((700,700), constants.RESIZABLE) interactables = [] filename = sys.argv[1] if len(sys.argv) > 1 else 'smlogicsim.json' try: jsonContent = "" with open(filename, 'r') as file: jsonContent = file.read() interactables = deserialize(jsonContent) except IOError: None pygame.display.set_caption("Scrap Mechanic Logic Gate Simulator - " + filename) # define a variable to control the main loop closing = False running = False selected = None isMoving = False isLinking = False posAtStart = (0,0) tick = 0 lastTickTime = time.time() # main loop while not closing: # event handling, gets all event from the event queue for event in pygame.event.get(): if event.type == constants.MOUSEBUTTONDOWN: if event.button == 1: selectedNow = findItem(interactables, event.pos) if selected is not None: selected.selected = False if selectedNow is None: selected = None else: selectedNow.selected = True selected = selectedNow posAtStart = event.pos elif event.type == constants.MOUSEBUTTONUP: if isLinking: target = findItem(interactables, event.pos) if target is not None and target is not selected and target.maxInputCount != 0: if selected in target.inputs: # the connection is already there - undo it target.inputs.remove(selected) else: # If the connection already goes the other way, reverse it. if target in selected.inputs: selected.inputs.remove(target) selected.inputsChanged() if target.maxInputCount == 1: target.inputs.clear() target.inputs.append(selected) target.inputsChanged() target.paint() selected.paint() isLinking = False isMoving = False elif event.type == constants.MOUSEMOTION: if event.buttons[0] == 1: # the >5 thing is to prevent random jiggles while clicking from instigating moves. if selected is not None \ and not isMoving \ and not isLinking \ and (abs(event.pos[0] - posAtStart[0]) > 5 or abs(event.pos[1] - posAtStart[1]) > 5): keyboardModifiers = key.get_mods() isMoving = keyboardModifiers in (constants.KMOD_SHIFT, constants.KMOD_LSHIFT, constants.KMOD_RSHIFT) isLinking = keyboardModifiers == 0 if isMoving: selected.move(event.rel) elif event.type == constants.KEYDOWN: if event.key == constants.K_DELETE and selected is not None: interactables.remove(selected) for i in interactables: if selected in i.inputs: i.inputs.remove(selected) i.inputsChanged() selected = None elif event.key == constants.K_LEFT and selected is not None: selected.swapGate(-1) elif event.key == constants.K_RIGHT and selected is not None: selected.swapGate(1) elif event.key == constants.K_UP and selected is not None: selected.alternate() elif event.key == constants.K_DOWN and selected is not None: selected.alternate() elif event.key == constants.K_F10 and not running: singleStep(interactables) tick += 1 elif event.key == constants.K_F4: tick = 0 running = False if event.mod in (constants.KMOD_SHIFT, constants.KMOD_LSHIFT, constants.KMOD_RSHIFT): putOnLift(interactables) else: reload(interactables) elif event.key == constants.K_F5: running = True elif event.key == constants.K_F6: running = False elif event.key == constants.K_s: with open(filename, 'w') as file: file.write(serialize(interactables)) elif event.key == constants.K_p: if event.mod in (constants.KMOD_SHIFT, constants.KMOD_LSHIFT, constants.KMOD_RSHIFT): for i in interactables: i.paint() elif selected is not None: selected.paint() elif event.key in Interactable.hotkeyToTypeMap.keys(): if selected is not None: selected.selected = False selected = Interactable.hotkeyToTypeMap[event.key](mouse.get_pos()) selected.selected = True interactables.append(selected) elif event.type == constants.QUIT: closing = True if running: timenow = time.time() if (timenow - lastTickTime > .25): singleStep(interactables) tick += 1 lastTickTime = timenow screen.fill(BLACK) tickImage = sysfont.render(str(tick), True, RED) tickRect = tickImage.get_rect() screenRect = screen.get_rect() tickRect.move_ip(screenRect.width - 10 - tickRect.width, 10) screen.blit(tickImage, tickRect) for box in interactables: for input in box.inputs: drawLineWithArrows(screen, input.rect.center, box.rect.center, LIGHTBLUE if input.prevState else BLUE) for box in interactables: box.draw(screen) if isLinking: mousePos = mouse.get_pos() target = findItem(interactables, mousePos) if target is None: draw.line(screen, GRAY, selected.rect.center, mouse.get_pos(), 1) else: draw.line(screen, GREEN, selected.rect.center, target.rect.center, 1) display.flip() # display.update() # Always just save on exit savedState = serialize(interactables) with open(filename, 'w') as file: file.write(savedState)
def set_cursor_pos_to_mouse_coords(self): if self.cursor_in_menu_bounds(): self.menu_pos = clamp( (int(get_pos()[1] / SETTINGS.get(Setting.SCREEN_SCALE)) - self.root_y) // 24 + self.menu_min, self.menu_min, self.menu_max)
def check_click(self): """Check mouse position has collided with this button, if so it is clicked""" if self.rect.collidepoint(mouse.get_pos()): self.clicked = True
def loop_display(self, clicked, hit, miss): gameTime, endGame = self.timerData if not gameTime and self.timer: gameTime = -1 # Display bg self.screen.blit(self.img_background, (0, 0)) # Display holes #有一个防止栈空 for i in range(1, Constants.HOLEROWS): for j in range(Constants.HOLECOLUMNS): if (self.vis[i][j] == False): self.screen.blit(self.diamond[j % Constants.HOLECOLUMNS], self.holes[j][i]) flag = False for i in range(1, Constants.HOLEROWS): for j in range(Constants.HOLECOLUMNS): if (self.change[i][j] > 0): flag = True self.screen.blit( self.diamond_remove[j % Constants.HOLECOLUMNS], self.holes[j][i]) self.change[i][j] -= 1 if (flag): if (self.turn % 2): self.screen.blit(self.imagea, (0 + self.moveset, 200 + self.moveset)) else: self.screen.blit(self.imageb, (250 - self.moveset, 200 - self.moveset)) self.moveset += 0.3 thisHammer = transform.rotate( self.img_mallet.copy(), (Constants.MALLETROTHIT if clicked else Constants.MALLETROTNORM)) hammer_x, hammer_y = mouse.get_pos() hammer_x -= thisHammer.get_width() / 5 hammer_y -= thisHammer.get_height() / 4 self.screen.blit(thisHammer, (hammer_x, hammer_y)) # Fade screen if not started or has ended if self.timer and (endGame or gameTime == -1): overlay = Surface((Constants.GAMEWIDTH, Constants.GAMEHEIGHT), SRCALPHA, 32) overlay = overlay.convert_alpha() #rgb, opacity overlay.fill((100, 100, 100, 0.8 * 255)) self.screen.blit(overlay, (0, 0)) # Debug data for readout debug_data = {} if Constants.DEBUGMODE: debug_data = { "DEBUG": True, "FPS": int(self.clock.get_fps()), "MOLES": "{}/{}".format(Constants.MOLECOUNT, Constants.HOLEROWS * Constants.HOLECOLUMNS), "KEYS": "E[H]R[M]T[M0]Y[M+5]U[M-5]I[H0]O[H+5]P[H-5]" } # Display data readout data = self.score.label(timer=gameTime, turn=self.turn, debug=debug_data, size=(1.5 if endGame else 1.5)) self.screen.blit(data, (5, 5)) # Display hit/miss indicators if not endGame: # Hit indicator if self.a: self.show_hit = time.get_ticks() self.a = False if self.show_hit > 0 and time.get_ticks( ) - self.show_hit <= Constants.MOLEHITHUD: hit_label = self.text.get_label("PLAYER 1 DONE", scale=3, color=(255, 50, 0)) hit_x = (Constants.GAMEWIDTH - hit_label.get_width()) / 2 hit_y = (Constants.GAMEHEIGHT - hit_label.get_height()) / 2 self.screen.blit(hit_label, (hit_x, hit_y)) else: self.show_hit = 0 # Miss indicator if self.b: self.show_miss = time.get_ticks() self.b = False if self.show_miss > 0 and time.get_ticks( ) - self.show_miss <= Constants.MOLEMISSHUD: miss_label = self.text.get_label("PLAYER 2 DONE", scale=2, color=(0, 150, 255)) miss_x = (Constants.GAMEWIDTH - miss_label.get_width()) / 2 miss_y = (Constants.GAMEHEIGHT + miss_label.get_height()) / 2 self.screen.blit(miss_label, (miss_x, miss_y)) else: self.show_miss = 0 # Click to start indicator if self.timer and gameTime == -1: timer_label = self.text.get_label("Click to begin...", scale=2, color=(0, 255, 255)) timer_x = (Constants.GAMEWIDTH - timer_label.get_width()) / 2 timer_y = (Constants.GAMEHEIGHT - timer_label.get_height()) / 2 self.screen.blit(timer_label, (timer_x, timer_y)) # Time's up indicator if endGame: winner = "" if (self.time_out and self.turn % 2): winner = "YOU PLAY BETTER THAN CXK" elif (self.time_out and self.turn % 2 == 0): winner = "YOU PALY AS GOOD AS CXK" elif (self.tot_stone == 0): if (self.turn % 2): winner = "YOU PLAY BETTER THAN CXK" else: winner = "YOU PALY AS GOOD AS CXK" timer_label_1 = self.text.get_label(winner, scale=2, color=(0, 150, 255)) timer_label_2 = self.text.get_label("Press space to restart...", scale=2, color=(0, 150, 255)) if (self.win_show == False): self.win_show = True else: if (winner == "YOU PLAY BETTER THAN CXK"): self.screen.blit(self.imagea, (150, 70)) else: self.screen.blit(self.imageb2, (150, 70)) if (self.victory_play == False): self.victory_play = True pygame.mixer.music.load("assets/cxkwin.wav") pygame.mixer.music.play() timer_x_1 = (Constants.GAMEWIDTH - timer_label_1.get_width()) / 2 timer_x_2 = (Constants.GAMEWIDTH - timer_label_2.get_width()) / 2 timer_y_1 = (Constants.GAMEHEIGHT / 2) - timer_label_1.get_height() timer_y_2 = (Constants.GAMEHEIGHT / 2) self.screen.blit(timer_label_1, (timer_x_1, timer_y_1 + 70)) self.screen.blit(timer_label_2, (timer_x_2, timer_y_2 + 70)) if (self.back_on == False): self.screen.blit(self.i5, (120, 600)) else: self.screen.blit(self.i51, (120, 600))
def sprites_clicked(self, _): for i in self.clickeableGroup: i.clicked(mouse.get_pos())
def main(): pre_time_left = None result = None time_need_begin = None game_end = None game_begin = None budget_need = True Ingame_enm_cards = [] global Card_List, select_card, card, budget, prev_diff, Tower_List, Other_Towers, InGameCards pygame.init() Clash_Font = pygame.font.SysFont("Chalkduster", 25) Clash_Font1 = pygame.font.SysFont("Chalkduster", 30) Clash_Font2 = pygame.font.SysFont("Chalkduster", 18) windowWidth = 360 windowHeight = 640 Giant = Card("GiantCard copy.png") Giant.id = 1 Witch = Card("WitchCard copy.png") Witch.id = 2 Fireball = Card("FireballCard copy.png") Fireball.id = 4 Wizard = Card("WizardCard copy.png") Wizard.id = 3 Bomber = Card("BomberCard copy.png") Bomber.id = 5 Balloon = Card("BalloonCard copy.png") Balloon.id = 6 Archer = Card("archers copy.png") Archer.id = 7 Lava = Card("LavaHoundCard copy.png") Lava.id = 8 Main_Tower = Tower("main_tower.png") Main_Tower.id = 1 Side_Tower1 = Tower("side_tower.png") Side_Tower1.id = 2 Side_Tower2 = Tower("side_tower.png") Side_Tower2.id = 3 Tower_List.extend([Main_Tower, Side_Tower1, Side_Tower2]) Enm_Main_Tower = Tower("tower2.png") Enm_Main_Tower.id = 1 Enm_Side_Tower1 = Tower("tower1.png") Enm_Side_Tower1.id = 2 Enm_Side_Tower2 = Tower("tower1.png") Enm_Side_Tower2.id = 3 Other_Towers.extend([Enm_Main_Tower, Enm_Side_Tower1, Enm_Side_Tower2]) enm_cards = random_cards(Giant, Witch, Wizard, Fireball, Archer, Bomber, Balloon) screen = pygame.display.set_mode((windowWidth, windowHeight)) while select_card: lable = Clash_Font1.render("Choose Your Cards", True, (255, 215, 0)) screen.fill((255, 255, 255)) screen.blit(lable, (17, 100)) get_event(Giant, Witch, Wizard, Fireball, Archer, Bomber, Balloon) screen.blit(Giant.picture, (25, 220)) screen.blit(Wizard.picture, (105, 220)) screen.blit(Witch.picture, (185, 220)) screen.blit(Fireball.picture, (265, 220)) screen.blit(Archer.picture, (70, 360)) screen.blit(Balloon.picture, (150, 360)) screen.blit(Bomber.picture, (230, 360)) if Giant in Card_List: screen.blit(pygame.image.load("CheckMark.png"), (45, 190)) if Wizard in Card_List: screen.blit(pygame.image.load("CheckMark.png"), (120, 190)) if Witch in Card_List: screen.blit(pygame.image.load("CheckMark.png"), (200, 190)) if Fireball in Card_List: screen.blit(pygame.image.load("CheckMark.png"), (280, 190)) if Archer in Card_List: screen.blit(pygame.image.load("CheckMark.png"), (88, 330)) if Balloon in Card_List: screen.blit(pygame.image.load("CheckMark.png"), (165, 330)) if Bomber in Card_List: screen.blit(pygame.image.load("CheckMark.png"), (245, 330)) if not (130 < pygame.mouse.get_pos()[0] < 230 and 500 < pygame.mouse.get_pos()[1] < 550 and pygame.mouse.get_pressed()[0]): pygame.draw.rect(screen, (0, 255, 0), (130, 500, 100, 50)) elif 130 < pygame.mouse.get_pos()[0] < 230 and 500 < pygame.mouse.get_pos()[1] < 550 and \ pygame.mouse.get_pressed()[0]: pygame.draw.rect(screen, (0, 200, 0), (130, 500, 100, 50)) lable = Clash_Font2.render("Ready", True, (0, 0, 0)) screen.blit(lable, (150, 510)) pygame.display.update() intial() game_begin = time.time() while True: game_end = time.time() time_left = 180 - int(game_end - game_begin) if time_left > 30: if time_left % 60 < 10: lable = Clash_Font.render( str(time_left // 60) + ':' + '0' + str(time_left % 60), True, (255, 255, 255)) else: lable = Clash_Font.render( str(time_left // 60) + ':' + str(time_left % 60), True, (255, 255, 255)) else: if time_left % 60 < 10: lable = Clash_Font.render( str(time_left // 60) + ':' + '0' + str(time_left % 60), True, (255, 0, 0)) else: lable = Clash_Font.render( str(time_left // 60) + ':' + str(time_left % 60), True, (255, 0, 0)) if Main_Tower not in Tower_List: result = -1 break if Enm_Main_Tower not in Other_Towers: result = 1 break if int(game_end - game_begin) == 180: if len(Other_Towers) > len(Tower_List): result = -1 elif len(Other_Towers) == len(Tower_List): result = 0 elif len(Other_Towers) < len(Tower_List): result = 1 break if time_left % 6 == 0 and add_enemy(time_left, pre_time_left): enemy = new_enemy(enm_cards) Ingame_enm_cards.append(enemy) pre_time_left = time_left main_get_event() screen.fill((255, 255, 255)) screen.blit(pygame.image.load("background.jpg"), (0, 0)) screen.blit(lable, (300, 10)) ShowCards(Card_List, screen, Ingame_enm_cards) if budget_need and budget != 10: time_need_begin = time.time() budget_need = False budget_need = deposit(time_need_begin) if m.get_pressed()[0] and m.get_pos()[1] > 400 and not card: card = chosen_card(m.get_pos(), Card_List) if card: card.set_position(m.get_pos()) for ingamecard in InGameCards: in_range_tower = in_range(ingamecard, Other_Towers) in_range_enmy = in_range(ingamecard, Ingame_enm_cards) if in_range_tower: closest_distance = (640**2 + 360**2)**0.5 for tower in in_range_tower: distance = (((tower.position[0] - tower.size[0] / 2) - (ingamecard.position[0] - 20))**2 + ((tower.position[1] - tower.size[1] / 2) - (ingamecard.position[1] - 23.5))**2)**0.5 if distance < closest_distance: closest_tower = tower closest_distance = distance ingamecard.attack(closest_tower) elif in_range_enmy and ingamecard.att_status != 'building': closest_distance = (640**2 + 360**2)**0.5 for enemy in in_range_enmy: distance = (((enemy.position[0] - 20) - (ingamecard.position[0] - 20))**2 + ((enemy.position[1] - 23.5) - (ingamecard.position[1] - 23.5))**2)**0.5 if distance < closest_distance: closest_enemy = enemy closest_distance = distance ingamecard.attack(closest_enemy) else: ingamecard.move() pygame.display.update() while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if result == -1: screen.fill((255, 0, 0)) lable = Clash_Font1.render("You lost", True, (0, 0, 0)) screen.blit(lable, (100, 300)) if result == 1: screen.fill((0, 255, 0)) lable = Clash_Font1.render("You Win", True, (0, 0, 0)) screen.blit(lable, (100, 300)) if result == 0: screen.fill((255, 255, 255)) lable = Clash_Font1.render("Draw", True, (0, 0, 0)) screen.blit(lable, (130, 300)) pygame.display.update()
def mouse_on_button(self): mx, my = get_pos() if self.rect.x < mx and self.rect.x + self.PL_W > mx and self.rect.y < my and self.rect.y + self.PL_H > my: return 1 else: return 0
def show(self, name, client, order): init() self.background = image.load('background.png') self.background = transform.scale(self.background, (1000, 800)) self.window_width, self.window_height = 1000, 800 self.main_window = display.set_mode( (self.window_width, self.window_height)) self.clock = time.Clock() self.black = (0, 0, 0) self.red = (255, 0, 0) self.gray = (100, 100, 100) self.white = (255, 255, 255) self.who_go = 0 # even means red goes first, old means black goes first self.first_click_coor = [] self.start = False self.load = False self.first_click = True self.mouse_up = False self.hui_yi_bu = False self.temp = Setting.coors_plate self.coors_chess = Setting.coors_chess self.legal_move = Setting.legal_move self.coors_plate = [] self.c_coors_plate = [] self.jiang_shuai = [] self.chess = 0 self.over = 0 self.record = [0, 0, 0, 0] self.mouse1 = [] self.mouse2 = [] self.name = name self.client = client self.order = order self.new_game(self.order) while True: self.main_window.blit(self.background, (0, 0)) self.Mouse = mouse.get_pos() self.click = mouse.get_pressed() self.coors = [0, 32, 0, 0, 0] self.coors_all = [[], []] self.non_chess_coors = [] for i, row in enumerate(self.coors_plate): self.coors[0] = 37 for ii, col in enumerate(row): self.coors[2], self.coors[3] = i, ii # red if col == 1010 or col == 1011 or col == 1020 or col == 1021: self.blit_chess('red', 'ju', self.coors) elif col == col == 2010 or col == 2011 or col == 2020 or col == 2021: self.blit_chess('red', 'ma', self.coors) elif col == 3010 or col == 3011 or col == 3020 or col == 3021: self.blit_chess('red', 'xiang', self.coors) elif col == col == 4010 or col == 4011 or col == 4020 or col == 4021: self.blit_chess('red', 'shi', self.coors) elif col == 5000 or col == 5001: self.blit_chess('red', 'shuai', self.coors) elif col == col == 6010 or col == 6011 or col == 6020 or col == 6021: self.blit_chess('red', 'pao', self.coors) elif col == 7010 or col == 7011 or col == 7020 or col == 7021 or col == 7030\ or col == 7031 or col == 7040 or col == 7041 or col == 7050 or col == 7051: self.blit_chess('red', 'bing', self.coors) # black elif col == 1110 or col == 1111 or col == 1120 or col == 1121: self.blit_chess('black', 'ju', self.coors) elif col == 2110 or col == 2111 or col == 2120 or col == 2121: self.blit_chess('black', 'ma', self.coors) elif col == 3110 or col == 3111 or col == 3120 or col == 3121: self.blit_chess('black', 'xiang', self.coors) elif col == 4110 or col == 4111 or col == 4120 or col == 4121: self.blit_chess('black', 'shi', self.coors) elif col == 5100 or col == 5101: self.blit_chess('black', 'jiang', self.coors) elif col == 6110 or col == 6111 or col == 6120 or col == 6121: self.blit_chess('black', 'pao', self.coors) elif col == 7110 or col == 7111 or col == 7120 or col == 7121 or col == 7130 \ or col == 7131 or col == 7140 or col == 7141 or col == 7150 or col == 7151: self.blit_chess('black', 'bing', self.coors) else: self.non_chess_coors.append(self.coors.copy()) self.coors[0] += 84 self.coors[1] += 75 self.show_all_selected() # 新游戏 self.display_button(900, 90, '新游戏', 30, 'new_game') # 储存游戏 self.display_button(900, 172, '存档', 30, 'save_game') # 加载游戏 self.display_button(900, 633, '读档', 30, 'load_game') # 悔一步 self.display_button(900, 407, '悔一步', 30, 'hui_qi') # 显示回合 if self.start or self.load: if self.who_go % 2 == 0: self.text_display(self.main_window, self.red, '对方回合', 30, [900, 717], 'simhei') else: self.text_display(self.main_window, self.black, '您的回合', 30, [900, 717], 'simhei') if self.start or self.load: self.over = self.game_over() if self.over == 1: self.text_display( self.main_window, self.black, '游戏结束', 100, [self.window_width // 2, self.window_height // 2], 'simhei') self.mouse_up = False for Event in event.get(): if Event.type == QUIT: if self.over == 1: send_msg = {'type': 'exit', 'name': self.name} send_json = json.dumps(send_msg) self.client.send(send_json.encode()) quit() break else: send_msg = {'type': 'quit', 'name': self.name} send_json = json.dumps(send_msg) self.client.send(send_json.encode()) quit() break if Event.type == MOUSEBUTTONUP: self.mouse_up = True if 385 > self.Mouse[ 1] or 425 < self.Mouse[1] and self.Mouse[0] < 800: if self.who_go % 2 == 1 and self.over != 1: self.click_chess( 1 ) # eg. chess = [709, 707, 9, 8] - x, y, row, col if Event.type == USEREVENT + 1: if self.who_go % 2 == 1 and self.over != 1: self.voice_control( 1) # eg. chess = [709, 707, 9, 8] - x, y, row, col if Event.type == USEREVENT + 2: if self.over == 1: send_msg = {'type': 'exit', 'name': self.name} send_json = json.dumps(send_msg) self.client.send(send_json.encode()) quit() break else: send_msg = {'type': 'quit', 'name': self.name} send_json = json.dumps(send_msg) self.client.send(send_json.encode()) quit() break if Event.type == USEREVENT + 7: self.voice_control(0) if Event.type == USEREVENT + 8: quit() break if Event.type == USEREVENT + 9: self.Mouse = self.mouse1 self.click_chess(0) self.Mouse = self.mouse2 self.click_chess(0) else: display.update() self.clock.tick() continue break
def main(): time_need_begin = None game_end = None game_begin = None budget_need = True global Card_List, select_card, card, budget, prev_diff, Tower_List, Other_Towers InGameCards = [] pygame.init() Clash_Font = pygame.font.SysFont("Chalkduster", 25) Clash_Font1 = pygame.font.SysFont("Chalkduster", 30) Clash_Font2 = pygame.font.SysFont("Chalkduster", 18) windowWidth = 360 windowHeight = 640 Giant = Card("GiantCard copy.png") Giant.id = 1 Witch = Card("WitchCard copy.png") Witch.id = 2 Fireball = Card("FireballCard copy.png") Fireball.id = 4 Wizard = Card("WizardCard copy.png") Wizard.id = 3 Bomber = Card("BomberCard copy.png") Bomber.id = 5 Balloon = Card("BalloonCard copy.png") Balloon.id = 6 Archer = Card("archers copy.png") Archer.id = 7 Lava = Card("LavaHoundCard copy.png") Lava.id = 8 Main_Tower = Tower("main_tower.png") Main_Tower.id = 1 Side_Tower1 = Tower("side_tower.png") Side_Tower1.id = 2 Side_Tower2 = Tower("side_tower.png") Side_Tower2.id = 3 Tower_List.extend([Main_Tower, Side_Tower1, Side_Tower2]) Enm_Main_Tower = Tower("tower2.png") Enm_Main_Tower.id = 1 Enm_Side_Tower1 = Tower("tower1.png") Enm_Side_Tower1.id = 2 Enm_Side_Tower2 = Tower("tower1.png") Enm_Side_Tower2.id = 3 Other_Towers.extend([Enm_Main_Tower, Enm_Side_Tower1, Enm_Side_Tower2]) screen = pygame.display.set_mode((windowWidth, windowHeight)) while select_card: lable = Clash_Font1.render("Choose Your Cards", True, (255, 215, 0)) screen.fill((255, 255, 255)) screen.blit(lable, (17, 100)) get_event(Giant, Witch, Wizard, Fireball, Archer, Bomber, Balloon) screen.blit(Giant.picture, (25, 220)) screen.blit(Wizard.picture, (105, 220)) screen.blit(Witch.picture, (185, 220)) screen.blit(Fireball.picture, (265, 220)) screen.blit(Archer.picture, (70, 360)) screen.blit(Balloon.picture, (150, 360)) screen.blit(Bomber.picture, (230, 360)) if Giant in Card_List: screen.blit(pygame.image.load("CheckMark.png"), (45, 190)) if Wizard in Card_List: screen.blit(pygame.image.load("CheckMark.png"), (120, 190)) if Witch in Card_List: screen.blit(pygame.image.load("CheckMark.png"), (200, 190)) if Fireball in Card_List: screen.blit(pygame.image.load("CheckMark.png"), (280, 190)) if Archer in Card_List: screen.blit(pygame.image.load("CheckMark.png"), (88, 330)) if Balloon in Card_List: screen.blit(pygame.image.load("CheckMark.png"), (165, 330)) if Bomber in Card_List: screen.blit(pygame.image.load("CheckMark.png"), (245, 330)) if not (130 < pygame.mouse.get_pos()[0] < 230 and 500 < pygame.mouse.get_pos()[1] < 550 and pygame.mouse.get_pressed()[0]): pygame.draw.rect(screen, (0, 255, 0), (130, 500, 100, 50)) elif 130 < pygame.mouse.get_pos()[0] < 230 and 500 < pygame.mouse.get_pos()[1] < 550 and \ pygame.mouse.get_pressed()[0]: pygame.draw.rect(screen, (0, 200, 0), (130, 500, 100, 50)) lable = Clash_Font2.render("Ready", True, (0, 0, 0)) screen.blit(lable, (150, 510)) pygame.display.update() intial() game_begin = time.time() while True: game_end = time.time() time_left = 180 - int(game_end - game_begin) if time_left > 30: if time_left % 60 < 10: lable = Clash_Font.render( str(time_left // 60) + ':' + '0' + str(time_left % 60), True, (255, 255, 255)) else: lable = Clash_Font.render( str(time_left // 60) + ':' + str(time_left % 60), True, (255, 255, 255)) else: if time_left % 60 < 10: lable = Clash_Font.render( str(time_left // 60) + ':' + '0' + str(time_left % 60), True, (255, 0, 0)) else: lable = Clash_Font.render( str(time_left // 60) + ':' + str(time_left % 60), True, (255, 0, 0)) if int(game_end - game_begin) == 180: break main_get_event() screen.fill((255, 255, 255)) screen.blit(pygame.image.load("background.jpg"), (0, 0)) screen.blit(lable, (300, 10)) ShowCards(Card_List, screen) if budget_need and budget != 10: time_need_begin = time.time() budget_need = False budget_need = deposit(time_need_begin) if m.get_pressed()[0] and m.get_pos()[1] > 400 and not card: card = chosen_card(m.get_pos(), Card_List) if card: card.set_position(m.get_pos()) pygame.display.update()
# Update events and keyboard events events = pg.event.get() keys = pg.key.get_pressed() # Check if we need to exit check_for_window_exit(events) check_for_key_exit(keys) # Check if we need to reset the robot position check_for_reset() # Inform the robot of the keys robotObject.update(keys) # Find the mouse position mouseRel = mouse.get_pos() # Draw the robot's path robotObject.path() # Fill the screen with black to start screen.fill(black) # Fill the screen with the background image screen.blit(Constants.backgroundImage, (0, 0)) # Add all our data add_text("Paths Length: " + str(len(robotObject.paths))) add_text("Robot Position: " + str_list(round_position((robotObject.x, robotObject.y)))) add_text("Odometry Position: " +
pygame.display.set_caption("Space Zoom") WIDTH, HEIGHT = 1280, 720 screen = pygame.display.set_mode( (WIDTH, HEIGHT)) # create a surface on screen that has the size of 1280 x 720 pygame.mouse.set_visible(True) stars = [] for x in range(100): stars.append([[WIDTH / 2, HEIGHT / 2], random.random() * 2 * math.pi]) running = True while (running): speed = mouse.get_pos()[0] / WIDTH for x in range(len(stars)): star = stars[x] draw.ellipse(screen, pygame.Color(255, 255, 255), pygame.Rect(star[0][0], star[0][1], 1, 1)) star = [[ star[0][0] - speed * math.cos(star[1]), star[0][1] + speed * math.sin(star[1]) ], star[1]] if (star[0][0] <= 0 or star[0][0] >= WIDTH or star[0][1] <= 0 or star[0][1] >= HEIGHT): star = [[WIDTH / 2, HEIGHT / 2], random.random() * 2 * math.pi]
def draw_mouse_coordinates(destination_surface, w=None, h=None, color=(255,0,0)): if w is None or h is None: w = 64 h = 16 pos = EwFont(pymo.get_pos()[0]+16, pymo.get_pos()[1], w, h, None, str((pymo.get_pos()[0], pymo.get_pos()[1])), color) pos.draw(destination_surface)
def move(self): self.x,self.y = mouse.get_pos()
hui_yi_bu = False temp = Setting.coors_plate coors_chess = Setting.coors_chess legal_move = Setting.legal_move coors_plate = [] c_coors_plate = [] jiang_shuai = [] over = 0 record = [0, 0, 0, 0] record_thread = threading.Thread(target=record_voice) record_thread.setDaemon(True) record_thread.start() while True: main_window.blit(background, (0, 0)) Mouse = mouse.get_pos() click = mouse.get_pressed() coors = [0, 32, 0, 0, 0] coors_all = [[], []] non_chess_coors = [] for i, row in enumerate(coors_plate): coors[0] = 37 for ii, col in enumerate(row): coors[2], coors[3] = i, ii # red if col == 1010 or col == 1011 or col == 1020 or col == 1021: blit_chess('red', 'ju', coors) elif col == col == 2010 or col == 2011 or col == 2020 or col == 2021: blit_chess('red', 'ma', coors) elif col == 3010 or col == 3011 or col == 3020 or col == 3021:
def is_hovered(self): mouse_pos = mouse.get_pos() return ( self.rect.x <= mouse_pos[0] <= self.rect.x + self.rect.width and self.rect.y <= mouse_pos[1] <= self.rect.y + self.rect.height )
#remove duplicates from the list of triangles triangles = list(set(triangles)) print 'triangle filter complete' print 'Time : ', time.time() - start_time print len(triangles), 'triangles' counter = 0 running = True toggle = False lock = True showVertices = True while running: mousepos = get_pos() vecmousepos = Vector(mousepos[0], mousepos[1], 0) waytogo = vecmousepos - (controlpoints[0].pos * scale) centre = [ controlpoints[0].pos.x, controlpoints[0].pos.y, controlpoints[0].pos.z ] for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == KEYDOWN: if event.key == K_ESCAPE: running = False elif event.key == K_RCTRL: toggle = not toggle elif event.key == K_RSHIFT:
def respond(self): mouse_buttons = mouse.get_pressed() mouse_position = mouse.get_pos() if mouse_buttons[0]: self.actor.target = Vector(*mouse_position)
def update(cls): cls.clock.tick(60) events = event.get( [KEYDOWN, MOUSEBUTTONDOWN, MOUSEBUTTONUP, QUIT, MOUSEMOTION]) event.clear() for e in events: if e.type == QUIT or (e.type == KEYDOWN and e.key == K_ESCAPE): EventHandler.trigger('salir', 'engine', {'mensaje': 'normal'}) elif e.type == KEYDOWN and not cls.locked: if e.key in (K_KP_ENTER, K_KP_EQUALS): EventHandler.trigger('Fin', cls.origin) elif e.key == K_BACKSPACE: EventHandler.trigger('BackSpace', cls.origin) elif e.key == K_UP: EventHandler.trigger('Arrow', cls.origin, { 'word': 'arriba', 'delta': -1 }) elif e.key == K_DOWN: EventHandler.trigger('Arrow', cls.origin, { 'word': 'abajo', 'delta': +1 }) else: name = key.name(e.key).strip('[]') if len( name ) == 1: # single character, excludes "space" and things like that. if name == '.': # bc there's not other way to identifying it. EventHandler.trigger('Key', cls.origin, {'value': '.'}) elif name.isdigit(): EventHandler.trigger('Key', cls.origin, {'value': name}) elif name.isalpha(): if e.mod & KMOD_LSHIFT or e.mod & KMOD_RSHIFT: name = name.capitalize() EventHandler.trigger('Typed', cls.origin, {'value': name}) elif name == 'space': EventHandler.trigger('Typed', cls.origin, {'value': ' '}) elif e.type == MOUSEBUTTONDOWN: widgets = [ i for i in cls.contents.sprites() if i.rect.collidepoint(e.pos) ] widgets.sort(key=lambda o: o.layer, reverse=True) if not cls.locked or widgets[0] is cls.the_one: cls.origin = widgets[0].on_mousebuttondown(e) else: cls.the_one.blink() elif e.type == MOUSEBUTTONUP: widgets = [ i for i in cls.contents.sprites() if i.rect.collidepoint(e.pos) ] widgets.sort(key=lambda o: o.layer, reverse=True) widgets[0].on_mousebuttonup(e) elif e.type == MOUSEMOTION: x, y = e.pos for widget in cls.contents.sprites(): if widget.rect.collidepoint((x, y)): widget.on_mousemotion(e.rel) x, y = mouse.get_pos() for widget in cls.contents.sprites(): if widget.rect.collidepoint( (x, y)) and (not cls.locked or widget is cls.the_one): widget.on_mouseover() cls.contents.update()
def draw(self, clicked, hit, miss): is_end = False this_time = None if self.timer_start != 0: remain = self.timer - (time.get_ticks() - self.timer_start) / 1000 this_time = remain if remain <= 0: is_end = True if this_time is None and self.timer is not None: this_time = 0 if (self.fixed_timer // 2) < this_time: self.screen.blit(self.img_bg, (0, 0)) elif (self.fixed_timer // 2) > this_time > (self.fixed_timer // 4): self.screen.blit(self.img_sunset, (0, 0)) else: self.screen.blit(self.img_night, (0, 0)) for position in self.holes: self.screen.blit(self.img_hole, position) for mole in self.moles: holes = [] for f in self.holes: if f not in self.used_holes: holes.append(f) mole_display = mole.do_display(holes, self.score.level, not is_end) if len(mole_display) == 2: self.used_holes.remove(mole_display[1]) if len(mole_display) == 3: self.used_holes.append(mole_display[1]) if mole_display[0]: pos = mole.get_hole_pos(not is_end) if mole.hit != False: self.screen.blit(mole.img_hit, pos) else: self.screen.blit(mole.img_normal, pos) hammer_x, hammer_y = mouse.get_pos() hammer_x -= 40 hammer_y -= 50 if clicked: self.screen.blit(self.img_hammer_hit, (hammer_x, hammer_y)) else: self.screen.blit(self.img_hammer_norm, (hammer_x, hammer_y)) data = self.score.work_text(timer=this_time, size=1) # score after finish self.screen.blit(data, (5, 5)) if is_end == False: if hit == True: # got him :) self.show_hit = time.get_ticks() if self.show_hit > 0 and time.get_ticks() - self.show_hit <= 500: self.screen.blit( self.img_bang, (self.bang_position[0] - 50, self.bang_position[1] - 50)) else: self.show_hit = 0 if miss == True: # missed him :( self.show_miss = time.get_ticks() if self.show_miss > 0 and time.get_ticks() - self.show_miss <= 250: self.screen.blit( self.img_oops, (self.oops_position[0] - 50, self.oops_position[1] - 50)) else: self.show_miss = 0 if self.timer and this_time == 0: self.screen.blit(self.img_click, (0, 0)) if self.timer and is_end: # time's up self.screen.blit(self.img_space, (0, 0)) data = self.score.work_text(timer=this_time, size=1.5) self.screen.blit(data, (5, 5))
def drawButton(self, destSurf, pos, size, colors, buttonText, buttonTextSize, buttonFunction=None): """ Utility function that draws a button to the screen **Args**: *destSurf*: Surface The surface that the button will be drawn to *pos*: Tuple (int, int) The (x,y) position of the button. This point corresponds to the top-left corner of the button. *size*: Tuple (int, int) The (width, height) of the button to be drawn. *colors*: Tuple (Color, Color) The first member of the tuple is the color of the button, and the second member is the color of the button while it is being hovered over. These colors can be given as pygame colors, triples of RGB values, or 4-tuples of RGBA values if transparency is desired *buttonText*: The text to be rendered at the center of the button *buttonTextSize*: The size of the text to be rendered *buttonFunction*: A function to call while the button is pressed **Preconditions**: None. **Postconditions**: None. **Returns**: None. """ t_font = font.SysFont('lucidaconsole', buttonTextSize) text = t_font.render(str(buttonText), True, (0, 0, 0)) button = surface.Surface(size, constants.SRCALPHA) offset = destSurf.get_abs_offset() #see if mouse is within the area of our button mousePos = mouse.get_pos() if mousePos[0] > pos[0] + offset[0] and mousePos[0] < pos[0] + size[ 0] + offset[0] and mousePos[1] > pos[1] + offset[ 1] and mousePos[1] < pos[1] + size[1] + offset[1]: button.fill(colors[1]) #mouse is in the button, so it may click the button and run its function if mouse.get_pressed( )[0] and buttonFunction != None and not self.buttonIsClicked: buttonFunction() self.buttonIsClicked = True elif not mouse.get_pressed()[0] and self.buttonIsClicked: self.buttonIsClicked = False else: #mouse isn't in the button button.fill(colors[0]) #put button onto the screen, then text onto the screen centered over the button destSurf.blits([(button, pos), (text, (pos[0] + size[0] / 2 - text.get_width() / 2, pos[1] + size[1] / 2 - text.get_height() / 2)) ])