def Draw(self, screen): pygame.draw.rect(screen, self.color, pygame.Rect(self.x, self.y, self.width, self.height), 0)
def recreate_ui(self): self.ui_manager.set_window_resolution(self.options.resolution) self.ui_manager.clear_and_reset() self.background_surface = pygame.Surface(self.options.resolution) self.background_surface.fill( self.ui_manager.get_theme().get_colour('dark_bg')) self.test_button = UIButton( pygame.Rect((int(self.options.resolution[0] / 2), int(self.options.resolution[1] * 0.90)), (100, 40)), '', self.ui_manager, tool_tip_text="<font face=fira_code color=normal_text size=2>" "<b><u>Test Tool Tip</u></b>" "<br><br>" "A little <i>test</i> of the " "<font color=#FFFFFF><b>tool tip</b></font>" " functionality." "<br><br>" "Unleash the Kraken!" "</font>", object_id='#hover_me_button') self.test_button_2 = UIButton(pygame.Rect( (int(self.options.resolution[0] / 3), int(self.options.resolution[1] * 0.90)), (100, 40)), 'EVERYTHING', self.ui_manager, object_id='#everything_button') self.test_button_3 = UIButton(pygame.Rect( (int(self.options.resolution[0] / 6), int(self.options.resolution[1] * 0.90)), (100, 40)), 'Scaling?', self.ui_manager, object_id='#scaling_button') self.test_slider = UIHorizontalSlider(pygame.Rect( (int(self.options.resolution[0] / 2), int(self.options.resolution[1] * 0.70)), (240, 25)), 25.0, (0.0, 100.0), self.ui_manager, object_id='#cool_slider') self.test_text_entry = UITextEntryLine(pygame.Rect( (int(self.options.resolution[0] / 2), int(self.options.resolution[1] * 0.50)), (200, -1)), self.ui_manager, object_id='#main_text_entry') current_resolution_string = (str(self.options.resolution[0]) + 'x' + str(self.options.resolution[1])) self.test_drop_down = UIDropDownMenu( ['640x480', '800x600', '1024x768'], current_resolution_string, pygame.Rect((int(self.options.resolution[0] / 2), int(self.options.resolution[1] * 0.3)), (200, 25)), self.ui_manager) self.test_drop_down_2 = UIDropDownMenu( ['Another', 'drop down', 'menu', 'testing', 'overlaps'], 'Another', pygame.Rect((int(self.options.resolution[0] / 2), int(self.options.resolution[1] * 0.25)), (200, 25)), self.ui_manager) self.panel = UIPanel(pygame.Rect(50, 50, 200, 300), starting_layer_height=4, manager=self.ui_manager) UIButton(pygame.Rect(10, 10, 174, 30), 'Panel Button', manager=self.ui_manager, container=self.panel) UISelectionList(pygame.Rect(10, 50, 174, 200), item_list=[ 'Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5', 'Item 6', 'Item 7', 'Item 8', 'Item 9', 'Item 10', 'Item 11', 'Item 12', 'Item 13', 'Item 14', 'Item 15', 'Item 16', 'Item 17', 'Item 18', 'Item 19', 'Item 20' ], manager=self.ui_manager, container=self.panel, allow_multi_select=True) self.fps_counter = UILabel(pygame.Rect( self.options.resolution[0] - 250, 20, 230, 44), "FPS: 0", self.ui_manager, object_id='#fps_counter') self.frame_timer = UILabel(pygame.Rect( self.options.resolution[0] - 250, 64, 230, 24), "Frame time: 0", self.ui_manager, object_id='#frame_timer') self.disable_toggle = UIButton(pygame.Rect( (int(self.options.resolution[0] * 0.85), int(self.options.resolution[1] * 0.90)), (100, 30)), 'Disable', self.ui_manager, object_id='#disable_button') self.hide_toggle = UIButton(pygame.Rect( (int(self.options.resolution[0] * 0.85), int(self.options.resolution[1] * 0.85)), (100, 30)), 'Hide', self.ui_manager, object_id='#hide_button')
def __init__(self, rect, ui_manager): super().__init__(rect, ui_manager, window_display_title='Everything Container', object_id='#everything_window', resizable=True) self.test_slider = UIHorizontalSlider(pygame.Rect( (int(self.rect.width / 2), int(self.rect.height * 0.70)), (240, 25)), 50.0, (0.0, 100.0), self.ui_manager, container=self) self.slider_label = UILabel( pygame.Rect( (int(self.rect.width / 2) + 250, int(self.rect.height * 0.70)), (27, 25)), str(int(self.test_slider.get_current_value())), self.ui_manager, container=self) self.test_text_entry = UITextEntryLine(pygame.Rect( (int(self.rect.width / 2), int(self.rect.height * 0.50)), (200, -1)), self.ui_manager, container=self) self.test_text_entry.set_forbidden_characters('numbers') current_resolution_string = 'Item 1' self.test_drop_down_menu = UIDropDownMenu( [ 'Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5', 'Item 6', 'Item 7', 'Item 8', 'Item 9', 'Item 10', 'Item 11', 'Item 12', 'Item 13', 'Item 14', 'Item 15', 'Item 16', 'Item 17', 'Item 18', 'Item 19', 'Item 20', 'Item 21', 'Item 22', 'Item 23', 'Item 24', 'Item 25', 'Item 26', 'Item 27', 'Item 28', 'Item 29', 'Item 30' ], current_resolution_string, pygame.Rect( (int(self.rect.width / 2), int(self.rect.height * 0.3)), (200, 25)), self.ui_manager, container=self) self.health_bar = UIScreenSpaceHealthBar(pygame.Rect( (int(self.rect.width / 9), int(self.rect.height * 0.7)), (200, 20)), self.ui_manager, container=self) loaded_test_image = pygame.image.load( 'data/images/splat.bmp').convert_alpha() self.test_image = UIImage(pygame.Rect( (int(self.rect.width / 9), int(self.rect.height * 0.3)), loaded_test_image.get_rect().size), loaded_test_image, self.ui_manager, container=self)
def main(): ptlist = [(100, 100), (100, height - 100), (width - 100, height - 100), (width - 100, 100)] freezeimg = pygame.image.load(resource_path("freeze.png")) freezex, freezey = ((width // 4) - 32, (height - 82)) freeze = pygame.Rect((freezex, freezey), (freezex + 64, freezey + 64)) mergeimg = pygame.image.load(resource_path("merge.png")) mergex, mergey = (width - (width // 4) - 32, (height - 82)) merge = pygame.Rect((mergex, mergey), (mergex + 64, mergey + 64)) clock = pygame.time.Clock() global no_of_particles no_of_particles = 2 global score score = 0 global bounce particles = [] bounce = 0 check_bounce = 0 freezeStart = 0 freezeSel = False mergeStart = 0 mergeSel = False size = 10 colour = (255, 0, 0) x = random.randint(100 + size, width - 100 - size) y = random.randint(100 + size, height - 100 - size) particle = Particle(x, y, size, colour) particle.speed = 2.5 particle.angle = random.uniform(0, math.pi * 2) particles.append(particle) for i in range(no_of_particles): particles.append(create_particle()) sel_particle = None while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: (mousex, mousey) = pygame.mouse.get_pos() if freeze.collidepoint((mousex, mousey)) and not freezeSel: freezeStart = pygame.time.get_ticks() / 1000 freezeSel = True particles[0].speed *= 0.5 if merge.collidepoint((mousex, mousey)) and not mergeSel: mergeStart = pygame.time.get_ticks() / 1000 mergeSel = True index = no_of_particles // 2 del (particles[index + 1:]) for p in particles: p.size += int(p.size / 2) sel_particle = findparticle(particles[1:], mousex, mousey) elif event.type == pygame.MOUSEBUTTONUP: sel_particle = None if sel_particle: (mousex, mousey) = pygame.mouse.get_pos() sel_particle.x = mousex sel_particle.y = mousey screen.fill(bgColor) pygame.draw.aalines(screen, fontColor, True, ptlist, 5) if not freezeSel: screen.blit(freezeimg, freeze) if not mergeSel: screen.blit(mergeimg, merge) if int((pygame.time.get_ticks() / 1000) - freezeStart) == 10 and freezeSel: particles[0].speed = 2.5 if (pygame.time.get_ticks() // 1000) - freezeStart <= 20 and freezeSel: updateFtimer(int((pygame.time.get_ticks() / 1000) - freezeStart)) else: freezeStart = 0 freezeSel = False if (pygame.time.get_ticks() // 1000) - mergeStart <= 20 and mergeSel: updateMtimer(int((pygame.time.get_ticks() / 1000) - mergeStart)) else: mergeStart = 0 mergeSel = False update_score() for i, particle in enumerate(particles): particle.move() bounceval = particle.bounce() if i != 0 and bounceval == 1: sleep(1) gameover() bounce += bounceval for particle2 in particles[i + 1:]: collide(particles[0], particle2) particle.display() if bounce != check_bounce: score += 1 if score != 0 and score % 5 == 0: no_of_particles += 1 particles.append(create_particle()) check_bounce = bounce update_score() pygame.display.flip() clock.tick(60) pygame.display.flip()
def __init__(self): self.rect = pygame.Rect(-50, 0, 25, 25)
class BlackjackGame(object): """Represents a single game of blackjack.""" draw_group = pg.sprite.Group() move_animations = pg.sprite.Group() advisor = Advisor(draw_group, move_animations) advisor.active = True advisor_back = prepare.GFX["advisor_back"] advisor_front = prepare.GFX["advisor_front"] advisor_back_dim = prepare.GFX["advisor_back_dim"] advisor_front_dim = prepare.GFX["advisor_front_dim"] font = prepare.FONTS["Saniretro"] result_font = prepare.FONTS["Saniretro"] deal_sounds = [ prepare.SFX[name] for name in ["cardplace{}".format(x) for x in (2, 3, 4)] ] chip_sounds = [ prepare.SFX[name] for name in ["chipsstack{}".format(x) for x in (3, 5, 6)] ] chip_size = (48, 30) screen_rect = pg.Rect((0, 0), prepare.RENDER_SIZE) advisor_active = True def __init__(self, casino_player, player_cash, chips=None, chip_pile=None): self.deck = Deck((20, 100), prepare.CARD_SIZE, 40) self.dealer = Dealer() self.chip_rack = ChipRack((1100, 130), self.chip_size) self.moving_stacks = [] self.casino_player = casino_player self.player = Player(self.chip_size, player_cash, chips, chip_pile) self.labels = self.make_labels() self.current_player_hand = self.player.hands[0] self.quick_bet = 0 self.last_bet = 0 rect = self.advisor_back.get_rect().union( self.advisor_front.get_rect()) self.advisor_button = Button(rect, call=self.toggle_advisor) def make_labels(self): labels_info = [("Drop chips in chip rack", 36, "antiquewhite", 100, { "midtop": (self.chip_rack.rect.centerx, self.chip_rack.rect.bottom + 5) }), ("to make change", 36, "antiquewhite", 100, { "midtop": (self.chip_rack.rect.centerx, self.chip_rack.rect.bottom + 60) }), ("Blackjack Pays 3 to 2", 64, "gold3", 120, { "midtop": (580, 300) }), ("Dealer must draw to 16 and stand on 17", 48, "antiquewhite", 100, { "midtop": (580, 240) })] labels = [] for info in labels_info: label = Label(self.font, info[1], info[0], info[2], info[4], bg=prepare.FELT_GREEN) label.image.set_alpha(info[3]) labels.append(label) return labels def toggle_advisor(self, *args): BlackjackGame.advisor_active = not BlackjackGame.advisor_active def tally_hands(self): """ Calculate result of each player hand and set appropriate flag for each hand. """ if self.dealer.hand.blackjack: for hand in self.player.hands: hand.loser = True elif self.dealer.hand.busted: for hand in self.player.hands: if not hand.busted and not hand.blackjack: hand.winner = True else: d_score = self.dealer.hand.best_score() for hand in self.player.hands: if not hand.busted: p_score = hand.best_score() if p_score == 21 and len(hand.cards) == 2: hand.blackjack = True elif p_score < d_score: hand.loser = True elif p_score == d_score: hand.push = True else: hand.winner = True def pay_out(self): """ Calculate player win amounts, update stats and return chips totalling total win amount. """ cash = 0 for hand in self.player.hands: bet = hand.bet.get_chip_total() self.casino_player.increase("hands played") self.casino_player.increase("total bets", bet) if hand.busted: self.casino_player.increase("busts") self.casino_player.increase("hands lost") elif hand.loser: self.casino_player.increase("hands lost") elif hand.blackjack: cash += int(bet * 2.5) self.casino_player.increase("blackjacks") self.casino_player.increase("hands won") elif hand.winner: cash += bet * 2 self.casino_player.increase("hands won") elif hand.push: cash += bet self.casino_player.increase("pushes") self.casino_player.increase("total winnings", cash) chips = cash_to_chips(cash, self.chip_size) return chips def get_event(self, event): self.advisor_button.get_event(event) def update(self, dt, mouse_pos): self.advisor_button.update(mouse_pos) total_text = "Chip Total: ${}".format( self.player.chip_pile.get_chip_total()) screen = self.screen_rect self.chip_total_label = Label( self.font, 48, total_text, "gold3", {"bottomleft": (screen.left + 3, screen.bottom - 3)}) self.chip_rack.update() if self.advisor_active: self.move_animations.update(dt)
def load(self, fname): tree = xml.parse(fname) if "\\" in fname: fname_path = fname[:fname.rfind("\\") + 1] else: fname_path = "" # Get the root node and all the relevant attributes root = tree.getroot() print("root.attrib = " + str(root.attrib)) if "width" in root.attrib: self.world_width = int(root.attrib["width"]) if "height" in root.attrib: self.world_height = int(root.attrib["height"]) # Get the tilesets for tileset in root.iter('tileset'): if "firstgid" in tileset.attrib and "source" in tileset.attrib: self.tile_sets.append(Tileset(fname_path, tileset.attrib["source"], int(tileset.attrib["firstgid"]))) if self.tile_width == 0: # The first layer -- it'll determine the tile_width & height for me. Usually they're all the same... self.tile_width = self.tile_sets[-1].tile_width self.tile_height = self.tile_sets[-1].tile_height # Get the layers for layer in root.iter("layer"): data = layer.find("data") if data != None: new_layer = [] lines = data.text.split("\n") for line in lines: if len(line) == 0: continue if line[-1] == ",": line = line[:-1] new_row = [] for item in line.split(","): new_row.append(int(item)) new_layer.append(new_row) self.tile_layers.append(new_layer) # Get the objects (including bounding areas) for obj in root.iter("object"): if "x" in obj.attrib and "y" in obj.attrib: x = float(obj.attrib["x"]) y = float(obj.attrib["y"]) w = h = 0 if "width" in obj.attrib and "height" in obj.attrib: w = float(obj.attrib["width"]) h = float(obj.attrib["height"]) props = {} for p in obj.iter("property"): if "name" in p.attrib and "value" in p.attrib: props[p.attrib["name"]] = p.attrib["value"] new_area = Area(pygame.Rect(x, y, w, h), props) if new_area.param_matches({"spawner": None}): # This is an (item) spawning location -- handle it now self.items.append((x, y, int(props["spawner"]))) else: # Add it to the list of all other types of areas. self.areas.append(new_area) # Create a few more attributes self.pixel_width = self.world_width * self.tile_width self.pixel_height = self.world_height * self.tile_height self.create_Brick()
# Boucle infinit pour la surface launched = True while launched: ### Corps du program ### #Passage de la couleur a screen screen.fill(white_color) #Dessin d'une ligne (surface, color, position dep, position arr, bordure) pygame.draw.line(screen, black_color, [10, 10], [100, 100], 5) #Rect(left, top, width, height) rect_form = pygame.Rect(200,200, 150, 200) #Dessin un rectangle (surface, color, ObjRect, bordure) pygame.draw.rect(screen, black_color, rect_form, 5) #Dessin d'un cercle (surface, color, [position du cercle], rayon, bordure) pygame.draw.circle(screen, black_color, [250, 100], 50, 5) #Coordonnée pour poligone coords = [(50, 250), (100, 350), (150, 150)] #Dessin d'un polygone (surface, color, position des points..., bordure) pygame.draw.polygon(screen, black_color, coords, 5) #Affiche image sur la surface blit(img, [coordonnée du point haut gauche de l'image X,Y]) screen.blit(sonicImg, [500, 200]) screen.blit(mushroomImg, [200, 500])
def show(self, screen): self.chunk = self.pos // S relpos = self.pos % S ## print(self.chunk, self.chunk%WORLD_SIZE) tl_land, tl_sea = self.get_surface(self.chunk) tr_land, tr_sea = self.get_surface(self.chunk + (1, 0)) bl_land, bl_sea = self.get_surface(self.chunk + (0, 1)) br_land, br_sea = self.get_surface(self.chunk + (1, 1)) postl = -relpos postr = postl + (S, 0) posbl = postl + (0, S) posbr = postl + (S, S) # screen.blit(tl_sea, postl) screen.blit(tr_sea, postr) screen.blit(bl_sea, posbl) screen.blit(br_sea, posbr) # for cloud in self.clouds: screen.blit(self.game.clouds[cloud.i], (cloud.x, cloud.y)) if parameters.REFLECT: if self.ship and not self.game.storm: screen.blit(self.ship, self.game.ship.img_pos + (0, self.shiph)) if parameters.RAIN_IMPACTS: if self.game.storm and not (self.game.is_winter): rain = self.game.falls ## fx.smokegen.kill_old_elements() #.... fx.smokegen.natural_kill() k = self.game.i % parameters.RAIN_DISTRIBUTIONS for i in range(parameters.RAIN_IMPACTS): coord = rain.impactsx[k][i], rain.impactsy[k][i] fx.smokegen.generate(Vector2(coord)) fx.smokegen.update_physics(-self.game.controlled.velocity) fx.smokegen.draw(screen) # screen.blit(tl_land, postl) screen.blit(tr_land, postr) screen.blit(bl_land, posbl) screen.blit(br_land, posbr) # if parameters.SHOW_GRID: for p in [postl, postr, posbl, posbr]: pygame.draw.rect(screen, (200, 200, 200), pygame.Rect(p, (S, S)), 1) tlrect = pygame.Rect(-relpos, (S, S)) trrect = pygame.Rect(postr, (S, S)) blrect = pygame.Rect(posbl, (S, S)) brrect = pygame.Rect(posbr, (S, S)) points = [(0, 0), (-10, 0), (10, 0)] rects = [(tlrect, self.chunk), (trrect, self.chunk + (1, 0)), (blrect, self.chunk + (0, 1)), (brrect, self.chunk + (1, 1))] collisions = [] for x, y in parameters._COLLISION_POINTS: ## pygame.draw.rect(screen,(0,0,0),pygame.Rect(x,y,2,2)) for r, c in rects: ## pygame.draw.rect(screen,(0,0,0),r) if r.collidepoint((x, y)): chunk = tuple(c % WORLD_SIZE) h = self.saved_chunks[chunk][0][x - r.x, y - r.y] collisions.append(h) return collisions
import pygame as pg TILE_WIDTH = 32 TILE_HEIGHT = 32 SIZE_X_WORLD = 44 SIZE_Y_WORLD = 22 SCREENRECT = pg.Rect(0, 0, TILE_WIDTH * SIZE_X_WORLD, TILE_HEIGHT * SIZE_Y_WORLD) TILES_PATH = "resources/sprites/tiles" PLAYER_WIDTH = 128 PLAYER_HEIGHT = 128
def drawApple(coord): x = coord['x'] * CELLSIZE y = coord['y'] * CELLSIZE appleRect = pygame.Rect(x, y, CELLSIZE, CELLSIZE) pygame.draw.rect(DISPLAYSURF, RED, appleRect)
return grids def convertToPuzzle(grids): puzzle = [[] for x in range(9)] for gridRow in range(0, 3): for grid in range(0, 3): for item in range(0, 9): puzzle[int(item/3)+gridRow*3].append(grids[gridRow][grid][item]) return puzzle """ main loop """ #song1.play(-1) pygame.mixer.music.set_volume(0.1) #pygame.mixer.music.play(-1) while not done: rect0 = pygame.Rect(((1900-exitB.get_rect().width)+20, 0), pygame.Surface.get_size(exitB)) if place == "menu1": screen.blit(bg,(0,0)) rect1 = centreBlit(playB, 0, -150) if rect1.collidepoint(pygame.mouse.get_pos()): if touching == False: hoverS.play() playB = pygame.transform.scale(playB, (250, 250)) touching = True elif touching == True: unhoverS.play() playB = pygame.image.load("playB.png") playB = pygame.transform.scale(playB, (200, 200)) touching = False
def erase_strip_above(draw_player): pygame.draw.rect(screen, color[EMPTY], pygame.Rect(0, 0, width, SQ)) if draw_player: pygame.draw.circle(screen, color[HUMAN], (pygame.mouse.get_pos()[0], SQ // 2), RADIUS) pygame.display.update()
def draw_loading_screen(self): pyg.draw.rect( self.display, consts.WHITE, pyg.Rect(0, 0, self.display.get_width(), self.display.get_height()))
screen.fill((40, 20, 0)) screen.fill((80, 40, 10), (40, 100, 500, 340)) args = { "midtop": (290, 100), "width": 500, "fontname": fontnames[jfontnames], "fontsize": fontsizes[jfontsizes], "owidth": outlines[joutlines], "shadow": shadows[jshadows], "lineheight": lineheights[jlineheights], } ptext.draw(text, **args) layout = ptext.layout(text, **args) word = pointedword(layout, pygame.mouse.get_pos()) if not pygame.Rect(40, 100, 500, 340).collidepoint(pygame.mouse.get_pos()): for line, rect, font in layout: surf = pygame.Surface(rect.size).convert_alpha() surf.fill((255, 255, 255, 40)) screen.blit(surf, rect) info = [ "Controls:", "1: cycle fontsize", "current: %d" % fontsizes[jfontsizes], "2: cycle fontname", "current: %s" % fontnames[jfontnames], "3: cycle outline", "current: %s" % outlines[joutlines], "4: cycle shadow", "current: %s" % (shadows[jshadows],),
WIDTH, HEIGHT = 1920, 900 BACKGROUND_IMAGES = (pygame.transform.scale( pygame.image.load(os.path.join("Background", "space.jpg")), (WIDTH, HEIGHT)), pygame.transform.scale( pygame.image.load( os.path.join("Background", "space2.jpg")), (WIDTH, HEIGHT)), pygame.transform.scale( pygame.image.load( os.path.join("Background", "space3.jpg")), (WIDTH, HEIGHT))) ICON = pygame.image.load(os.path.join("Assets", "icon.png")) FPS = 60 BORDER = pygame.Rect(WIDTH // 2 - 10, 0, 10, HEIGHT) RED_SPACESHIP_WIDTH, RED_SPACESHIP_HEIGHT = 75, 75 BLACK_SPACESHIP_WIDTH, BLACK_SPACESHIP_HEIGHT = 75, 75 RED_SPACESHIP_IMAGE = pygame.transform.rotate( pygame.transform.scale( pygame.image.load(os.path.join("Assets", "red_spaceship.png")), (RED_SPACESHIP_WIDTH, RED_SPACESHIP_HEIGHT)), 90) BLACK_SPACESHIP_IMAGE = pygame.transform.rotate( pygame.transform.scale( pygame.image.load(os.path.join("Assets", "black_spaceship.png")), (BLACK_SPACESHIP_WIDTH, BLACK_SPACESHIP_HEIGHT)), 180) VEL = 5 BULLET_VEL = 10 MAX_BULLETS = 3 P1_SCORE, P2_SCORE = 0, 0 PLAYER1_HIT = pygame.USEREVENT + 1
def __init__(self, x, y, width=300, height=50, color=(200, 200, 255)): self.rect = pygame.Rect(x, y, width, height) #цвет заливки - или переданный параметр, или общий цвет фона self.fill_color = color
def main(): global P1_SCORE, P2_SCORE pygame.mixer.music.unload() soundtrack = os.listdir(r".\Music\SoundTracks")[random.randint(0, 1)] pygame.mixer.music.load(os.path.join("Music", "SoundTracks", soundtrack)) pygame.mixer.music.play(-1, 0.0) red = pygame.Rect(0, HEIGHT // 2 - RED_SPACESHIP_HEIGHT, RED_SPACESHIP_WIDTH, RED_SPACESHIP_HEIGHT) black = pygame.Rect(WIDTH - BLACK_SPACESHIP_WIDTH, HEIGHT // 2 - BLACK_SPACESHIP_HEIGHT, BLACK_SPACESHIP_WIDTH, BLACK_SPACESHIP_HEIGHT) red_bullets = [] black_bullets = [] red_health = 10 black_health = 10 winner_text = "" num = random.randint(0, 2) round_finished = 0 while True: clock.tick(FPS) for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit(0) if event.type == pygame.KEYDOWN: if event.key == pygame.K_LCTRL and len( red_bullets) < MAX_BULLETS: FIRE_SOUND.play() red_bullets.append( pygame.Rect(red.x + red.width, red.y + red.height // 2 - 2, 10, 5)) if event.key == pygame.K_RCTRL and len( black_bullets) < MAX_BULLETS: FIRE_SOUND.play() black_bullets.append( pygame.Rect(black.x, black.y + black.height // 2 - 2, 10, 5)) if event.type == PLAYER1_HIT: red_health -= 1 if event.type == PLAYER2_HIT: black_health -= 1 if red_health <= 0: round_finished = 1 P2_SCORE += 1 winner_text = "Player 2 WINS!!!" elif black_health <= 0: round_finished = 1 P1_SCORE += 1 winner_text = "Player 1 WINS!!!" if len(winner_text) > 0: draw_winner(winner_text) break keys = pygame.key.get_pressed() handle_movement(keys, red, black) handle_bullets(red, black, red_bullets, black_bullets) display_window(red, black, red_bullets, black_bullets, red_health, black_health, round_finished, num) main()
def get_item_bounds(self, item): img = self.item_imgs[item[2]] return pygame.Rect(item[0], item[1], img.get_width(), img.get_height())
def clip(self, clipped_rect): if type(clipped_rect) is dict: self.sheet.set_clip(pygame.Rect(self.get_frame(clipped_rect))) else: self.sheet.set_clip(pygame.Rect(clipped_rect)) return clipped_rect
score += 1 if score != 0 and score % 5 == 0: no_of_particles += 1 particles.append(create_particle()) check_bounce = bounce update_score() pygame.display.flip() clock.tick(60) pygame.display.flip() title = font.render("INFINITE BOUNCE", True, fontColor) startimg = pygame.image.load(resource_path("start.png")) imgx, imgy = ((width // 2) - 32, (height // 2 + 32)) rect = pygame.Rect((imgx, imgy), (imgx + 64, imgy + 64)) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.MOUSEBUTTONDOWN: mp = pygame.mouse.get_pos() if rect.collidepoint(mp): main() screen.fill(bgColor) screen.blit(title, ((width - title.get_width()) // 2, height // 2 - title.get_height() - 64)) screen.blit(startimg, rect) pygame.display.flip()
def animate(self): self.rect = pygame.Rect(self.x, self.y, self.rect[2], self.rect[3])
def update(self): _pos = (random.randint(10, WIDTH - self.rect.width - 10), random.randint(50, HEIGHT - self.rect.height - 10)) self.rect = pygame.Rect(_pos, (self.rect.width, self.rect.height))
def run(self): pg.init() self.screen = pg.display.set_mode(SCREEN_RES) pg.display.set_caption('Sudoku solver') display = Display_board(self.screen) flag1 = 0 val = 0 pos = (0, 0) blink = False alpha = 1 a_change = True blink_color = GREEN initial_lock = 0 get_cord((0, 0)) set_highlight((0, 0), (0, 0), (0, 0), input_lock) board = create_board().board while 1: for event in pg.event.get(): if event.type == pg.QUIT or (event.type == pg.KEYDOWN and event.key == pg.K_ESCAPE): exit() if event.type == pg.MOUSEBUTTONDOWN: flag1 = 1 pos = pg.mouse.get_pos() get_cord(pos) # Checks if selection is on the board if pos[0] < TOP_LX or pos[1] < TOP_LY or pos[0] > int(BOT_RX) or pos[1] > int(BOT_RY): blink = False else: blink = True if event.type == pg.KEYDOWN and input_lock != 1: if event.key == pg.K_1: val = 1 if event.key == pg.K_2: val = 2 if event.key == pg.K_3: val = 3 if event.key == pg.K_4: val = 4 if event.key == pg.K_5: val = 5 if event.key == pg.K_6: val = 6 if event.key == pg.K_7: val = 7 if event.key == pg.K_8: val = 8 if event.key == pg.K_9: val = 9 elif event.type == pg.KEYDOWN and input_lock == 1: if event.key == pg.K_BACKSPACE: val = 0 set_highlight((0, 0), (0, 0), (0, 0), initial_lock) blink_color = GREEN if val != 0: display.draw_val(val, box_index_x, box_index_y) if valid(board, int(box_index_x), int(box_index_y), val, display): board[int(box_index_x)][int(box_index_y)] = val else: board[int(box_index_x)][int(box_index_y)] = 0 val = 0 # Draws the screen pg.draw.rect(self.screen, BLACK, (0, 0, self.screen.get_width(), self.screen.get_height())) self.screen.fill(BEIGE) # Draws the board display.draw(board) # Check if cell is selected if blink: cell = display.find_cell(box_index_x, box_index_y) blink = display.blink(alpha, a_change) alpha = blink[0] a_change = blink[1] myRect = pg.Rect(cell) rectSurf = pg.Surface(myRect.size, pg.SRCALPHA) rectSurf.fill(blink_color) rectSurf.set_alpha(alpha) self.screen.blit(rectSurf, (myRect.x, myRect.y)) # Check if incorrect input if input_lock == 1: display.update(board, row_index, col_index, blk_index) blink_color = RED # display.draw_box() pg.display.update() self.solution = solve_board(board) self.solution.assign_flags(board)
def draw(self): # A instance of the Window screen # Window object must've been instatiated # draw_rect is necessary to readjust the image position given .x and .y self.rect = pygame.Rect(self.x, self.y, self.width, self.height) window.Window.get_screen().blit(self.image, self.rect)
def draw(self,win): x,y = self.get_window_pos() pygame.init() self.rect = pygame.Rect(x,y,self.square_length,self.square_length) self.draw_square = pygame.gfxdraw.rectangle(win,self.rect,self.color) return self.draw_square
def process_events(self): for event in pygame.event.get(): if event.type == pygame.QUIT: self.running = False self.ui_manager.process_events(event) if event.type == pygame.KEYDOWN and event.key == pygame.K_d: self.debug_mode = False if self.debug_mode else True self.ui_manager.set_visual_debug_mode(self.debug_mode) if event.type == pygame.KEYDOWN and event.key == pygame.K_f: print("self.ui_manager.focused_set:", self.ui_manager.focused_set) if event.type == pygame.USEREVENT: if (event.user_type == pygame_gui.UI_TEXT_ENTRY_FINISHED and event.ui_object_id == '#main_text_entry'): print(event.text) if event.user_type == pygame_gui.UI_TEXT_BOX_LINK_CLICKED: if event.link_target == 'test': print("clicked test link") elif event.link_target == 'actually_link': print("clicked actually link") if event.user_type == pygame_gui.UI_BUTTON_PRESSED: if event.ui_element == self.test_button: self.test_button.set_text( random.choice( ['', 'Hover me!', 'Click this.', 'A Button'])) self.create_message_window() if event.ui_element == self.test_button_3: ScalingWindow(pygame.Rect((50, 50), (224, 224)), self.ui_manager) if event.ui_element == self.test_button_2: EverythingWindow(pygame.Rect((10, 10), (640, 480)), self.ui_manager) if event.ui_element == self.disable_toggle: if self.all_enabled: self.disable_toggle.set_text('Enable') self.all_enabled = False self.ui_manager.root_container.disable() self.disable_toggle.enable() else: self.disable_toggle.set_text('Disable') self.all_enabled = True self.ui_manager.root_container.enable() if event.ui_element == self.hide_toggle: if self.all_shown: self.hide_toggle.set_text('Show') self.all_shown = False self.ui_manager.root_container.hide() self.hide_toggle.show() else: self.hide_toggle.set_text('Hide') self.all_shown = True self.ui_manager.root_container.show() if (event.user_type == pygame_gui.UI_DROP_DOWN_MENU_CHANGED and event.ui_element == self.test_drop_down): self.check_resolution_changed()
import pygame import random SCREEN_RECT = pygame.Rect(0,0,480,700) CREAT_ENEMY_EVENT = pygame.USEREVENT HERO_FIRE_EVENT = pygame.USEREVENT + 1 class MenWeiJia_GameSprite(pygame.sprite.Sprite): def __init__(self,image_name,speed=1): super().__init__() self.image = pygame.image.load(image_name) self.rect = self.image.get_rect() self.speed = speed def update(self): self.rect.y -= self.speed class MenWeiJia_Background(MenWeiJia_GameSprite): def __init__(self,is_alt = False): super().__init__("./images/background.png") self.rect.y = 0 if is_alt: self.rect.top = self.rect.bottom def update(self): super().update() class MenWeiJia_Enemy(MenWeiJia_GameSprite): def __init__(self): super().__init__("./images/enemy1.png")
def move(self, coord): if coord == None: raise Exception("coord is None") self.coordinate = coord if not self._ghost: self.rect = pygame.Rect(self.coordinate.x * TILE_SIZE, self.coordinate.y * TILE_SIZE, TILE_SIZE, TILE_SIZE)
while running: fpsClock.tick(FPS) event = pygame.event.poll() if event.type == pygame.QUIT: running = 0 screen.fill(bgcolor) pygame.draw.circle(screen, yellow, (550, 100), 50) #draw circle pygame.draw.circle(screen,yellow, (int(x_ball), int(y_ball)), 12) # draw the box pygame.draw.rect(screen, darkBlue, pygame.Rect((100, 350), (100, 100)), 10) # draw the box top pygame.draw.line(screen, red, (100, 350), (x_box, y_box),10) #angle of the box top movement alpha_box += pi/75*dir_box #Move the box top (arc movement) x_box = 100 + (100 * cos(alpha_box)) y_box = 350 - (100 * sin(alpha_box)) #move the box top from 0 to 90 degrees if alpha_box >=pi/2 or alpha_box <= 0: dir_box *= -1 pygame.draw.circle(screen, (243,79,79), (100,350), 12)