def again(winner, lost, kicked): global repeat if kicked: text = m_font.render("You timed outed!", True, (10, 10, 10)) elif lost: text = m_font.render("Sorry,You lost!", True, (10, 10, 10)) elif winner != '': text = m_font.render(winner, True, (10, 10, 10)) else: text = m_font.render("GAME OVER", True, (10, 10, 10)) x = screen.get_size()[0] // 2 - text.get_size()[0] // 2 y = screen.get_size()[1] // 2 - text.get_size()[1] // 2 text_r = m_font.render('Press "R" key to reload session', True, (0, 0, 0)) x1 = screen.get_size()[0] // 2 - text_r.get_size()[0] // 2 y1 = y + text.get_size()[1] + 25 rep_loop = True while rep_loop: clock.tick(FPS) for event in pygame.event.get(): if event.type == pygame.QUIT: rep_loop = False if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: rep_loop = False if event.key == pygame.K_r: rep_loop = False repeat = True screen.fill((200, 200, 200)) screen.blit(text, (x, y)) screen.blit(text_r, (x1, y1)) pygame.display.flip()
def draw(self): # self.txt = self.font.render(str(self.text), True, self.txt_col) colour = self.colour if not self.is_active else self.act_colour but = pygame.Surface((self.button_w, self.button_h)) but.fill(colour) but.set_alpha(180) screen.blit(but, (self.button_x, self.button_y)) # pygame.draw.rect(screen, colour, (self.button_x, self.button_y, self.button_w, self.button_h)) pygame.draw.rect( screen, self.color_per, (self.button_x, self.button_y, self.button_w, self.button_h), 2) screen.blit(self.txt, (self.txt_x, self.txt_y))
def menu(): global screen, clock, Gmode buttons = [] solo = Button('Solo Game', 100, 200, l_font, (0, 0, 0), (100, 255, 100), (16, 128, 16), start) buttons.append( solo) #НИ В КОЕМ СЛУЧАЕ НЕ ТРОГАТЬ ПРОБЕЛЫ В ТЕКСТЕ, ВСЕ СЛОМАЕТСЯ online = Button('Online ', 100, 250, l_font, (0, 0, 0), (200, 200, 50), (128, 128, 16), start) buttons.append( online) #НИ В КОЕМ СЛУЧАЕ НЕ ТРОГАТЬ ПРОБЕЛЫ В ТЕКСТЕ, ВСЕ СЛОМАЕТСЯ aiM = Button('AI mod ', 100, 300, l_font, (0, 0, 0), (100, 100, 255), (16, 16, 128), start) buttons.append( aiM) #НИ В КОЕМ СЛУЧАЕ НЕ ТРОГАТЬ ПРОБЕЛЫ В ТЕКСТЕ, ВСЕ СЛОМАЕТСЯ quit = Button('Quit ', 100, 350, l_font, (0, 0, 0), (255, 100, 100), (128, 16, 16), start) buttons.append( quit) #НИ В КОЕМ СЛУЧАЕ НЕ ТРОГАТЬ ПРОБЕЛЫ В ТЕКСТЕ, ВСЕ СЛОМАЕТСЯ LoopMenu = True while LoopMenu: clock.tick(FPS) for event in pygame.event.get(): if event.type == pygame.QUIT: LoopMenu = False pos = pygame.mouse.get_pos() for button in buttons: dist_x = pos[0] - button.button_x dist_y = pos[1] - button.button_y if 0 <= dist_x <= button.button_w and 0 <= dist_y <= button.button_h: button.is_active = True if event.type == pygame.MOUSEBUTTONDOWN: Gmode = button.run(button.text) LoopMenu = False else: button.is_active = False screen.blit(poster, (0, 0)) for button in buttons: button.draw() pygame.display.flip()
def draw(self): self.cur_image = (self.cur_image + 1) % len(self.images) body = pygame.Surface((self.width, self.width)) pygame.draw.rect(body, self.color, (0, 0, self.width, self.width)) body.set_colorkey((255, 255, 255)) body.blit(self.images[self.cur_image], (0, 0)) if self.direction == Direction.RIGHT: body = pygame.transform.rotate(body, -90) if self.direction == Direction.LEFT: body = pygame.transform.rotate(body, 90) if self.direction == Direction.UP: body = pygame.transform.rotate(body, 0) if self.direction == Direction.DOWN: body = pygame.transform.rotate(body, 180) screen.blit(body, (self.x, self.y))
def draw_tank(seconds, name, x, y, id, width, height, direction, **kwargs): color = (255, 0, 0) if id == name else (0, 255, 0) cur_image = int(seconds * 30) % len(tankAnim) body = pygame.Surface((width, height)) pygame.draw.rect(body, color, (0, 0, width, height)) body.set_colorkey((255, 255, 255)) body.blit(tankAnim[cur_image], (0, 0)) if direction == 'RIGHT': body = pygame.transform.rotate(body, -90) if direction == 'LEFT': body = pygame.transform.rotate(body, 90) if direction == 'UP': body = pygame.transform.rotate(body, 0) if direction == 'DOWN': body = pygame.transform.rotate(body, 180) screen.blit(body, (x, y)) txt = s_font.render('YOU' if id == name else id, True, (0, 0, 0)) screen.blit(txt, (x + width // 2 - txt.get_size()[0] // 2, y + width + 2))
def drawScoreboard(name, tanks, room): global screen pygame.draw.rect(screen, (255, 255, 255), (1000, 0, 200, 600)) pygame.draw.line(screen, (0, 0, 0), (1000, 0), (1000, 600), 2) info_text = m_font.render('Scoreboard', True, (0, 0, 0)) screen.blit(info_text, (1100 - info_text.get_size()[0] // 2, 10)) tanks.sort(key=lambda x: x['score'], reverse=True) prev_y = 10 + info_text.get_size()[1] for tank in tanks: t_name = 'You' if tank['id'] == name else tank['id'] score_text = s_font.render( "{}: {}, {} HP".format(t_name, tank['score'], tank['health']), True, (0, 0, 0)) screen.blit(score_text, (1100 - score_text.get_size()[0] // 2, prev_y + 10)) prev_y += score_text.get_size()[1] CRoom = s_font.render(f"You in room number {room[5:]}", True, (0, 0, 0)) screen.blit(CRoom, (1100 - CRoom.get_size()[0] // 2, screen.get_size()[1] - CRoom.get_size()[1] - 10))
def draw(self): screen.blit(self.image, self.coord)
def solo(): global clock, screen bullets, tanks, walls = [], [], [] spawnpoints = [] free_spaces = [] # # КАРТЫ МЕНЯТЬ В РУЧНУЮ 1-10 #UPD добавил генератор на вторую карту, меняется всегда. # #.txt формат. W - walls, P - players, Пробел = Пробел :/ # Карты 38x20 символов with open('TanksRss/Maps/map2.txt') as map: lines = map.readlines() i = 0 for line in lines: j = 0 for symb in line: if symb == 'W': walls.append(Wall([j * 32, i * 32])) elif symb == 'P': spawnpoints.append([j * 32, i * 32]) elif symb == ' ': free_spaces.append([j * 32, i * 32]) j += 1 i += 1 tank1 = Tank(spawnpoints[0][0], spawnpoints[0][1], 800 // 6, (62, 132, 45), 32, 'Player 1', fire=pygame.K_RETURN) #ЦВЕТ ТАНКА (62, 132, 45) tank2 = Tank( spawnpoints[1][0], spawnpoints[1][1], 800 // 6, (62, 132, 45), 32, 'Player 2', #ЦВЕТ ТАНКА (62, 132, 45) d_right=pygame.K_d, d_left=pygame.K_a, d_up=pygame.K_w, d_down=pygame.K_s) tanks += [tank1, tank2] box = 0, 0 cycle = 0 winner = '' game_over = False mainloop = True while mainloop: millis = clock.tick(FPS) seconds = millis / 1000 for event in pygame.event.get(): if event.type == pygame.QUIT: mainloop = False if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: mainloop = False game_over = True for tank in tanks: if event.key == tank.fire_key: bullets.append(Bullet(tank)) pressed = pygame.key.get_pressed() for tank in tanks: # print(tank.direction) # stay = True for key in tank.KEY.keys(): if pressed[key]: tank.changeDirection(tank.KEY[key]) tank.is_static = False # stay = False # if stay: # tank.is_static = True screen.fill((200, 150, 200)) screen.blit(bg, (0, 0)) for wall in walls: wall.draw() for i in range(len(tanks)): tanks[i].move(seconds, box, tanks) txt = s_font.render( f'{tanks[i].name}: {tanks[i].lifes} lifes, {tanks[i].score} points', True, (0, 0, 0)) screen.blit(txt, (5, i * txt.get_size()[1] + 5)) for j in range(len(walls)): if checkCollisions(tanks[i], walls[j], False, True): tanks[i].lifes -= 1 del walls[j] break for j in range(len(bullets)): if checkCollisions(tanks[i], bullets[j], False, False): explosion_sound.play() bullets[j].tank.score += 1 tanks[i].lifes -= 1 del bullets[j] break if tanks[i].lifes <= 0: del tanks[i] break for i in range(len(bullets)): bullets[i].move(seconds) if bullets[i].lifetime > bullets[i].destroytime: del bullets[i] break for j in range(len(walls)): if checkCollisions(bullets[i], walls[j], False, True): bullets[i].lifetime = 10 del walls[j] break pygame.display.flip() if len(tanks) == 0: winner = '' game_over = True mainloop = False if len(tanks) == 1: win_tank = tanks[0] winner = f'Congrats! Score: {win_tank.score}. Winner(-s): {win_tank.name}' game_over = True mainloop = False return game_over, winner, False, False
def aiM(): global clock, screen screen = pygame.display.set_mode((1200, 640)) rpc = RpcClient() rpc_response = {} for i in range(1, 31): rpc_response = rpc.room_register(f'room-{i}') if rpc_response.get('status', 200) == 200: break else: print(rpc_response) room, name = rpc_response['roomId'], rpc_response['tankId'] room_state = RoomEvents(room) room_state.start() ai = AI(name) counter = 0 seconds = 0 winner = '' lost = False kicked = False game_over = False mainloop = True while mainloop: millis = clock.tick(FPS) seconds += millis / 1000 for event in pygame.event.get(): if event.type == pygame.QUIT: mainloop = False if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: mainloop = False game_over = True if not room_state.ready: wait_text = 'Wait, loading in progress.' wait_text = l_font.render(wait_text, True, (255, 255, 255)) screen.fill((50, 50, 50)) text_rect = wait_text.get_rect(center=(screen.get_size()[0] // 2, screen.get_size()[1] // 2)) screen.blit(wait_text, text_rect) elif room_state.response: screen.fill((200, 200, 200)) screen.blit(bg, (0, 0)) cur_state = room_state.response tanks = cur_state['gameField']['tanks'] bullets = cur_state['gameField']['bullets'] ai.start(tanks, bullets) if ai.fire: rpc_response = rpc.fire() ai.fire = False if ai.turn_direction: print(ai.turn_direction) rpc_response = rpc.turn_tank(ai.turn_direction) ai.turn_direction = '' remaining_time = cur_state.get('remainingTime', 0) text = m_font.render(f'Remaining time: {remaining_time}', True, (0, 0, 0)) text_rect = text.get_rect(center=(400, 50)) screen.blit(text, text_rect) drawScoreboard(name, tanks, room) for tank in tanks: draw_tank(seconds, name, **tank) for bullet in bullets: draw_bullet(name, **bullet) if len(bullets) > counter: shoot_sound.play(maxtime=1600) counter = len(bullets) if room_state.new and cur_state['hits']: room_state.new = False explosion_sound.play() if next((x for x in cur_state['losers'] if x['tankId'] == name), None): lost = True mainloop = False game_over = True elif next((x for x in cur_state['kicked'] if x['tankId'] == name), None): kicked = True mainloop = False game_over = True elif cur_state['winners']: mainloop = False game_over = True win_text = 'Congrats! Score: {}. Winner(-s): '.format(cur_state["winners"][0]["score"]) winner = win_text + ', '.join(map(lambda i: i['tankId'] if i['tankId'] != name else 'You', cur_state['winners'])) elif not next((x for x in tanks if x['id'] == name), None): lost = True mainloop = False game_over = True pygame.display.flip() room_state.kill = True room_state.join() screen = pygame.display.set_mode((1200, 640)) return game_over, winner, lost, kicked
def online(): global clock, screen screen = pygame.display.set_mode((1200, 640)) rpc = RpcClient() rpc_response = {} for i in range(1, 31): rpc_response = rpc.room_register(f'room-{i}') if rpc_response.get('status', 200) == 200: break else: print(rpc_response) room, name = rpc_response['roomId'], rpc_response['tankId'] room_state = RoomEvents(room) room_state.start() #КНОПОЧКИ------------------------------------ KEYS = { pygame.K_w: 'UP', pygame.K_a: 'LEFT', pygame.K_d: 'RIGHT', pygame.K_s: 'DOWN' } #СТРЕЛЬБА. FIRE_KEY = pygame.K_SPACE counter = 0 seconds = 0 winner = '' lost = False kicked = False game_over = False mainloop = True while mainloop: millis = clock.tick(FPS) seconds += millis / 1000 for event in pygame.event.get(): if event.type == pygame.QUIT: mainloop = False if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: mainloop = False game_over = True if event.key == FIRE_KEY: rpc_response = rpc.fire() if event.key in KEYS: direction = KEYS[event.key] rpc_response = rpc.turn_tank(direction) #ЗАГРУЗКА if not room_state.ready: wait_text = 'Hold on.Game is Loading...' wait_text = l_font.render(wait_text, True, (250, 250, 250)) screen.fill((0, 0, 0)) #НАРИСОВАТЬ ЗАГР. ЭКРАН! text_rect = wait_text.get_rect(center=(screen.get_size()[0] // 2, screen.get_size()[1] // 2)) screen.blit(wait_text, text_rect) elif room_state.response: screen.fill((125, 125, 125)) screen.blit(bg, (0, 0)) cur_state = room_state.response tanks = cur_state['gameField']['tanks'] bullets = cur_state['gameField']['bullets'] remaining_time = cur_state.get('remainingTime', 0) text = m_font.render(f'Time Left: {remaining_time}', True, (255, 0, 0)) text_rect = text.get_rect(center=(600, 75)) screen.blit(text, text_rect) #ТАБЛИЦА СЧЕТА, НЕ ТРОГАТЬ, МОГУТ БЫТЬ ОШИБКИ drawScoreboard(name, tanks, room) for tank in tanks: draw_tank(seconds, name, **tank) #СТРЕЛЬБА for bullet in bullets: draw_bullet(name, **bullet) if len(bullets) > counter: shoot_sound.play(maxtime=1600) counter = len(bullets) #ЗВУК ПОПАДАНИЯ if room_state.new and cur_state['hits']: room_state.new = False explosion_sound.play() #ПРОИГРАВШИЕ if next((x for x in cur_state['losers'] if x['tankId'] == name), None): lost = True mainloop = False game_over = True #КИКНУТЫЕ elif next((x for x in cur_state['kicked'] if x['tankId'] == name), None): kicked = True mainloop = False game_over = True #ПОБЕДИТЕЛИ elif cur_state['winners']: mainloop = False game_over = True win_text = 'Good game! Winner with score: {} is : '.format( cur_state["winners"][0]["score"]) winner = win_text + ', '.join( map( lambda i: i['tankId'] if i['tankId'] != name else 'YOU', cur_state['winners'])) elif not next((x for x in tanks if x['id'] == name), None): lost = True mainloop = False game_over = True pygame.display.flip() #ВОЗВРАТ В МЕНЮ ПОСЛЕ ИГРЫ room_state.kill = True room_state.join() screen = pygame.display.set_mode((1200, 640)) return game_over, winner, lost, kicked