def test_boxlist_inside(): b = BoxList() b.append(Box(Rectangle(0, 0, 10, 10))) infrect = Box(Rectangle(-inf, -inf, inf, inf)) assert_equals(1, len(b.inside(infrect))) assert_equals(0, len(b.inside(Box.empty_box)))
def test_clip_identity(): """ Test clipping a box with itself results in the same box """ box1 = Box(Rectangle(-inf, -inf, inf, inf)) box2 = Box(Rectangle(-inf, -inf, inf, inf)) clipped = box1.clip(box2) assert_is_not(clipped, Box.empty_box) assert_equals(clipped.rect, box1.rect)
def test_clip_x_infinite(): """ Test correctly clipping (-inf, 0, inf, 10) with (-inf, -inf, inf, inf) """ box1 = Box(Rectangle(-inf, -inf, inf, inf)) box2 = Box(Rectangle(-inf, 0, inf, 10)) clipped = box1.clip(box2) assert_is_not(clipped, Box.empty_box) assert_equals(clipped.rect, (-inf, 0, inf, 10))
def updateDisplay(): for y in range(MAX_Y): for x in range(MAX_X): if board[x][y]: if started: cell = Box([randint(0, 255), randint(0, 255), randint(0, 255)], [x * SIZE, y * SIZE], SIZE) else: cell = Box([255, 255, 255], [x * SIZE, y * SIZE], SIZE) screen.blit(cell.image, cell.rect) elif not keep_background: cell = Box([0, 0, 0], [x * SIZE, y * SIZE], SIZE) screen.blit(cell.image, cell.rect) pygame.display.update()
def updateDisplay(): for dy in range(MAX_Y): for dx in range(MAX_X): if board[dx][dy] == LIVE_CELL: if rand_col: boxes[dx][dy] = Box([ random.randint(0, 255), random.randint(0, 255), random.randint(0, 255) ], [dx * SIZE, dy * SIZE], SIZE) else: boxes[dx][dy] = Box([255, 255, 255], [dx * SIZE, dy * SIZE], SIZE) elif keep_background == False: boxes[dx][dy] = Box([0, 0, 0], [dx * SIZE, dy * SIZE], SIZE) screen.blit(boxes[dx][dy].image, boxes[dx][dy].rect) pygame.display.update()
def __init__(self, width=None, height=None, box_quantity=None, boxes_x=None, boxes_y=None): if not width: width = randint(5000, 10000) self.width = width if not height: height = randint(5000, 10000) self.height = height if not box_quantity: box_quantity = randint(40, 100) self.Box = Box() self.boxes_x = boxes_x self.boxes_y = boxes_y self.boxes = box_quantity
def run(): #the function inits the whole game and runs its loop def finish_deal(): draw_button.enabled = False pass_button.enabled = False double_button.enabled = False while croupier.points <= 21 and croupier.points < player.points: croupier.draw(cards) images.append( CardImg(screen, (len(croupier.hand) * 160 - 60, settings.screen_height - 500), (150, 200), croupier.hand[-1])) for img in images: img.blitme() pygame.init() settings = Settings() screen = pygame.display.set_mode( (settings.screen_width, settings.screen_height)) pygame.display.set_caption("Blackjack") screen.fill(settings.bg_color) images = [] #declaring necessary objects place_bet_box = InputBox(screen, settings, (100, settings.screen_height - 55), settings.def_box_size) bet_label = Box(screen, settings, color=settings.bg_color, enabled=True, pos=(100, settings.screen_height - 90), size=(150, 30), text='Your bet:') place_bet_button = Button(screen, settings, (220, settings.screen_height - 55), settings.def_box_size, text="Place bet") player = Player() croupier = Player() cards = Cards() balance_label = Box(screen, settings, color=settings.bg_color, pos=(100, 50), size=(200, 30), text="Balance: " + str(player.balance)) your_bet_label = Box(screen, settings, color=settings.bg_color, pos=(100, 80), size=(150, 30), text="Your bet: ") win_loss_label = Box(screen, settings, color=settings.bg_color, pos=(500, settings.screen_height / 2 + 30), size=settings.def_box_size, text='') your_cards_label = Box(screen, settings, color=settings.bg_color, pos=(100, settings.screen_height / 2 + 60), size=settings.def_box_size, text='Your cards:') croupiers_cards_label = Box(screen, settings, color=settings.bg_color, pos=(100, 150), size=(200, 30), text='Croupiers cards:') draw_button = Button(screen, settings, (340, settings.screen_height - 55), size=settings.def_box_size, text='Draw') draw_button.color = settings.dr_button_color pass_button = Button(screen, settings, (460, settings.screen_height - 55), size=settings.def_box_size, text='Pass') pass_button.color = settings.p_button_color double_button = Button(screen, settings, (580, settings.screen_height - 55), size=settings.def_box_size, text='Double') double_button.color = settings.do_button_color place_bet_button.enabled = True def restart(): pygame.display.flip() sleep(3) cards.shuffle() screen.fill(settings.bg_color) your_bet_label.update_text('Your bet:') win_loss_label.update_text('') balance_label.update_text("Balance: " + str(player.balance)) player.hand = [] croupier.hand = [] player.points = croupier.points = 0 place_bet_button.enabled = True while True: #the loop of the game bet_label.blitme() place_bet_box.blitme() place_bet_button.blitme() your_bet_label.blitme() balance_label.blitme() your_cards_label.blitme() croupiers_cards_label.blitme() draw_button.blitme() pass_button.blitme() double_button.blitme() win_loss_label.blitme() if player.points > 21: win_loss_label.update_text("You lose.") draw_button.enabled = False pass_button.enabled = False double_button.enabled = False images = [] restart() elif croupier.points <= 21 and croupier.points > player.points: win_loss_label.update_text("You lose.") images = [] restart() elif croupier.points > 21: player.balance += player.bet * 2 win_loss_label.update_text("You win.") images = [] restart() elif croupier.points == player.points != 0: player.balance += player.bet win_loss_label.update_text("That's a tie.") images = [] restart() for event in pygame.event.get(): place_bet_box.handle_event(event, settings.font) if draw_button.handle_event(event): player.draw(cards) images.append( CardImg(screen, (len(images) * 160 + 100, settings.screen_height - 200), (150, 200), player.hand[-1])) for img in images: img.blitme() if double_button.handle_event(event): player.bet *= 2 player.draw(cards) images.append( CardImg(screen, (len(images) * 160 + 100, settings.screen_height - 200), (150, 200), player.hand[-1])) for img in images: img.blitme() your_bet_label.blitme() player.balance -= player.bet // 2 balance_label.update_text("Balance: " + str(player.balance)) your_bet_label.update_text("Your bet: " + str(player.bet)) finish_deal() if pass_button.handle_event(event): finish_deal() if place_bet_button.handle_event(event): #checks if player has enough money to place a bet player.bet = int(place_bet_box.text) if player.bet <= player.balance and player.bet != 0: player.balance -= player.bet place_bet_button.enabled = False your_bet_label.update_text("Your bet: " + str(player.bet)) draw_button.enabled = True pass_button.enabled = True double_button.enabled = True balance_label.update_text("Balance: " + str(player.balance)) if event.type == pygame.QUIT: e() pygame.display.flip()
def __init__(self, x, y, port, serv_port, host, max_size, name): self.width = x self.height = y self.max_size = max_size self.server = (host, serv_port) self.fight_server = (host, serv_port + 1) self.box_server = (host, serv_port + 2) self.enemies_server = (host, serv_port + 3) self.client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.client_2 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.client_3 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.client_4 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.client.bind((socket.gethostbyname(socket.gethostname()), port)) port += 1 self.client_2.bind((socket.gethostbyname(socket.gethostname()), port)) port += 1 self.client_3.bind((socket.gethostbyname(socket.gethostname()), port)) port += 1 self.client_4.bind((socket.gethostbyname(socket.gethostname()), port)) self.S = Skills() #statistic self.dmg = randint(2, 5) self.hp = randint(7, 12) self.max_hp = self.hp self.chance = randint(5, 10) self.mp = randint(10, 20) self.speed = 5 self.skills = [self.S.basic, self.S.critic, self.S.heal] self.all_skills = [ self.S.basic, self.S.critic, self.S.heal, self.S.harnas_vomit, self.S.tatra_shot ] self.max_lvl = len(self.skills) - 2 self.score = 0 self.next_skill = 3 self.colors = [] for i in range(0, 10): self.colors.append((100, 100, 100)) self.skill_time = 0 self.stats = False pygame.init() #pygame and pygame fonts initialization pygame.font.init() self.your_hero_x = 0 self.your_hero_y = 0 self.hero_x = [] self.hero_y = [] self.hero_status = [] self.hero_names = [] self.hero_addresses_all = [] self.hero_addresses = [] self.world_w = 0 self.world_h = 0 self.boxes = 0 self.boxes_x = [] self.boxes_y = [] self.boxes_status = [] self.Box = Box() self.name = name self.buffer = 100 self.enemy_nr = -2 self.client.sendto(name.encode("utf-8"), self.server) self.client_2.sendto(name.encode("utf-8"), self.server) self.client_3.sendto(name.encode("utf-8"), self.server) self.client_4.sendto(name.encode("utf-8"), self.server) self.client_4.close() self.shot_time = time() self.red = (200, 50, 50) self.blue = (60, 90, 220) self.green = (40, 220, 80) # local enemies init self.enemies = [] self.enemies_x = [] self.enemies_y = [] self.enemies_status = [] self.local_enemy_nr = -2 #getting variables values from server for j in range(0, max_size): self.data, addr = self.client.recvfrom(self.buffer) self.hero_addresses_all.append(self.data.decode("utf-8")) self.hero_addresses.append(self.data.decode("utf-8")) self.data, addr = self.client.recvfrom(self.buffer) self.hero_names.append(self.data.decode("utf-8")) self.data, addr = self.client.recvfrom(self.buffer) self.hero_x.append(int(self.data.decode("utf-8"))) self.data, addr = self.client.recvfrom(self.buffer) self.hero_y.append(int(self.data.decode("utf-8"))) self.data, addr = self.client.recvfrom(self.buffer) self.hero_status.append(int(self.data.decode("utf-8"))) self.data, addr = self.client.recvfrom(self.buffer) self.world_w = (int(self.data.decode("utf-8"))) self.data, addr = self.client.recvfrom(self.buffer) self.world_h = (int(self.data.decode("utf-8"))) self.data, addr = self.client.recvfrom(self.buffer) self.boxes = (int(self.data.decode("utf-8"))) self.data, addr = self.client.recvfrom(self.buffer) self.enemies_amount = int(self.data.decode("utf-8")) for i in range(0, self.boxes): self.data, addr = self.client.recvfrom(self.buffer) self.boxes_x.append(int(self.data.decode("utf-8"))) self.data, addr = self.client.recvfrom(self.buffer) self.boxes_y.append(int(self.data.decode("utf-8"))) self.boxes_status.append(0) for i in range(0, self.enemies_amount): self.data, addr = self.client.recvfrom(self.buffer) self.enemies_x.append(int(self.data)) self.data, addr = self.client.recvfrom(self.buffer) self.enemies_y.append(int(self.data)) self.screen = pygame.display.set_mode((self.width, self.height)) for i in range(0, self.enemies_amount): self.enemies.append(Enemy(self.red, self.screen)) self.enemies_status.append(0) self.real_boxes_x = self.boxes_x self.real_boxes_y = self.boxes_y for i in range(0, self.max_size): if self.hero_names[i] == name: self.your_hero_x = self.hero_x[i] self.your_hero_y = self.hero_y[i] self.hero_x.pop(i) self.hero_y.pop(i) self.hero_addresses.pop(i) self.hero_status.pop(i) self.hero_names.pop(i) self.max_size -= 1 break for i in range(0, self.max_size): print(self.hero_names[i]) print(self.hero_addresses[i]) print(self.hero_x[i]) print(self.hero_y[i]) #worrld and map gen self.worldGen = GenerateWorld(self.world_w, self.world_h, self.boxes, self.boxes_x, self.boxes_y) self.map = Map(self.screen, self.world_w, self.world_h, self.boxes_x, self.boxes_y, self.enemies_x, self.enemies_y) self.bool_map = False self.buttle_x = -100000 self.buttle_y = -100000 self.clock = pygame.time.Clock() #heroes init self.hero = Hero((160, 32, 240), self.screen) self.heroes = [] self.name = name self.xp = 0 self.lvl_xp = 100 self.lvl = 1 print(self.name) for i in range(0, self.max_size): self.heroes.append(Hero((255, 0, 0), self.screen)) self.speed_x = 0 self.speed_y = 0 self.status = 0 self.player_x = (x / 2) - 25 self.player_y = (y / 2) - 25 #rendering "harnas" beer self.image = pygame.image.load("harnas1.png") self.screen.blit(self.image, (500, 250)) self.buck = Bullet(self.screen) self.pos_x = 0 self.pos_y = 0 self.turn = 2 self.first_or_second = 2 self.shot_or_not_shot = False self.timer = time() self.wait_time = 0
def test_boxlist_inside_not_inside(): b = BoxList() b.append(Box(Rectangle(0, 0, 10, 10))) otherbox = Box(Rectangle(-100, -100, -90, -90)) assert_equals(0, len(b.inside(otherbox)))
def test_basic_boxes(): box = Box(Rectangle(11, 22, 33, 44), "text") assert_equals(box.rect, (11, 22, 33, 44)) assert_equals((11, 22, 33, 44), box.rect) assert_equals(22, box.top) assert_equals('text', box.text)
import pygame, random from pygame.locals import * from boxes import Box MAX_X = 20 MAX_Y = 20 SIZE = 15 # MAKING THE BOXES boxes = [''] * MAX_X for i in range(MAX_X): boxes[i] = [''] * MAX_Y pygame.init() screen = pygame.display.set_mode([MAX_X * SIZE, MAX_Y * SIZE]) while pygame.event.poll().type != KEYDOWN: for y in range(MAX_Y): for x in range(MAX_X): boxes[x][y] = Box([ random.randint(0, 255), random.randint(0, 255), random.randint(0, 255) ], [x * SIZE, y * SIZE], SIZE) screen.blit(boxes[x][y].image, boxes[x][y].rect) pygame.display.update() pygame.time.delay(10)
def api_packing_algorithm(boxes_info, items_info, options): ''' non-database calling method which allows checking multiple boxes for packing efficiency Args: session (sqlalchemy.orm.session.Session) boxes_info (List[Dict( weight: float height: float length: float width: float dimension_units: ('inches', 'centimeters', 'feet', 'meters') weight_units: ('grams', 'pounds', 'kilograms', 'onces') name: String )]) items_info (List[Dict( weight: float height: float length: float width: float dimension_units: ('inches', 'centimeters', 'feet', 'meters') weight_units: ('grams', 'pounds', 'kilograms', 'onces') product_name: String )]) options (Dict( max_weight: float )) Returns: Dict[ 'package_contents': List[Dict[ items_packed: Dict[item, quantity] total_weight: float 'best_box': Dict[ weight: float height: float length: float width: float dimension_units: ('inches', 'centimeters', 'feet', 'meters') weight_units: ('grams', 'pounds', 'kilograms', 'onces') name: String ] ] ] ''' boxes = [] items = [] if len(set(box['name'] for box in boxes_info)) < len(boxes_info): # non-unique names for the boxes have been used. raise BoxError('Please use unique boxes with unique names') min_box_dimensions = [0, 0, 0] for item in items_info: dimensions = sorted([ float(item['width']), float(item['height']), float(item['length']) ]) weight_units = item['weight_units'] item_weight = float(item['weight']) items += ([ItemTuple(item['product_name'], dimensions, item_weight)] * item['quantity']) min_box_dimensions = [ max(a, b) for a, b in zip(dimensions, min_box_dimensions) ] if options is not None: max_weight = int(options.get('max_weight', 31710)) else: max_weight = 31710 for box in boxes_info: dimension_units = box.get('dimension_units', units.CENTIMETERS) dimensions = sorted([box['width'], box['length'], box['height']]) if does_it_fit(min_box_dimensions, dimensions): box_weight = float(box['weight']) boxes.append({ 'box': Box(name=box['name'], weight=box_weight, length=dimensions[0], width=dimensions[1], height=dimensions[2]), 'dimensions': dimensions }) if len(boxes) == 0: raise BoxError('Some of your products are too big for your boxes. ' 'Please provide larger boxes.') # sort boxes by volume boxes = sorted(boxes, key=lambda box: volume(box['dimensions'])) # send everything through the packing algorithm package_info = packing_algorithm(items, boxes, max_weight) package_contents_dict = [ get_item_dictionary_from_list(parcel) for parcel in package_info.items_per_box ] package_contents = [] best_box = [ box for box in boxes_info if box['name'] == package_info.box.name ][0] if package_info.last_parcel is not None: last_parcel = [ box for box in boxes_info if box['name'] == package_info.last_parcel.name ][0] else: last_parcel = None for i, parcel in enumerate(package_contents_dict): if i == len(package_contents_dict) - 1 and last_parcel is not None: selected_box = last_parcel total_weight = package_info.last_parcel.weight else: selected_box = best_box total_weight = package_info.box.weight items_packed = {} for item, info in parcel.items(): items_packed[item] = info['quantity'] total_weight += info['quantity'] * info['item'].weight package_contents.append({ 'packed_products': items_packed, 'total_weight': total_weight, 'box': selected_box }) return {'packages': package_contents}