def load_image(name, colorkey=None): fullname = os.path.join('../data', name) # если файл не существует, то выходим if not os.path.isfile(fullname): print(f"Файл с изображением '{fullname}' не найден") sys.exit() image = pygame.image.load(fullname) return image pygame.init() screen = pygame.display.set_mode((600, 600)) clock = pygame.time.Clock() arrow = load_image("arrow.png") r = arrow.get_rect() pygame.mouse.set_visible(0) running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False if event.type == pygame.MOUSEMOTION: screen.fill(pygame.Color("black")) r.topleft = event.pos if pygame.mouse.get_focused(): screen.blit(arrow, r) pygame.display.flip() clock.tick(100) pygame.quit()
def init_player(): plane_img = pygame.Surface([50, 50]) plane_img.fill(pygame.Color(100, 100, 100, 100)) player = role.Player(plane_img, [role.SCREEN_WIDTH / 2, role.SCREEN_HEIGHT / 2]) return player
return (a, b) def fst(pair): return pair[0] def snd(pair): return pair[1] def makeRect(left, top, width, height): return pygame.Rect(left, top, width, height) white = pygame.Color("white") black = pygame.Color("black") def makeClock(): return pygame.time.Clock() def debug(msg): print(msg) sys.stdout.flush() def getType(e): return e.type
import pygame import towerComm import Character import EnemySpawner from time import sleep BLACK = pygame.Color('black') WHITE = pygame.Color('white') RED = pygame.Color('red') GREEN = pygame.Color('green') BLUE = pygame.Color('blue') comm = towerComm.towerComm() pygame.init() screen = pygame.display.set_mode((700, 500)) pygame.display.set_caption("Volcano of Doom") clock = pygame.time.Clock() pygame.joystick.init() Player = Character.Character(comm) time = pygame.time.get_ticks() spawner = EnemySpawner.EnemySpawner(comm, time) def loop(): done = False while done == False: time = pygame.time.get_ticks() for event in pygame.event.get(): # User did something. if event.type == pygame.QUIT: # If user clicked close. done = True # Flag that we are done so we exit this loop. elif event.type == pygame.JOYBUTTONDOWN:
# 鼠标按下 if event.type == pygame.MOUSEBUTTONDOWN: # 获取圆不存在的索引值 num = circleExists.index(False) # 将该索引值的圆设置为存在 circleExists[num] = True # 圆的半径设置为0 radius[num] = 0 # 获取鼠标坐标 circleX[num], circleY[num] = pygame.mouse.get_pos() # 随机获取颜色值 RGBx[num] = random.randint(0, 255) RGBy[num] = random.randint(0, 255) RGBz[num] = random.randint(0, 255) # 画圆 pygame.draw.circle(screen, pygame.Color(RGBx[num], RGBy[num], RGBz[num]), (circleX[num], circleY[num]), radius[num], 1) if event.type == pygame.QUIT: pygame.quit() sys.exit() for i in range(10): # 圆不存在则跳过循环 if not circleExists[i]: pass else: # 随机圆的大小 if radius[i] < random.randint(10, 50): # 圆的随机半径增量 circleDelt[i] = random.randint(0, 5) radius[i] += circleDelt[i] # 画圆
def drawPosition(self, screen, vorigX, vorigY, positionX, positionY, labelPosition=0, drawLabel=True, abstand=5): if vorigX == positionX and vorigY == positionY: pygame.draw.circle(screen, pygame.Color('black'), (vorigX, vorigY), abstand, 1) else: prozentSatz = abstand / (math.sqrt( abs(vorigX - positionX)**2 + abs(vorigY - positionY)**2)) gerundetX = round(abs(vorigX - positionX) * prozentSatz) gerundetY = round(abs(vorigY - positionY) * prozentSatz) if vorigX < positionX and vorigY > positionY: PunktCX = int(positionX - gerundetX) PunktCY = int(positionY + gerundetY) PunktBX = int(positionX + gerundetY) PunktBY = int(positionY + gerundetX) PunktAX = int(positionX + gerundetX) PunktAY = int(positionY - gerundetY) PunktDX = int(positionX - gerundetY) PunktDY = int(positionY - gerundetX) if vorigX < positionX and vorigY < positionY: PunktDX = int(positionX - gerundetX) PunktDY = int(positionY - gerundetY) PunktAX = int(positionX + gerundetY) PunktAY = int(positionY - gerundetX) PunktBX = int(positionX + gerundetX) PunktBY = int(positionY + gerundetY) PunktCX = int(positionX - gerundetY) PunktCY = int(positionY + gerundetX) if vorigX > positionX and vorigY < positionY: PunktBX = int(positionX + gerundetX) PunktBY = int(positionY - gerundetY) PunktCX = int(positionX + gerundetY) PunktCY = int(positionY + gerundetX) PunktDX = int(positionX - gerundetX) PunktDY = int(positionY + gerundetY) PunktAX = int(positionX - gerundetY) PunktAY = int(positionY - gerundetX) if vorigX > positionX and vorigY > positionY: PunktBX = int(positionX + gerundetX) PunktBY = int(positionY + gerundetY) PunktCX = int(positionX - gerundetY) PunktCY = int(positionY + gerundetX) PunktDX = int(positionX - gerundetX) PunktDY = int(positionY - gerundetY) PunktAX = int(positionX + gerundetY) PunktAY = int(positionY - gerundetX) if vorigX == positionX and vorigY < positionY: PunktAX = positionX PunktAY = positionY - abstand PunktBX = positionX + abstand PunktBY = positionY PunktCX = positionX PunktCY = positionY + abstand PunktDX = positionX - abstand PunktDY = positionY if vorigX == positionX and vorigY > positionY: PunktAX = positionX PunktAY = positionY - abstand PunktBX = positionX + abstand PunktBY = positionY PunktCX = positionX PunktCY = positionY + abstand PunktDX = positionX - abstand PunktDY = positionY if vorigX < positionX and vorigY == positionY: PunktCX = positionX - abstand PunktCY = positionY PunktBX = positionX PunktBY = positionY + abstand PunktAX = positionX + abstand PunktAY = positionY PunktDX = positionX PunktDY = positionY - abstand if vorigX > positionX and vorigY == positionY: PunktBX = positionX + abstand PunktBY = positionY PunktCX = positionX PunktCY = positionY + abstand PunktDX = positionX - abstand PunktDY = positionY PunktAX = positionX PunktAY = positionY - abstand pygame.draw.polygon(screen, pygame.Color('black'), [(PunktAX, PunktAY), (PunktBX, PunktBY), (PunktCX, PunktCY), (PunktDX, PunktDY)], 0) ''' schrift = pygame.font.Font('FreeMono.ttf', 12) label = schrift.render("A", 1, (0, 0, 255)) screen.blit(label, (PunktAX, PunktAY)) label = schrift.render("B", 1, (0, 0, 255)) screen.blit(label, (PunktBX, PunktBY)) label = schrift.render("C", 1, (0, 0, 255)) screen.blit(label, (PunktCX, PunktCY)) label = schrift.render("D", 1, (0, 0, 255)) screen.blit(label, (PunktDX, PunktDY)) ''' if drawLabel == True: if labelPosition == 0: pygame.draw.aaline(screen, pygame.Color('black'), (PunktAX + 3, PunktAY - 3), (PunktAX + 20, PunktAY - 20)) self.genLabel(screen, 0, PunktAX + 20, PunktAY - 20) if labelPosition == 1: pygame.draw.aaline(screen, pygame.Color('black'), (PunktBX + 3, PunktBY + 3), (PunktBX + 20, PunktBY + 20)) self.genLabel(screen, 1, PunktBX + 20, PunktBY + 20) if labelPosition == 2: pygame.draw.aaline(screen, pygame.Color('black'), (PunktCX - 3, PunktCY + 3), (PunktCX - 20, PunktCY + 20)) self.genLabel(screen, 2, PunktCX - 20, PunktCY + 20) if labelPosition == 3: pygame.draw.aaline(screen, pygame.Color('black'), (PunktDX - 3, PunktDY - 3), (PunktDX - 20, PunktDY - 20)) self.genLabel(screen, 3, PunktDX - 20, PunktDY - 20)
def show(self, color): global screen pygame.draw.circle(screen, pygame.Color(color), (self.x, self.y), self.RADIUS)
import os import pygame pygame.init() SIZE = WIDTH, HEIGHT = 720, 480 BACKGROUND_COLOR = pygame.Color('black') FPS = 60 screen = pygame.display.set_mode(SIZE) clock = pygame.time.Clock() def load_images(path): """ Loads all images in directory. The directory must only contain images. Args: path: The relative or absolute path to the directory to load images from. Returns: List of images. """ images = [] for file_name in os.listdir(path): image = pygame.image.load(path + os.sep + file_name).convert() images.append(image) return images class AnimatedSprite(pygame.sprite.Sprite): def __init__(self, position, images):
def main(): screen = p.display.set_mode((WIDTH, HEIGHT)) clock = p.time.Clock() screen.fill(p.Color("white")) gs = chess_engine.GameState() valid_moves = gs.get_valid_moves() move_made = False # flag for if a new move has been made animate = False # flag for animation load_images() running = True sq_selected = () # keeps track of last user click. tuple(row,col) # keeps track of user clicks. list[tuple(row,col), tuple(row,col)] player_clicks = [] game_over = False white_did_check = "" black_did_check = "" last_move_printed = False moves_list = [] turn = 1 player_one = True # if true human is playing white player_two = False # if true human is playing black while running: human_turn = (gs.white_to_move and player_one) or (not gs.white_to_move and player_two) for e in p.event.get(): if e.type == p.QUIT: running = False p.quit() sys.exit() elif e.type == p.MOUSEBUTTONDOWN: if not game_over and human_turn: location = p.mouse.get_pos() # (x,y) location of mouse col = location[0] // SQ_SIZE row = location[1] // SQ_SIZE if sq_selected == (row, col): # user clicked the same square sq_selected = () # clear selection player_clicks = [] # clear the list else: sq_selected = (row, col) # append the clicks to the list player_clicks.append(sq_selected) if len(player_clicks) == 2: # 1st and 2nd click move = chess_engine.Move(player_clicks[0], player_clicks[1], gs.board) # prints the move in chess notation print(move.get_chess_notation()) for i in range(len(valid_moves)): if move == valid_moves[i]: gs.make_move(valid_moves[i]) move_made = True sq_selected = () player_clicks = [] if not move_made: player_clicks = [sq_selected] elif e.type == p.KEYDOWN: if e.key == p.K_z: # undo when z is pressed if gs.white_to_move: if turn > 1: turn -= 1 gs.undo_move() move_made = True animate = False game_over = False last_move_printed = False if e.key == p.K_r: # reset the game when r is pressed gs = chess_engine.GameState() valid_moves = gs.get_valid_moves() sq_selected = () player_clicks = [] move_made = False animate = False game_over = False turn = 1 last_move_printed = False moves_list = [] # AI move finder if not game_over and not human_turn: AI_move = chess_ai.findBestMoveNegaMaxAlphaBeta(gs, valid_moves) if AI_move is None: AI_move = chess_ai.findRandomMove(valid_moves) gs.make_move(AI_move, True) move_made = True animate = True if move_made: if gs.check_for_pins_and_checks()[0]: if not gs.white_to_move: white_did_check = "+" else: black_did_check = "+" if gs.white_to_move: moves_list.append( f"\n{turn}. {gs.move_log[-2].get_chess_notation()}{white_did_check} {gs.move_log[-1].get_chess_notation()}{black_did_check}" ) print( f"\n{turn}. {gs.move_log[-2].get_chess_notation()}{white_did_check} {gs.move_log[-1].get_chess_notation()}{black_did_check}", end="") turn += 1 white_did_check = "" black_did_check = "" if animate: animate_move(gs.move_log[-1], screen, gs.board, clock) valid_moves = gs.get_valid_moves() move_made = False animate = False draw_game_state(screen, gs, valid_moves, sq_selected) if gs.checkmate: game_over = True if gs.white_to_move: draw_text(screen, "Black wins by checkmate") if not last_move_printed: moves_list[-1] += "+" moves_list.append("result: 0-1") print("+") print("result: 0-1") last_move_printed = True save_game(moves_list) else: draw_text(screen, "White wins by checkmate") if not last_move_printed: moves_list.append( f"\n{turn}. {gs.move_log[-1].get_chess_notation()}++") moves_list.append("result: 1-0") print( f"\n{turn}. {gs.move_log[-1].get_chess_notation()}++") print("result: 1-0") last_move_printed = True save_game(moves_list) elif gs.stalemate: game_over = True draw_text(screen, "Stalemate") if not last_move_printed: if not gs.white_to_move: moves_list.append( f"\n{turn}. {gs.move_log[-1].get_chess_notation()}") moves_list.append("result: 1/2-1/2") print(f"\n{turn}. {gs.move_log[-1].get_chess_notation()}") print("result: 1/2-1/2") last_move_printed = True save_game(moves_list) clock.tick(MAX_FPS) p.display.flip()
def draw_chosen_unit(self): def add_to_hexagons_to_move(hexagon, num_): next_ = [] pos = hexagon.index helper_1, helper_2 = (0, -1) if pos[0] % 2 else (1, 0) for j in range(pos[0] - 1, pos[0] + 2): for i in range( pos[1] - 1 + helper_1 - (1 if j == pos[0] and helper_1 else 0), pos[1] + 2 + helper_2 + (1 if j == pos[0] and helper_2 else 0)): try: if not any([ i < 0, i >= len(self.board), j < 0 or j >= len(self.board[0]), pos == (j, i), (not self.board[i][j].tile.can_move and not (self.board[i][j].tile.__class__.__name__ == "Throne" and self.board[i][j].tile.player != self.turn)), self.board[i][j] == self.chosen_unit ]): if self.board[i][j] not in union_dict: union_dict[self.board[i][j]] = num_ if self.board[i][j] not in next_: next_ += [self.board[i][j]] except IndexError: pass return next_ if self.chosen_unit and self.chosen_unit.unit: if not self.hexagons_to_move: to_do = [self.chosen_unit] union_dict = {} for num in range( max(self.chosen_unit.unit.moved, self.chosen_unit.unit.attack_range)): new = [] for elm in to_do: if not (elm.unit and elm.unit != self.chosen_unit.unit): new += add_to_hexagons_to_move(elm, num + 1) to_do = new[:] for elm in union_dict.keys(): if not self.clicked_throne: if self.chosen_unit.unit.moved >= union_dict[elm] and elm.tile.__class__.__name__ != "Throne" \ and not (elm.tile.__class__.__name__ == "Field" and elm.tile.player != self.turn): self.hexagons_to_move[elm] = union_dict[elm] if elm.unit and elm.unit.player != self.turn \ and self.chosen_unit.unit.attack_range >= union_dict[elm]: self.hexagons_to_attack[elm] = union_dict[elm] if elm.tile is not None and elm.tile.can_be_attacked and elm.tile.player != self.turn \ and self.chosen_unit.unit.attack_range >= union_dict[elm]: self.hexagons_to_attack[elm] = union_dict[elm] if self.chosen_spell: to_do = [self.chosen_unit] union_dict = {} for num in range(self.chosen_spell.range): new = [] for elm in to_do: if not (elm.unit and elm.unit != self.chosen_unit.unit): new += add_to_hexagons_to_move(elm, num + 1) to_do = new[:] self.hexagon_to_cast = list(union_dict.keys()) if self.chosen_spell.use_on_himself: self.hexagon_to_cast += [self.chosen_unit] for elm in self.hexagons_to_move.keys(): if elm.unit is None: pygame.draw.circle( self.screen, pygame.Color("white"), self.board[elm.index[1]][elm.index[0]].center, 2, 5) for elm in self.hexagons_to_attack.keys(): pygame.draw.circle( self.screen, pygame.Color("red"), self.board[elm.index[1]][elm.index[0]].center, 2, 5) pygame.draw.polygon(self.screen, pygame.Color("red"), elm.points, 3) if self.chosen_spell and not self.chosen_spell.mana_cost or self.chosen_unit.unit.mana: for elm in self.hexagon_to_cast: if elm.unit and self.chosen_spell and self.chosen_spell.can_cast( self, elm.unit): pygame.draw.polygon(self.screen, pygame.Color("yellow"), elm.points, 3) if self.throne_menu_enable: union_dict = {} if self.turn == 0: for elm in self.throne_0: add_to_hexagons_to_move(elm, 1) self.hexagons_to_stay = list(set(union_dict.keys())) empty_hexagons = [] for num in self.hexagons_to_stay: if not num.unit: empty_hexagons.append(num) self.hexagons_to_stay = empty_hexagons for elm in union_dict: if elm.unit is None: pygame.draw.circle( self.screen, pygame.Color("White"), self.board[elm.index[1]][elm.index[0]].center, 2, 5) else: for elm in self.throne_1: add_to_hexagons_to_move(elm, 1) self.hexagons_to_stay = list(set(union_dict.keys())) empty_hexagons = [] for num in self.hexagons_to_stay: if not num.unit: empty_hexagons.append(num) self.hexagons_to_stay = empty_hexagons for elm in union_dict: if elm.unit is None: pygame.draw.circle( self.screen, pygame.Color("White"), self.board[elm.index[1]][elm.index[0]].center, 2, 5)
def hud(self): if self.chosen_unit: # TODO start_pos = (0 if not (self.throne_menu_enable and self.turn == 1) else (self.height - 80) // 5 * 2 + 80, 4 * (self.height / 5)) hud_width = 6 * (self.width / 12) hud_height = self.height - 4 * (self.height / 5) indent = hud_height // 15 if not (self.throne_menu_enable and self.turn == 1): flex = 0 else: flex = (self.height - 80) // 5 * 2 + 80 text_x = hud_height bar_width = hud_width - indent - text_x pygame.draw.rect(self.screen, pygame.Color("black"), (*start_pos, hud_width, hud_height)) pygame.draw.rect(self.screen, pygame.Color("white"), (*start_pos, hud_width, hud_height), 3) pygame.draw.circle(self.screen, pygame.Color("white"), (start_pos[0] + hud_height // 2, start_pos[1] + hud_height // 2), hud_height // 2 - hud_height // 15, 2) char_class = pygame.font.Font(None, 30).render( str(self.chosen_unit.unit), True, (255, 255, 255)) self.screen.blit( char_class, ((text_x + (bar_width - char_class.get_width()) // 2 + flex), start_pos[1] + indent)) text = f"{self.chosen_unit.unit.moved}/{self.chosen_unit.unit.moves_per_round}" attack = pygame.font.Font(None, 26).render( f"АТК: {self.chosen_unit.unit.damage} ХОД: {text}", True, (255, 255, 255)) self.screen.blit( attack, ((text_x + (bar_width - attack.get_width()) // 2 + flex), start_pos[1] + (2 * indent) // 2 + char_class.get_height())) self.draw_double_bar( ("red", "white"), (text_x + flex, start_pos[1] + 2 * indent + attack.get_height() + char_class.get_height(), bar_width, 1.3 * indent), self.chosen_unit.unit.health / (self.chosen_unit.unit.full_health / 100), 1) if self.chosen_unit.unit.mana: self.draw_double_bar( ("blue", "white"), (text_x + flex, start_pos[1] + 4 * indent + attack.get_height() + char_class.get_height(), bar_width, 1.3 * indent), self.chosen_unit.unit.mana / (self.chosen_unit.unit.full_mana / 100), 1) count_spells = len( list(filter(lambda x: x, self.chosen_unit.unit.spells))) spell_box_side = self.height - (start_pos[1] + 6 * indent + 2 * attack.get_height()) - indent top_tab = start_pos[1] + (6.3 if self.chosen_unit.unit.mana else 5) * indent + 2 * attack.get_height() tab = (bar_width - 4 * spell_box_side) / 3 left_tab = ((4 * spell_box_side + 3 * tab) - (count_spells * spell_box_side + (count_spells - 1) * tab)) / 2 for num in range(count_spells): pygame.draw.rect(self.screen, pygame.Color("white"), (left_tab + text_x + (spell_box_side + tab) * num + flex, top_tab, spell_box_side, spell_box_side), 1)
def draw_units_to_go(self): if self.need_to_light_units: for elm in self.one_d_board: if elm.unit and elm.unit.player == self.turn and elm.unit.moved: pygame.draw.polygon(self.screen, pygame.Color("orange"), elm.points, 3)
import pygame import sys pygame.init() screen = pygame.display.set_mode((100,100)) file_name = "skill.bmp" surf = pygame.image.load(file_name).convert() sys.stdout = open("log.txt" , "w") pixel_array = pygame.PixelArray( surf ) for i in range(len(pixel_array)): for j in range(len(pixel_array[0])): color = surf.unmap_rgb( pixel_array[i][j] ) r , g , b= color[0] , color[1] , color[2] print r , g, b if r > 200 and g > 200 and b > 200: pixel_array[i][j] = pygame.Color(247,0,255) pygame.image.save(pixel_array.make_surface() , "new_" + file_name)
def set_cursor_attr(self, attr): """ Change attribute of cursor. """ self.cursor_attr = attr % self.num_fore_attrs self.cursor.set_palette_at( 254, pygame.Color(0, self.cursor_attr, self.cursor_attr))
def main(): global score pygame.init() clock = pygame.time.Clock() p_speed = 9 # setting the main window wn_width = 980 wn_height = 700 bgcolor = pygame.Color("grey12") win = pygame.display.set_mode((wn_width, wn_height)) pygame.display.set_caption("--- PONG GAME ---") win.fill(bgcolor) ball, p1, p2 = form_creation(wn_height, wn_width) show_text(win," ", (wn_width/2, wn_height/2), " Press <space> to play the game") pygame.display.flip() sleep(1.5) counter(win, 3, wn_width/2, wn_height/2, window_col = bgcolor) # game loop run = True while run: #check for events for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() if event.type == pygame.KEYDOWN: if event.key == pygame.K_RIGHT: p1.speed = p_speed if event.key == pygame.K_LEFT: p1.speed = -p_speed if event.type == pygame.KEYUP: p1.speed = 0 #visuals win.fill(bgcolor) p1.draw_self(win) p2.draw_self(win) ball.draw_self(win) pygame.draw.aaline(win, (200, 200, 200), (0, wn_height/2), (wn_width, wn_height/2) ) show_text(win, player_score, (50, (wn_height/2) + 20), "player") show_text(win, cpu_score, (40, (wn_height/2) - 20), "cpu") object_movement(ball, p1, p2) collisions(ball, p1, p2, wn_height, wn_width) runcheck_score() # updating the display pygame.display.flip() clock.tick(60)
def update(self, *args): for col in range(HP_BARS_W): color = 'green' if col < HP_BARS_W * self.obj.hp / self.max_hp else 'red' for row in range(HP_BARS_H): self.image.set_at((col, row), pygame.Color(color))
# Pygame Init init_status = pygame.init() if init_status[1] > 0: print("(!) Had {0} initialising errors, exiting... ".format( init_status[1])) sys.exit() else: print("(+) Pygame initialised successfully ") # Play Surface size = width, height = 640, 320 playSurface = pygame.display.set_mode(size) pygame.display.set_caption("Snake Game") # Colors red = pygame.Color(255, 0, 0) green = pygame.Color(0, 255, 0) black = pygame.Color(0, 0, 0) white = pygame.Color(255, 255, 255) brown = pygame.Color(165, 42, 42) # FPS controller fpsController = pygame.time.Clock() # Game settings delta = 10 snakePos = [100, 50] snakeBody = [[100, 50], [90, 50], [80, 50]] foodPos = [400, 50] foodSpawn = True direction = 'RIGHT'
class Race(object): def __init__(self): self.vb = None self.w = 0 self.h = 0 self.startpos = (0, 0) self.checkpoints = [] self.endpoints = [] self.bouys = [] self.boats = [] self.ships = [] self.fzcache = None self.anomalies = [] def small_positive_noise(self, x, y): return math.fabs(noise.pnoise3( float(x) / self.w, float(y) / self.h, 1.2, octaves=6, persistence=0.84123, lacunarity=2.41212, repeatx=1, repeaty=1, repeatz=1, base=1)) def my_noise(self, x, y): return noise.pnoise3( float(x * 10) / self.w, float(y * 10) / self.h, 1.2, octaves=5, persistence=0.54123, lacunarity=2.81212, repeatx=10, repeaty=10, repeatz=1, base=4) def getz(self, x, y): z = self.heightmap[int(x) % self.w][int(y) % self.h] return z def getfz2(self, x, y): z = self.heightmap[int(x) % self.w][int(y) % self.h] z = self.my_noise(x, y) + z return z def getfz(self, x, y): z = self.heightmap[int(x) % self.w][int(y) % self.h] if math.fabs(z) < 5.0: return z if not self.fzcache: self.fzcache = {} elem = self.fzcache.get((x, y)) if elem: return elem else: z = self.my_noise(x, y) + z self.fzcache[(x, y)] = z return z def getz_noised(self, x, y): z = self.heightmap[int(x) % self.w][int(y) % self.h] n = self.noisemap[int(x) % self.w][int(y) % self.h] if z > 0.5: k = 1 # k = z - 1 if z - 1 < 1 else 1 z += k * n * self.small_positive_noise(x, y) elif z < 0.5: k = 1 z += k * -n * self.small_positive_noise(x, y) return z @for_color(pygame.Color(255, 255, 0)) def sand(self, x, y): self.heightmap[x][y] = 1 self.noisemap[x][y] = 0.1 @for_color(pygame.Color(0, 128, 0)) def hills(self, x, y): self.heightmap[x][y] = 30 self.noisemap[x][y] = 10 @for_color(pygame.Color(255, 0, 0)) def start(self, x, y): self.heightmap[x][y] = self.heightmap[x - 1][y] self.noisemap[x][y] = 0 self.startpos = (x, y) @for_color(pygame.Color(128, 0, 0)) def checkpoint(self, x, y): self.heightmap[x][y] = self.heightmap[x - 1][y] self.noisemap[x][y] = 0 self.checkpoints.append((x, y)) @for_color(pygame.Color(255, 127, 127)) def endpoint(self, x, y): self.heightmap[x][y] = self.heightmap[x - 1][y] self.noisemap[x][y] = 0 self.endpoints.append((x, y)) @for_color(pygame.Color(0, 0, 0)) def mountains(self, x, y): self.heightmap[x][y] = 300 self.noisemap[x][y] = 100 @for_color(pygame.Color(192, 192, 192)) def rough(self, x, y): self.heightmap[x][y] = 50 self.noisemap[x][y] = 50 @for_color(pygame.Color(128, 128, 128)) def wall(self, x, y): self.heightmap[x][y] = 20 self.noisemap[x][y] = 0 @for_color(pygame.Color(0, 255, 255)) def lake(self, x, y): self.heightmap[x][y] = -10 self.noisemap[x][y] = 10.0 @for_color(pygame.Color(255, 128, 0)) def buoy(self, x, y): self.heightmap[x][y] = self.heightmap[x - 1][y] self.noisemap[x][y] = 0 self.bouys.append((x, y)) @for_color(pygame.Color(0, 255, 0)) def boat(self, x, y): self.heightmap[x][y] = self.heightmap[x - 1][y] self.noisemap[x][y] = 0 self.boats.append((x, y)) @for_color(pygame.Color(0, 0, 128)) def ocean(self, x, y): self.heightmap[x][y] = -100 self.noisemap[x][y] = 50.0 @for_color(pygame.Color(255, 255, 255)) def ship(self, x, y): self.heightmap[x][y] = self.heightmap[x - 1][y] self.noisemap[x][y] = 0 self.ships.append((x, y)) @for_color(pygame.Color(0, 0, 255)) def sea(self, x, y): self.heightmap[x][y] = -50 self.noisemap[x][y] = 25.0 @for_color(pygame.Color(128, 255, 128)) def sink(self, x, y): self.heightmap[x][y] = -50 self.noisemap[x][y] = 0 a = SinkAnomaly(x, y) a.range = 40 self.anomalies.append(a) @for_color(pygame.Color(255, 0, 255)) def curl(self, x, y): self.heightmap[x][y] = -50 self.noisemap[x][y] = 0 a = CurlAnomaly(x, y) a.range = 40 self.anomalies.append(a) @for_color(pygame.Color(255, 127, 255)) def softcurl(self, x, y): self.heightmap[x][y] = -50 self.noisemap[x][y] = 0 a = CurlAnomaly(x, y) a.range = 8 a.force = 0.000 self.anomalies.append(a) @for_color(pygame.Color(255, 128, 128)) def fountain(self, x, y): self.heightmap[x][y] = -50 self.noisemap[x][y] = 0 a = SourceAnomaly(x, y) a.range = 30 self.anomalies.append(a) def noise_heightmap(self): w = self.w h = self.h new_heightmap = np.ndarray(shape=(w, h), dtype=float) for y in range(h): for x in range(w): if (math.fabs(self.heightmap[x][y]) <= 1.0 or x == 0 or y == 0 or x == w - 1 or y == h - 1): new_heightmap[x][y] = self.heightmap[x][y] else: new_heightmap[x][y] = self.getz_noised(x, y) self.heightmap = new_heightmap def soften_heightmap(self): w = self.w h = self.h new_heightmap = np.ndarray(shape=(w, h), dtype=float) dirs = [ (-1, 0), (1, 0), (0, 1), (0, -1), (-1, -1), (1, 1), (-1, 1), (1, -1), (0, 0), ] for y in range(h): for x in range(w): if self.heightmap[x][y] <= 0: new_heightmap[x][y] = self.heightmap[x][y] else: summ = 0.0 for dx, dy in dirs: summ += self.getz(x + dx, y + dy) new_heightmap[x][y] = summ / len(dirs) self.heightmap = new_heightmap def enum_currents(self, x, y): if 0 <= x < self.w and 0 <= y < self.h: if self.heightmap[x][y] >= 100.3: pass else: for an in self.anomalies: yield an.anomaly(x, y) def get_current(self, x, y): summ = np.ndarray(shape=(2,), dtype=float) summ[0] = 0 summ[1] = 0 for (x, y) in self.enum_currents(x, y): summ += (x, y) result = np.ndarray(shape=(3,), dtype=float) result[0] = summ[0] result[1] = summ[1] result[2] = 0 return result def save_default_race_conf(self, name): self.save_race_conf({ "scale_x": "20.0", "scale_y": "20.0", "scale_z": "2.0", "biome": "default", "prenoise": "1", "smooth": "2", "postnoise": "1", "next_races": "lake", "intro": "This is a simple race, nothing unusual", "outro": "Race completed!", "start_time": "30", "cp_time": "15", "laps": "1", "type": 'countup', # "type" : 'checkpoints' "placeholder1": "1.0", "placeholder2": "1.0" }, name) def save_race_conf(self, cfg, name): s = json.dumps(cfg, indent=2) f = open(name, 'w') f.write(s) f.close() def load_race_conf(self, name): if not os.path.exists(name): self.save_default_race_conf(name) f = json.load(open(name)) self.config = f self.sx = float(self.config['scale_x']) self.sy = float(self.config['scale_y']) self.sz = float(self.config['scale_z']) self.prenoise = int(self.config['prenoise']) self.smooth = int(self.config['smooth']) self.postnoise = int(self.config['postnoise']) def load(self, name): self.load_race_conf(name.replace('.png', '.json')) img = pygame.image.load(name) w, h = img.get_size() self.w = w self.h = h self.heightmap = np.ndarray(shape=(w, h), dtype=float) self.noisemap = np.ndarray(shape=(w, h), dtype=float) self.currents = np.ndarray(shape=(w, h, 2), dtype=float) for y in range(h): for x in range(w): c = hc(img.get_at((x, h - y - 1))) f = color_actions.get(c) if f: f(self, x, y) else: color_actions[c] = lambda s, x, y: None logging.warn('Please add @for_color(pygame.Color{})'.format(c)) for i in range(self.prenoise): logging.info('noising') self.noise_heightmap() for i in range(self.smooth): logging.info('bluring') self.soften_heightmap() for i in range(self.postnoise): logging.info('noising') self.noise_heightmap()
def update(self): self.show('black') newx, newy = pygame.mouse.get_pos() newy -= self.height // 2 newy1 = newy + self.height if newy > BORDER_HEIGHT and newy1 < WINDOW_HEIGHT - BORDER_HEIGHT: self.y = newy self.show('white') # Classes defined # Initialize BALL and PADDLE Object ball_play = Ball(WINDOW_WIDTH - Ball.RADIUS - 16, WINDOW_HEIGHT // 2, -1, 1) racket = Paddle(WINDOW_HEIGHT // 2 - 26) # Setup the borders pygame.draw.rect(screen, pygame.Color("white"), pygame.Rect((0, 0), (BORDER_WIDTH, BORDER_HEIGHT))) pygame.draw.rect(screen, pygame.Color(WALL_COLOR), pygame.Rect((0, 0), (BORDER_HEIGHT, WINDOW_HEIGHT))) pygame.draw.rect( screen, pygame.Color(WALL_COLOR), pygame.Rect((0, WINDOW_HEIGHT - 10), (BORDER_WIDTH, BORDER_HEIGHT))) # Borders are setup ball_play.show("white") racket.show("white") # On pressing X, it doesnt exit. To exit, listen for events and if the type is quit, quit. while True: e = pygame.event.poll() if e.type == pygame.QUIT: pygame.quit()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys import pygame pygame.init() width, height = 400, 500 surface = pygame.display.set_mode((width, height)) pygame.display.set_caption('Mouse position') # Colors red = pygame.Color(115, 38, 80) white = pygame.Color(255, 255, 255) font = pygame.font.Font("freesansbold.ttf", 32) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() x, y = pygame.mouse.get_pos() message = "mouse position: {},{}".format(x, y) text = font.render(message, True, red) rect = text.get_rect() rect.center = (width // 2, height // 2)
def show(self, color): global screen pygame.draw.rect( screen, pygame.Color(color), pygame.Rect((self.x, self.y), (self.length, self.height)))
def game(self, playerData, worldData): #update PLAYER data to window size data = playerData player_speed = self.applyXY(5) for player in data["player"]: player[PLAYER_KEY[2]] = self.applyXY( player[PLAYER_KEY[2]], player[PLAYER_KEY[5]]["x"], player[PLAYER_KEY[5]]["y"]) # size on 1280 * 720 resolution #player object instance player = Player(data, player_speed) #place block from saved world (string) world = World(BLOCK_TEXTURES, self.applyXY(DUNGEON_SPRITE_SIZE)) world.generate(worldData) #Define player spawn position if len(world.start_points ) > 0: #choose a random position from start points start_point_index = random.randint(0, len(world.start_points) - 1) start_point = world.start_points[start_point_index] player.pos.x, player.pos.y = start_point[0], start_point[1] else: # find random position on floor findedBlock = False while not findedBlock: block = random.choice(world.world_blocks) if not block.collision: findedBlock = True player.pos.x = block.rect.x player.pos.y = block.rect.y #camera target=player camera = Camera(self.simple_camera, self.XWIN, self.YWIN) camera.state = camera.camera_func(camera.state, player.rect) #Create Light mask lightMask = LightMask((0, 0), self.DISPLAY, pygame.Color(110, 110, 110), self.FLAGS) lightMask.mask.fill(lightMask.colorBG) lightMask.drawLight(self.applyXY( player.skills[SKILLS[6]]), (camera.apply(player).x - int( self.applyXY(player.skills[SKILLS[6]]) / 2 - player.rect.width / 2), camera.apply(player).y - int( self.applyXY(player.skills[SKILLS[6]]) / 2 - player.rect.height / 2))) showFPS = False currentFPS = 0 showLightMask = True continueGame = True pause = "" while continueGame: #//////EVENTS///////// for event in pygame.event.get(): if event.type == QUIT: self.stop() elif event.type == KEYDOWN: if event.key == K_ESCAPE: pause = self.pauseMenu() if event.key == K_LEFT: player.events["horizontal"] = -1 if event.key == K_RIGHT: player.events["horizontal"] = 1 if event.key == K_UP: player.events["vertical"] = -1 if event.key == K_DOWN: player.events["vertical"] = 1 if event.key == K_l: if showLightMask: showLightMask = False else: showLightMask = True if event.key == K_f: if showFPS: showFPS = False else: showFPS = True elif event.type == KEYUP: if event.key == K_RIGHT: if player.events["horizontal"] == 1: player.events["horizontal"] = 0 if event.key == K_LEFT: if player.events["horizontal"] == -1: player.events["horizontal"] = 0 if event.key == K_UP: if player.events["vertical"] == -1: player.events["vertical"] = 0 if event.key == K_DOWN: if player.events["vertical"] == 1: player.events["vertical"] = 0 #///////UPDATES//////// if pause == "save": player.updateData() path = SAVESFOLDER + player.name + PLAYER_FILE_EXTENSION self.save(path, player.data) pause = self.pauseMenu() continue elif pause == "quit": self.continueGame = False break mouse_pos = pygame.mouse.get_pos() mouseRect = Rect(mouse_pos[0], mouse_pos[1], 1, 1) #player moves,rotates.... player.update(world.walls, (mouse_pos[0], mouse_pos[1]), camera) #camera target player camera.update(player) #///////DISPLAY//////// #draw Backgrounds self.window.fill(COLORS[1]) #floor self.window.blit(world.bg_surface, camera.applyRect(world.rect)) #player player.draw(self.window, camera) #walls self.window.blit(world.fg_surface, camera.applyRect(world.rect)) #draw light mask if showLightMask: lightMask.draw(self.window) #draw current fps in topleft if showFPS: self.text(self.applyX(20), self.applyY(20), FONTS[0], self.window, "FPS: " + str(currentFPS), COLORS[0]) currentFPS = int(self.clock.get_fps()) pygame.display.flip() self.clock.tick(self.FPS)
def mapColor2(m, max_iter): r = int(255 * m / max_iter) g = int(255 * m / max_iter) b = int(255 * m / max_iter) return pygame.Color(r, g, b)
pygame.display.set_caption("Rikoshet") clock = pygame.time.Clock() x, y = 300, heigh - size player = [(x, y)] dx, dy = 0, 0 xb, yb = 400, heigh - size * 2 ball = [(xb, yb)] dxb, dyb = -1, -1 target = randrange(size * 2, width - size * 3, size), randrange(size * 2, heigh / 2, size) directions = {'Left': True, 'Right': False, 'Up': True, 'Down': False} font_score = pygame.font.SysFont('Consolas', 20, bold=True) font_end = pygame.font.SysFont('Arial', 75, bold=True) while True: screen.fill(pygame.Color('black')) [(pygame.draw.rect(screen, pygame.Color('white'), (i, j, size * 10, size))) for i, j in player] [(pygame.draw.rect(screen, pygame.Color('yellow'), (i, j, size, size))) for i, j in ball] pygame.draw.rect(screen, pygame.Color('red'), (*target, size * 3, size * 3)) x += dx * size y += dy * size player.append((x, y)) player = player[-1:] xb += dxb * size yb += dyb * size ball.append((xb, yb)) ball = ball[-1:] render_score = font_score.render(f'SCORE: {score}', 1,
def main(): pygame.init() screen = pygame.display.set_mode((480, 800)) pygame.display.set_caption('飞机大战') text_font = pygame.font.Font(None, 36) background = pygame.Surface([480, 800]) background.fill(pygame.Color(200, 200, 200)) bullet_img = pygame.Surface([10, 10]) bullet_img.fill(pygame.Color(100, 100, 100)) enemy_img = pygame.Surface([30, 30]) enemy_img.fill(pygame.Color(100, 100, 100)) enemy_down_img = pygame.Surface([30, 30]) enemy_down_img.fill(pygame.Color(255, 0, 0)) player = init_player() enemies = pygame.sprite.Group() enemies_down = pygame.sprite.Group() enemy_frequency = 0 score = 0 clock = pygame.time.Clock() running = True while running: clock.tick(30) for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() player.shoot(bullet_img) #生成敌机 if enemy_frequency >= 50: enemy_frequency = 0 enemy_pos = [ random.randint(0, role.SCREEN_WIDTH - enemy_img.get_width()), 0 ] enemies.add(role.Enemy(enemy_img, enemy_down_img, enemy_pos)) enemy_frequency += 1 # 移动子弹 for bullet in player.bullets: bullet.move() if bullet.rect.bottom < 0: player.bullets.remove(bullet) ##移动敌机 for enemy in enemies: enemy.move() if enemy.rect.top > role.SCREEN_HEIGHT: enemies.remove(enemy) #移动玩家 key_pressed = pygame.key.get_pressed() if key_pressed[pygame.K_w] or key_pressed[pygame.K_UP]: player.moveUp() if key_pressed[pygame.K_s] or key_pressed[pygame.K_DOWN]: player.moveDown() if key_pressed[pygame.K_a] or key_pressed[pygame.K_LEFT]: player.moveLeft() if key_pressed[pygame.K_d] or key_pressed[pygame.K_RIGHT]: player.moveRight() #击落 temp_enemies_down = pygame.sprite.groupcollide(enemies, player.bullets, 1, 1) score += len(temp_enemies_down) * 10 for enemy_down in temp_enemies_down: enemy_down.transToDown() enemies_down.add(enemy_down) #绘制背景 screen.fill(0) screen.blit(background, (0, 0)) #绘制FPS fps_text = text_font.render(str(int(clock.get_fps())), True, (128, 128, 128)) fps_rect = fps_text.get_rect() fps_rect.topleft = [10, 10] screen.blit(fps_text, fps_rect) #绘制分数 score_text = text_font.render(str(int(score)), True, (128, 128, 128)) score_rect = score_text.get_rect() score_rect.midbottom = [240, 700] screen.blit(score_text, score_rect) #绘制子弹 player.bullets.draw(screen) #绘制玩家 screen.blit(player.image, player.rect) #绘制敌机 enemies.draw(screen) for enemy_down in enemies_down: if enemy_down.down_cnt > 7: enemies_down.remove(enemy_down) enemy_down.down_cnt += 1 enemies_down.draw(screen) pygame.display.update()
''' v1.12 新增功能: 1、实现子弹的消亡和数量控制 ''' import pygame import time import random COLOR = pygame.Color(0, 0, 0) RED = pygame.Color(255, 0, 0) class MainGame(): #游戏主窗口 window = None SCREEN_HEIGHT = 500 SCREEN_WIDTH = 800 #创建我方坦克 TANK_P1 = None #敌方坦克存储列表 EnemyTank_list = [] #敌方坦克数量 EnemyTank_count = 5 #存储我方子弹的列表 Bullet_list = [] def __init__(self): pass #游戏开始方法
import sys import pygame # Initialize pygame so it runs in the background and manages things pygame.init() red = pygame.Color(255, 0, 0) yellow = pygame.Color(255, 255, 0) green = pygame.Color(0, 255, 0) orange = pygame.Color(255, 165, 0) blue = pygame.Color(0, 255, 0) purple = pygame.Color(255, 0, 255) color_index = 0 colors = [red, yellow, green, orange, blue, purple] # Create a display. Size must be a tuple, which is why it's in parentheses screen = pygame.display.set_mode((400, 300)) x = 0 y = 0 font = pygame.font.SysFont("Arial", 100) text = font.render("abc", True, (100, 200, 255)) # Main loop. Your game would go inside this loop while True: # do something for each event in the event queue (list of things that happen) for event in pygame.event.get(): # Check to see if the current event is a QUIT event print(event) if event.type == pygame.QUIT: # If so, exit the program sys.exit()
""" class: Selector """ import os import pygame LINECOLOR = pygame.Color("black") SELECTCOLOR = pygame.Color("red") LINETHICKNESS = 1 PATH = 'resources/sprites/icons/spells/' class Selector(pygame.sprite.Sprite): """ Is bijna een volledige kopie van de shop selector. """ def __init__(self, x, y, healing_type): super().__init__() self.selector_type = healing_type # hij komt binnen met een hoofdletter van de enum, maar de bestandsnaam heeft een kleine letter self.image = self._load_selected_image(PATH, healing_type.name) pygame.draw.rect(self.image, LINECOLOR, self.image.get_rect(), LINETHICKNESS) self.rect = self.image.get_rect() self.rect.topleft = x, y
def main(): pygame.init() screen = pygame.display.set_mode(display_size, display_flags) width, height = screen.get_size() def to_pygame(p): """Small hack to convert pymunk to pygame coordinates""" return int(p.x), int(-p.y + height) def from_pygame(p): return to_pygame(p) clock = pygame.time.Clock() running = True font = pygame.font.Font(None, 16) ### Physics stuff space = pm.Space() space.gravity = (0.0, -1900.0) space.damping = 0.999 # to prevent it from blowing up. mouse_body = pm.Body(body_type=pm.Body.KINEMATIC) bodies = [] for x in range(-100, 150, 50): x += width / 2 offset_y = height / 2 mass = 10 radius = 25 moment = pm.moment_for_circle(mass, 0, radius, (0, 0)) body = pm.Body(mass, moment) body.position = (x, -125 + offset_y) body.start_position = Vec2d(*body.position) shape = pm.Circle(body, radius) shape.elasticity = 0.9999999 space.add(body, shape) bodies.append(body) pj = pm.PinJoint(space.static_body, body, (x, 125 + offset_y), (0, 0)) space.add(pj) reset_bodies(space) selected = None if not is_interactive: pygame.time.set_timer(pygame.USEREVENT + 1, 70000) # apply force pygame.time.set_timer(pygame.USEREVENT + 2, 120000) # reset pygame.event.post(pygame.event.Event(pygame.USEREVENT + 1)) pygame.mouse.set_visible(False) while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == pygame.KEYDOWN and event.key == pygame.K_p: pygame.image.save(screen, "newtons_cradle.png") if event.type == pygame.USEREVENT + 1: r = random.randint(1, 4) for body in bodies[0:r]: body.apply_impulse_at_local_point((-6000, 0)) if event.type == pygame.USEREVENT + 2: reset_bodies(space) elif (event.type == pygame.KEYDOWN and event.key == pygame.K_r and is_interactive): reset_bodies(space) elif (event.type == pygame.KEYDOWN and event.key == pygame.K_f and is_interactive): r = random.randint(1, 4) for body in bodies[0:r]: body.apply_impulse_at_local_point((-6000, 0)) elif event.type == pygame.MOUSEBUTTONDOWN and is_interactive: if selected != None: space.remove(selected) p = from_pygame(Vec2d(*event.pos)) hit = space.point_query_nearest(p, 0, pm.ShapeFilter()) if hit != None: shape = hit.shape rest_length = mouse_body.position.get_distance( shape.body.position) ds = pm.DampedSpring(mouse_body, shape.body, (0, 0), (0, 0), rest_length, 1000, 10) space.add(ds) selected = ds elif event.type == pygame.MOUSEBUTTONUP and is_interactive: if selected != None: space.remove(selected) selected = None elif event.type == pygame.KEYDOWN: running = False elif event.type == pygame.MOUSEBUTTONDOWN: running = False mpos = pygame.mouse.get_pos() p = from_pygame(Vec2d(*mpos)) mouse_body.position = p ### Clear screen screen.fill(pygame.Color("black")) ### Draw stuff for c in space.constraints: pv1 = c.a.position + c.anchor_a pv2 = c.b.position + c.anchor_b p1 = to_pygame(pv1) p2 = to_pygame(pv2) pygame.draw.aalines(screen, pygame.Color("lightgray"), False, [p1, p2]) for ball in space.shapes: p = to_pygame(ball.body.position) drawcircle(screen, ball.color, p, int(ball.radius), 0) # pygame.draw.circle(screen, ball.color, p, int(ball.radius), 0) ### Update physics fps = 50 iterations = 25 dt = 1.0 / float(fps) / float(iterations) for x in range( iterations): # 10 iterations to get a more stable simulation space.step(dt) ### Flip screen if is_interactive: screen.blit( font.render("fps: " + str(clock.get_fps()), True, pygame.Color("white")), (0, 0), ) screen.blit( font.render( "Press left mouse button and drag to interact", True, pygame.Color("darkgrey"), ), (5, height - 35), ) screen.blit( font.render( "Press R to reset, any other key to quit", True, pygame.Color("darkgrey"), ), (5, height - 20), ) pygame.display.flip() clock.tick(fps)
all_sprites.add(wall65) walls.add(wall65) wall66 = Object(wall, -115, 630, 0) all_sprites.add(wall66) walls.add(wall66) wall67 = Object(wall, -115, 720, 0) all_sprites.add(wall67) walls.add(wall67) #Стенки points = 0 #Количество очков(собранных предметов) #Текст игры points_font = pygame.font.Font(None, 40) #Шрифт и размер points_text = points_font.render("Мана: 0", True, pygame.Color("White")) #Текст, сглаживание и цвет run = True while run: window.blit(bg, (0, 0)) #Наложение фона for event in pygame.event.get(): if event.type == pygame.QUIT: #Выход при нажатии на крестик run = False keys = pygame.key.get_pressed() #Нажатие на клавиатуру #Передвижение игрока if event.type == pygame.KEYDOWN: if keys[pygame.K_w] or keys[pygame.K_UP]: player.rect.y -= player.speed if keys[pygame.K_s] or keys[pygame.K_DOWN]: player.rect.y += player.speed