def reflect_ball_by_block(self): for block in self.blocks: if math.fabs(self.ball.top - block.bottom) < self.eps or \ math.fabs(self.ball.bottom - block.top) < self.eps: if block.left <= self.ball.left <= block.right or \ block.left <= self.ball.right <= block.right: self.ball.speed[1] = -self.ball.speed[1] self.score += int(20 * self.multiplier) if block.decrease_and_check_destroying(self.ball.power): self.score += int(100 * self.multiplier) if block.bonus is not None: if block.bonus == "destroy_line": destr = [] for b in self.blocks: if b.y == block.y and b != block: destr.append(b) self.score += len(destr) * 150 for d in destr: self.blocks.remove(d) destr.clear() else: bon = bonus.Bonus(block.bonus, block.left, block.top) self.active_bonuses.append(bon) self.blocks.remove(block) self.multiplier += 0.1 self.check_win() return elif math.fabs(self.ball.left - block.right) < self.eps or \ math.fabs(self.ball.right - block.left) < self.eps: if block.top <= self.ball.top <= block.bottom or \ block.top <= self.ball.bottom <= block.bottom: self.ball.speed[0] = -self.ball.speed[0] self.score += int(20 * self.multiplier) if block.decrease_and_check_destroying(self.ball.power): self.score += int(100 * self.multiplier) if block.bonus is not None: if block.bonus == "destroy_line": destr = [] for b in self.blocks: if b.y == block.y and b != block: destr.append(b) self.score += len(destr) * 150 for d in destr: self.blocks.remove(d) destr.clear() else: bon = bonus.Bonus(block.bonus, block.left, block.top) self.active_bonuses.append(bon) self.blocks.remove(block) self.multiplier += 0.1 self.check_win() return
def start_the_game(): clock = pygame.time.Clock() score = Score(display) rocketa = hero.Hero() # enemy = rocket.Rocket(rocketa, display, 1000, 700) # enemy2 = rocket.Rocket(rocketa, display, 100, 100) coin = bonus.Bonus(display, rocketa, 10) coin_list = [] enemy_list = [] coin_counter = 0 time_start = pygame.time.get_ticks() run = True while run: if pygame.time.get_ticks() % 1500 == 0: enemy_list.append( rocket.Rocket(rocketa, display, random.randint(-200, const.width_display + 50), random.randint(-200, const.height_display + 50))) clock.tick(const.FPS) rocketa.change_xy() for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() keys = pygame.key.get_pressed() display.blit(const.bg, (0, 0)) if keys[pygame.K_LEFT]: rocketa.go_left() rocketa.rotate_left() elif keys[pygame.K_RIGHT]: rocketa.go_right() rocketa.rotate_right() else: rocketa.rect() if keys[pygame.K_ESCAPE]: menu.Pause() if coin.check(): coin_counter += 1 # enemy.is_collision() # enemy2.is_collision() for i in enemy_list: i.enemy_change_xy() i.is_collision() coin.update() score.score_update(coin_counter) # enemy.enemy_change_xy() # enemy2.enemy_change_xy() pygame.display.flip()
def __collide_controller(self, game): """Check for collusions with enemy or player. Manages the health of the enemy and the player. Manages the shield of the player. Manages the sound and graphics effects on kill. Manages game stats. Creates the bonus if enemy is killed. """ for enemy in game.enemies.sprites(): if pygame.sprite.collide_circle(self, enemy) \ and not self.is_enemy_bullet \ and self.direction == -1: self.kill() enemy.health -= self.power sounds.Sound('e_hit').play() if enemy.health <= 0: bonus.Bonus(enemy.bonus, enemy.rect.midtop, game.sprites) enemy.kill() effects.Explosion(enemy.rect.midtop, game, game.sprites) sounds.Sound('death').play() game.gamer.score += game.game_level * 1000 game.gamer.kills += 1 for gamer in game.players.sprites(): if pygame.sprite.collide_circle(self, gamer) \ and self.is_enemy_bullet: self.kill() if gamer.shield > 0: gamer.shield -= self.power sounds.Sound('shield_hit').play() if gamer.shield <= 0: gamer.health += gamer.shield gamer.shield = 0 self.__check_death__(game, gamer) gamer.shield = max(0, gamer.shield) else: gamer.health -= self.power gamer.health = max(0, gamer.health) sounds.Sound('hit').play() self.__check_death__(game, gamer)
def plot_circle_ai(self, filename, p_value): """plot the circle in Aitchison geometry :param filename: file name for the plot :param p_value: p value :return: """ # set the range of x, y ,z axis x = y = z = arange(0.0, 1.0, 0.01) # get the points of the S^3 vector space points = [(a, b, c) for a in x for b in y for c in z if (a + b + c == 1) and a > 0 and b > 0 and c > 0] # get the circle centered at (a, b, c) position with radius r by approximation circle_points = [ el for el in points if abs(bonus.Bonus().cal_distance(el, (0.4, 0.2, 0.4)) - 0.5) < 0.025 ] fig = plt.figure() # ax = fig.add_subplot(111, projection='3d') # plot 3d object ax = fig.add_subplot(111) # plot 2d points = random.sample( points, 500 ) # reduce the number of points to be plotted to make plot faster for x, y, z in points: # points in the space # ax.scatter(x, y, z) ax.scatter(x, y) # project to 2d for x, y, z in circle_points: # points in the circle # ax.scatter(x, y, z, color='red') ax.scatter(x, y, color='red') # project to 2d ax.set_xlim([0, 1]) ax.set_ylim([0, 1]) # ax.set_zlim([0, 1]) ax.set_xlabel('X Label') ax.set_ylabel('Y Label') # ax.set_zlabel('Z Label') fig.savefig(filename)
def __work(self): targetfile = "业务提成明细表.xlsx" if os.path.isfile(targetfile): os.remove(targetfile) # reply = QMessageBox.question(None, "是否覆盖原文件", "目标文件'业务提成明细表.xlsx'已存在,是否重新生成?") # if reply == QMessageBox.Yes: # os.remove(targetfile) # else: # return self.__progressText.setText("正在读取输入文件") self.__updateProgress(3) excel = Easyexcel(self.__files[0], False, self.__readword, self.__writeword) self.__updateProgress(5) self.__progressText.setText("正在读取数据源表") src_dict, src_data = excel.get_sheet("数据源表") self.__updateProgress(25) self.__progressText.setText("正在读取规则表") rul_dict, rul_data = excel.get_sheet("规则") calc_ratio = CalcRatio(rul_dict, rul_data) self.__updateProgress(30) # 注意1:这里默认客户编号表里面所有行都没有空属性且文件结尾前没有空行 # 注意2:这里默认客户编号表里所有客户类型都在规则表的"规则名"列中 self.__progressText.setText("正在读取客户编号表") clt_dict, clt_data = excel.get_sheet("客户编号") client_dict = {} # 映射关系:客户编号->该客户对应行 for row in clt_data: client_dict[row[clt_dict['客户编号']]] = row self.__updateProgress(40) self.__progressText.setText("正在读取指导价表") sht2_head, sht2 = excel.get_sheet("指导价") price = [] for row in sht2: price.append([row[sht2_head['编号']],row[sht2_head['指导单价(未税)\n元/KG']],row[sht2_head['备注']],row[sht2_head['出货开始时间']],row[sht2_head['出货结束时间']]]) self.__updateProgress(45) sht4_head, sht4= excel.get_sheet("主管表") self.__progressText.setText("正在读取售后员表") slr_dict, slr_data = excel.get_sheet("售后员") excel.close() # 关闭输入文件 self.__updateProgress(50) self.__progressText.setText("正在计算:业务员提成明细(售后)") places = [] # 售后员表中的地点名 for row in slr_data: if row[1] != 'None': places.append([row[1],row[5],row[6]]) after_sales = AfterSales(slr_dict, slr_data) as_header, as_content = after_sales.calc_commission(src_dict, src_data, clt_dict, client_dict, calc_ratio) self.__updateProgress(55) self.__progressText.setText("正在计算:业务员提成") bs=bonus.Bonus(price) h1, r1, r2 = bs.calc_commission(src_dict, src_data, clt_dict, client_dict, rul_dict, rul_data, places, sht4) self.__updateProgress(60) self.__progressText.setText("正在写入:"+targetfile) ex = Easyexcel(os.getcwd() + "\\" + targetfile, False) self.__progressText.setText("正在写入:业务员提成明细(售后)") ex.create_sheet("业务员提成明细(售后)") ex.set_sheet("业务员提成明细(售后)", as_header, as_content) self.__updateProgress(70) self.__progressText.setText("正在写入:业务员提成明细") ex.create_sheet("业务员提成明细") ex.set_sheet("业务员提成明细", h1, r1) self.__updateProgress(85) self.__progressText.setText("正在写入:业务员提成打印") ex.create_sheet("业务员提成打印") ex.set_sheet("业务员提成打印", h1, r2) self.__updateProgress(100) print("写入完成") ex.save() ex.close() self.__files.clear() # 清除所有文件
def game(user): global sock_client global sock_server global server_running global client_running global server_global_data global client_data global players_controls global car_draw_obj global cars_obj global bullets_obj global bullets_draw_obj global dead_players global disconnected_players global disconnected_caught global music_stopped global rules_read global bonuses_obj global bonuses_draw_obj user_gui = gui.GameGUI(gameDisplay) pygame.mixer.music.load("media/music/main_theme.wav") pygame.mixer.music.play(-1) music_stopped = False if user == "server": players_ip = server_global_data["players"].keys() else: players_ip = client_global_data["players"].keys() if user == "server": rng_num = random.randint(0,0) bonus_keys = bonus_values.keys() for bonus_key in bonus_keys: for valarr in bonus_values[bonus_key][rng_num]: newbonus = bonus.Bonus(valarr[0],valarr[1],valarr[2]) bonuses_obj.append(newbonus) for player_ip in players_ip: if user == "server": player_lst = list(server_global_data["players"][player_ip]) player_name = server_global_data["names"][player_ip] player_status = server_global_data["status"][player_ip] else: player_lst = list(client_global_data["players"][player_ip]) player_name = client_global_data["names"][player_ip] player_status = client_global_data["status"][player_ip] if player_ip == config["ip"]: client_car_color = player_lst[0] if player_lst[0] == "yellow": car_draw_yellow = car.CarDraw("yellow",player_name,player_lst[1],player_lst[2],player_lst[3],player_lst[4],player_lst[5],player_lst[6],player_status) car_draw_obj["yellow"] = car_draw_yellow cars_obj["yellow"] = car_yellow if player_lst[0] == "red": car_draw_red = car.CarDraw("red",player_name,player_lst[1],player_lst[2],player_lst[3],player_lst[4],player_lst[5],player_lst[6],player_status) car_draw_obj["red"] = car_draw_red cars_obj["red"] = car_red if player_lst[0] == "blue": car_draw_blue = car.CarDraw("blue",player_name,player_lst[1],player_lst[2],player_lst[3],player_lst[4],player_lst[5],player_lst[6],player_status) car_draw_obj["blue"] = car_draw_blue cars_obj["blue"] = car_blue if player_lst[0] == "green": car_draw_green = car.CarDraw("green",player_name,player_lst[1],player_lst[2],player_lst[3],player_lst[4],player_lst[5],player_lst[6],player_status) car_draw_obj["green"] = car_draw_green cars_obj["green"] = car_green #setting camera on client cam = camera.Camera(gameDisplay,car_draw_obj[client_car_color].x - center_w,car_draw_obj[client_car_color].y - center_h) cam_x = cam.x cam_y = cam.y #checking on x if (car_draw_obj[client_car_color].x - center_w > 0) and (car_draw_obj[client_car_color].x + center_w < game_map.map_width): cam_x = car_draw_obj[client_car_color].x - center_w else : if (car_draw_obj[client_car_color].x + center_w >= game_map.map_width): cam_x = game_map.map_width - display_width if (car_draw_obj[client_car_color].x + center_w < display_width): cam_x = 0 #checking on y if (car_draw_obj[client_car_color].y - center_h > 0) and (car_draw_obj[client_car_color].y + center_h < game_map.map_height): cam_y = car_draw_obj[client_car_color].y - center_h else : if (car_draw_obj[client_car_color].y + center_h >= game_map.map_height): cam_y = game_map.map_height - display_height if (car_draw_obj[client_car_color].y + center_h < display_height): cam_y = 0 #creating camera cam = camera.Camera(gameDisplay,cam_x,cam_y) while True: if user == "client": if disconnected_caught == True: disconnected_caught = False error_gui("CONNECTION LOST") break if user == "server": players_ip = server_global_data["players"].keys() else: players_ip = client_global_data["players"].keys() for player_ip in players_ip: if user == "server": player_lst = list(server_global_data["players"][player_ip]) player_status = server_global_data["status"][player_ip] else: player_lst = list(client_global_data["players"][player_ip]) player_status = client_global_data["status"][player_ip] car_draw_obj[player_lst[0]].update(player_lst[1],player_lst[2],player_lst[3],player_lst[4],player_lst[5],player_lst[6],player_status) if user == "server": bullets_draw_obj = server_global_data["bullets"] bonuses_draw_obj = server_global_data["bonuses"] else: bullets_draw_obj = client_global_data["bullets"] bonuses_draw_obj = client_global_data["bonuses"] #Check for exit for event in pygame.event.get(): if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE): pygame.quit() quit() if rules_read == True: #Check for key input keys = pygame.key.get_pressed() if keys[pygame.K_LEFT]: if not ("left" in client_data["controls"]): client_data["controls"].append("left") else: if "left" in client_data["controls"]: client_data["controls"].remove("left") if keys[pygame.K_RIGHT]: if not ("right" in client_data["controls"]): client_data["controls"].append("right") else: if "right" in client_data["controls"]: client_data["controls"].remove("right") if keys[pygame.K_UP]: if not ("up" in client_data["controls"]): client_data["controls"].append("up") else: if "up" in client_data["controls"]: client_data["controls"].remove("up") if keys[pygame.K_DOWN]: if not ("down" in client_data["controls"]): client_data["controls"].append("down") else: if "down" in client_data["controls"]: client_data["controls"].remove("down") if keys[pygame.K_a]: if not ("a" in client_data["controls"]): client_data["controls"].append("a") else: if "a" in client_data["controls"]: client_data["controls"].remove("a") if user == "server": players_controls[config["ip"]] = client_data if user == "server": keys_ip = server_global_data["players"] for key_ip in keys_ip: if server_global_data["players"][key_ip][1] == 0: if key_ip not in dead_players: dead_players.append(server_global_data["players"][key_ip][0]) #обработка всех контролей в массиве players_controls если сервер с учетом коллижинов keys_dict = players_controls.keys() for key in keys_dict: if server_global_data["players"][key][1] != 0 and server_global_data["status"][key] != "disconnected": player_data = players_controls[key] if ("up" in player_data["controls"]) and ("down" not in player_data["controls"]): cars_obj[server_global_data["players"][key][0]].accelerate() if ("down" in player_data["controls"]) and ("up" not in player_data["controls"]): cars_obj[server_global_data["players"][key][0]].deaccelerate() else: cars_obj[server_global_data["players"][key][0]].soften() if ("left" in player_data["controls"]) and ("right" not in player_data["controls"]): cars_obj[server_global_data["players"][key][0]].steerleft() if ("right" in player_data["controls"]) and ("left" not in player_data["controls"]): cars_obj[server_global_data["players"][key][0]].steerright() if ("a" in player_data["controls"]): if cars_obj[server_global_data["players"][key][0]].current_timeout == cars_obj[server_global_data["players"][key][0]].bullet_timeout: new_bullet = bullet.Bullet(cars_obj[server_global_data["players"][key][0]].global_x,cars_obj[server_global_data["players"][key][0]].global_y,cars_obj[server_global_data["players"][key][0]].dir,key) bullets_obj.append(new_bullet) cars_obj[server_global_data["players"][key][0]].current_timeout = cars_obj[server_global_data["players"][key][0]].bullet_timeout-1 if (server_global_data["players"][key][0] not in dead_players) and (server_global_data["players"][key][0] not in disconnected_players): #Players collision for car_clr in cars_obj: if (car_clr not in dead_players) and (car_clr not in disconnected_players): if car_clr != server_global_data["players"][key][0]: car_s = pygame.sprite.Group() car_s.add(cars_obj[car_clr]) if cars_obj[server_global_data["players"][key][0]].check_wall_collide(car_s): cars_obj[car_clr].backup_position() #Wall collision if not cars_obj[server_global_data["players"][key][0]].check_wall_collide(collision_map_s): cars_obj[server_global_data["players"][key][0]].update_global() cars_obj[server_global_data["players"][key][0]].update() n_lst = [server_global_data["players"][key][0],cars_obj[server_global_data["players"][key][0]].health,cars_obj[server_global_data["players"][key][0]].global_x,cars_obj[server_global_data["players"][key][0]].global_y,cars_obj[server_global_data["players"][key][0]].dir,cars_obj[server_global_data["players"][key][0]].weapon_timeout,cars_obj[server_global_data["players"][key][0]].bubble_timeout] server_global_data["players"][key] = n_lst server_global_data["bullets"] = [] for bullet_obj in bullets_obj: bullet_obj.update_global() bullet_s = pygame.sprite.Group() bullet_s.add(bullet_obj) for car_clr in cars_obj: if (car_clr not in dead_players) and (car_clr not in disconnected_players): if car_clr != server_global_data["players"][bullet_obj.owner][0]: if cars_obj[car_clr].check_bullet_collide(bullet_s): cars_obj[car_clr].hit() bullets_obj.remove(bullet_obj) continue if bullet_obj.check_wall_collide(collision_map_s): bullets_obj.remove(bullet_obj) else: bullet_obj.update() server_global_data["bullets"].append([bullet_obj.global_x,bullet_obj.global_y]) server_global_data["bonuses"] = [] for bonus_obj in bonuses_obj: bonus_s = pygame.sprite.Group() bonus_s.add(bonus_obj) for car_clr in cars_obj: if (car_clr not in dead_players) and (car_clr not in disconnected_players): if cars_obj[car_clr].check_bonus_collide(bonus_s,bonus_obj.bonus_type): if bonus_obj.bonus_type == "weapon": if cars_obj[car_clr].weapon_upgraded == False: cars_obj[car_clr].weapon_upgrade() bonuses_obj.remove(bonus_obj) continue if bonus_obj.bonus_type == "medkit": if cars_obj[car_clr].health != num_of_lifes: cars_obj[car_clr].heal() bonuses_obj.remove(bonus_obj) continue if bonus_obj.bonus_type == "shield": if cars_obj[car_clr].bubbled == False: cars_obj[car_clr].defend() bonuses_obj.remove(bonus_obj) continue #here will be a check of collision between cars and bonuses server_global_data["bonuses"].append([bonus_obj.bonus_type,bonus_obj.global_x,bonus_obj.global_y]) #а теперь мы высчитываем насколько нужно сдвинуть камеру cam_x = cam.x cam_y = cam.y #checking on x if (car_draw_obj[client_car_color].x - center_w > 0) and (car_draw_obj[client_car_color].x + center_w < game_map.map_width): cam_x = car_draw_obj[client_car_color].x - center_w car_draw_obj[client_car_color].x = center_w else : if (car_draw_obj[client_car_color].x + center_w >= game_map.map_width): car_draw_obj[client_car_color].x = (car_draw_obj[client_car_color].x - cam.x) #checking on y if (car_draw_obj[client_car_color].y - center_h > 0) and (car_draw_obj[client_car_color].y + center_h < game_map.map_height): cam_y = car_draw_obj[client_car_color].y - center_h car_draw_obj[client_car_color].y = center_h else : if (car_draw_obj[client_car_color].y + center_h >= game_map.map_height): car_draw_obj[client_car_color].y = (car_draw_obj[client_car_color].y - cam.y) #updating camera position if car_draw_obj[client_car_color].health != 0: cam.set_pos(cam_x, cam_y) #заливка пустым цветом gameDisplay.blit(background, (0,0)) #отрисовываем карту с учетом сдвига камеры game_map.update(cam.x,cam.y) game_map_s.draw(gameDisplay) #print(cars_obj[client_car_color].global_x, " ", cars_obj[client_car_color].global_y) #drawing bonuses for bonusXY in bonuses_draw_obj: bonus_to_draw = bonus.BonusDraw(bonusXY[0],bonusXY[1],bonusXY[2]) bonus_to_draw.draw(gameDisplay, -cam.x, -cam.y) #drawing bullets for bulletXY in bullets_draw_obj: bullet_to_draw = bullet.BulletDraw(bulletXY[0],bulletXY[1]) bullet_to_draw.draw(gameDisplay,-cam_x,-cam_y) possible_win = False other_possible = False #drawing cars color_keys = car_draw_obj.keys() for color_key in color_keys: if car_draw_obj[color_key].health != 0 and car_draw_obj[color_key].status != "disconnected": if client_car_color == color_key: possible_win = True car_draw_obj[color_key].draw(gameDisplay,car_draw_obj[color_key].bubbled) else: other_possible = True car_draw_obj[color_key].draw(gameDisplay, car_draw_obj[color_key].bubbled, -cam.x , -cam.y) if (possible_win) and (not other_possible): if music_stopped == False: music_stopped = True pygame.mixer.music.pause() pygame.mixer.Sound.play(victory_sound) #отрисовываем слой 2 : интерфейс user_gui.draw(car_draw_obj[client_car_color].health, car_draw_obj[client_car_color].name,car_draw_obj[client_car_color].weapon_upgraded,car_draw_obj[client_car_color].bubbled,"win") if button('EXIT', display_width - get_button_size('EXIT')[0] - 15, display_height - get_button_size('EXIT')[1] - 15 , get_button_size('EXIT')[0], get_button_size('EXIT')[1], white, yellow): if user == "server": #sock_server.close() server_running = False else: sock_client.close() client_running = False pygame.mixer.pause() break #pygame.quit() #quit() else: user_gui.draw(car_draw_obj[client_car_color].health, car_draw_obj[client_car_color].name,car_draw_obj[client_car_color].weapon_upgraded,car_draw_obj[client_car_color].bubbled) if car_draw_obj[client_car_color].health == 0: if button('EXIT', display_width - get_button_size('EXIT')[0] - 15, display_height - get_button_size('EXIT')[1] - 15 , get_button_size('EXIT')[0], get_button_size('EXIT')[1], white, yellow): if user == "server": #sock_server.close() server_running = False else: sock_client.close() client_running = False pygame.mixer.pause() break #pygame.quit() #quit() if music_stopped == False: music_stopped = True pygame.mixer.music.pause() pygame.mixer.Sound.play(lose_sound) if rules_read == False: gameDisplay.blit(rules_image, [display_width // 2 - rules_image.get_width() // 2, display_height // 2 - rules_image.get_height() // 2]) if button('OK AND GO', display_width // 2 - get_button_size('OK AND GO')[0] // 2, display_height // 2 - get_button_size('OK AND GO')[1] // 2 + 110 , get_button_size('OK AND GO')[0], get_button_size('OK AND GO')[1], white, yellow): rules_read = True #апдейтим экран pygame.display.flip() ####### clock.tick(30)
0] <= self.x + 50: if self.y >= position_to_kii[1] - 50 and self.y <= position_to_kii[ 1]: return True return False while i < 4: # Тут создаются обьекты класса "Enemy" print(len(enemys_poistions)) en[i] = Enemy(win, enemys_poistions) enemys_poistions.append(en[i].enemy_posreturn()) i += 1 bonus = bonus.Bonus(win) pl = Player() def shot_or_not(bull, en): try: for i in range(len(bull)): if bull[i] == None: bull.pop(i) elif bull[i].y > 10: bull[i].shottiing() for j in range(len(en)): if bull[i].bullet_posittion1(en[j].enemy_posreturn()): global score score += 20 en[j].bumbum()
def game(): import pygame, sys, pygame.mixer from pygame.locals import * import common_pygame import enemy import load_resources import random import ship import background import hud import bonus import menu import effects import particles import smoke import lasers import input import lib.eztext import scoreboard pygame = common_pygame.pygame screen= common_pygame.screen clock = common_pygame.clock #dictionnaries that will contain all our needed resources sounds = dict() single_sprites = dict() sprite_sequences = dict() #create the menu ( we create it here in order to let the menu object read the configuration, #to set the correct screen size menu=menu.Menu() #fill up our dictionnaries (sounds, single_sprites, sprite_sequences) = load_resources.load_resources(pygame) #sprite proprieties being used later laser_height = single_sprites['sprite_laser.png'].get_height() laser_width = single_sprites['sprite_laser.png'].get_width() #lasershoot_width = single_sprites['sprite_lasershoot.png'].get_width() #lasershoot_height = single_sprites['sprite_lasershoot.png'].get_height() #the ship's laser list laserlist = list() lasershoot = 7 tinyfont = pygame.font.Font(None, 16) font = pygame.font.Font(None,32) font2 = pygame.font.Font(None, 150) background = background.BackGen(single_sprites) hud= hud.Hud(single_sprites, menu, sounds) #start the menu menu.init2(single_sprites, sounds, background, hud) menu.launch(0) ship = ship.Ship(single_sprites, sounds, menu, sprite_sequences ) ship.setWeapon(1) ship_top = screen.get_height()-ship.height ship_left = screen.get_width()/2 - ship.width/2 decal_laser_ship_x = (ship.width /2) coord_laser_ship_y = -40 #the enemy laser system lasers = lasers.Lasers(single_sprites, ship) enemy_list = list() compteur = 0 countdown=0 #to know if it's ok to shoot compteur_shoot=int(0) nbAsteroids=0 #current_sprite=0 it=0 #bonus processing scoreBonus=bonus.Bonus(sounds, menu) thegame=True level =-1 spawnedBoss=False while thegame: compteur_shoot=compteur_shoot+1 #every 2 minutes, level up if compteur%(30*60)==0: level=level+1 #level 1 : 3 enemies every 3 seconds if level==1: if compteur%(3*20)==0: boolrand = bool(random.getrandbits(1)) for i in range(1): enemy_list.append(enemy.Enemy( single_sprites, sprite_sequences , sounds, i*80+250+60*int(boolrand), -single_sprites['sprite_enemy.png'].get_height(),boolrand \ , 0, menu)) #print (enemy_list[0].nbAsteroids) if level==2: if compteur%(2*60)==0: boolrand = bool(random.getrandbits(1)) for i in range(6): enemy_list.append(enemy.Enemy( single_sprites, sprite_sequences , sounds, i*80+190+60*int(boolrand), -single_sprites['sprite_enemy.png'].get_height(),boolrand \ , 0, menu)) #print (enemy_list[0].nbAsteroids) if level==3 and not spawnedBoss: enemy_list.append(enemy.Enemy( single_sprites, sprite_sequences , sounds, 400-single_sprites['boss1.png'].get_width()/2, -single_sprites['boss1.png'].get_height(),1 ,\ 2, menu)) spawnedBoss=True #if compteur%(1*60)==0: #boolrand = bool(random.getrandbits(1)) #for i in range(9): #enemy_list.append(enemy.Enemy( single_sprites, sprite_sequences , sounds, #i*80+80+60*int(boolrand), -single_sprites['sprite_enemy.png'].get_height(),boolrand , 0, menu)) #print (enemy_list[0].nbAsteroids) #new asteroids #if ((len(enemy_list)==0) or enemy_list[0].nbAsteroids<=2) and compteur%150==0: if compteur%150==0: boolrand = bool(random.getrandbits(1)) enemy_list.append(enemy.Enemy( single_sprites, sprite_sequences , sounds, random.randrange(0, screen.get_width()), -32,boolrand , 1, menu)) enemy_list[0].nbAsteroids=enemy_list[0].nbAsteroids+1 #if (len(enemy_list)>=0): #print( compteur = compteur +1 background.updatecompteur() clock.tick_busy_loop(30) screen.fill((0,0,0)) #blit the stars and the asteroids background.blitStars() background.blitPlanets() #show the fog background.blitFog() mouse_x,mouse_y=pygame.mouse.get_pos() for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() #elif event.type == MOUSEBUTTONDOWN: #sounds['laser.wav'].play() #laserlist.append( (ship.position_ship_x+ship.width/2 -laser_width/2 , #ship.position_ship_y-laser_height)) #lasershoot = 7 if pygame.key.get_pressed()[K_ESCAPE]: #launch menu with resume option menu.launch(1) if pygame.key.get_pressed()[K_LEFT]: if ship.currentspeed_x >=0: ship.currentspeed_x = -5 if ship.currentspeed_x > -20: ship.currentspeed_x = ship.currentspeed_x -1 elif pygame.key.get_pressed()[K_RIGHT]: if ship.currentspeed_x <= 0: ship.currentspeed_x = 5 if ship.currentspeed_x < 20: ship.currentspeed_x = ship.currentspeed_x +1 if pygame.key.get_pressed()[K_DOWN]: if ship.currentspeed_y <= 0: ship.currentspeed_y = 5 if ship.currentspeed_y < 20: ship.currentspeed_y = ship.currentspeed_y +1 elif pygame.key.get_pressed()[K_UP]: if ship.currentspeed_y >= 0: ship.currentspeed_y = -5 if ship.currentspeed_y > -20: ship.currentspeed_y = ship.currentspeed_y -1 if pygame.key.get_pressed()[K_LEFT] ==0 and pygame.key.get_pressed()[K_RIGHT]==0 \ and pygame.key.get_pressed()[K_UP] ==0 and pygame.key.get_pressed()[K_DOWN]==0: ship.currentspeed_y=0 ship.currentspeed_x=0 #are we shooting ? if pygame.key.get_pressed()[K_SPACE]: (compteur_shoot, laserlist) =ship.shoot(laserlist,compteur_shoot, laser_width, laser_height) #update the ships position ship.updatePosition() #blit the right thing ship.blit(compteur) #blit the laser shot fire #if lasershoot >= 0 : #screen.blit(single_sprites['sprite_lasershoot.png'],(ship.position_ship_x+ship.width/2 -lasershoot_width/2, #ship.position_ship_y )) #lasershoot = lasershoot -1 oldLasers = list() #blit the lasers for index in range(len(laserlist)): (currentx, currenty, lasertype) = laserlist[index] if currenty>=-40: #it's a normal laser if lasertype==1: screen.blit(single_sprites['sprite_laser_light.png'],(currentx-29-32,currenty-22-32)) screen.blit(single_sprites['sprite_laser.png'],(currentx,currenty)) currenty = currenty - 15 #it's a plasma ball else : screen.blit(single_sprites['ball1_light.png'],(currentx-10,currenty-10)) screen.blit(single_sprites['ball1.png'],(currentx,currenty)) currenty = currenty - 20 laserlist[index]=(currentx,currenty, lasertype) else: oldLasers.append((currentx,currenty, lasertype)) #purge old lasers for index in range(len(oldLasers)): laserlist.remove(oldLasers[index]) deadEnemies=list() #blit and process the enemies for index in range(len(enemy_list)): oldLasers=enemy_list[index].processHit(laserlist, ship) enemy_list[index].update(ship, lasers) if enemy_list[index].alive==False: deadEnemies.append(enemy_list[index]) #purge old lasers for index in range(len(oldLasers)): laserlist.remove(oldLasers[index]) #purge dead enemies for index in range(len(deadEnemies)): enemy_list.remove(deadEnemies[index]) #blit and process the enemy's lasers lasers.update() #blit the hud level = hud.blit(ship, level) #process ship hurt countdown = ship.processHurt(countdown) if (ship.life<=0): thegame=False #youlost = font2.render("Game over", True, (255,255, 255)) #presskey = font.render("press any key to quit", True, (255,255, 255)) #yourscore = font.render("Your score : "+ str(ship.score), True, (255,255, 255)) youlost = pygame.font.Font("BITSUMIS.TTF",105).render("Game over", True, (255,255, 255)) presskey = pygame.font.Font("BITSUMIS.TTF",23).render("press escape to quit", True, (255,255, 255)) yourscore = pygame.font.Font("BITSUMIS.TTF",30).render("Your score : "+ str(ship.score), True, (255,255, 255)) yourname = pygame.font.Font("BITSUMIS.TTF",55).render("Your name : ", True, (255,255, 255)) #play a the explosion sound menu.play_sound(sounds['explosion2.wav']) #blit the explosion screen.blit(sprite_sequences['sprite_explosion_list_asteroid.png'][3],\ (ship.position_ship_x-64,ship.position_ship_y-64)) #fade to red effects.fadeToColor(255, 0, 0) #scoreBonus.ProcessBonus(ship) particles.blitAndUpdate() smoke.blitAndUpdate() pygame.display.flip() exitloop = True exitcountdown =0 name = "" car = "" txtbx = lib.eztext.Input(maxlength=45, color=(255,50,50), prompt='Your name: ') txtbx.set_pos( 230,180) txtbx.set_font(pygame.font.Font("BITSUMIS.TTF",30)) nametyped = False scoreObj = scoreboard.ScoreBoard() while exitloop: exitcountdown =exitcountdown+ 1 clock.tick_busy_loop(30) screen.fill((0,0,0)) background.updatecompteur() background.blitStars() background.blitPlanets() #show the fog background.blitFog() screen.blit(youlost, (110,35 )) screen.blit(yourscore, (130,150 )) #screen.blit(yourname, (180,330 )) #screen.blit(pygame.font.Font("BITSUMIS.TTF",55)\ #.render(name, True, (255,0, 0)), (300, 330)) screen.blit(presskey, (270,520 )) #car = str(input.keyInput()) #if isinstance(car, str): #name = name + pygame.key.name(car) #print("name : " + name) #input.keyInput() if not nametyped: # update txtbx txtbx.update(pygame.event.get()) # blit txtbx on the sceen #if exitcountdown%20>10: #txtbx.draw(screen) if txtbx.hasTyped() ==False: if exitcountdown%20>10: txtbx.draw(screen) elif nametyped == False: txtbx.draw(screen) if exitcountdown==30: menu.play_sound(sounds["loser.wav"]) if exitcountdown>=30: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() if pygame.key.get_pressed()[K_ESCAPE]: print("exiting") exit() exitloop=False if pygame.key.get_pressed()[K_RETURN]: if not nametyped: scoreObj.addScore(ship.score, txtbx.getText()) nametyped = True scoreObj.printScore() #if pygame.KEYDOWN: #print("exiting") #exit() pygame.display.flip()
running = False elif event.type == pygame.KEYDOWN: if event.key == pygame.K_SPACE: if not player.hidden: player.shoot() hits = pygame.sprite.groupcollide(asteroids, rockets, True, True) for hit in hits: expl_sound.play() score += 1 expl = explosion.Explosion(hit.rect.center, 'sm') all_sprites.add(expl) if random.random() > settings.POW_CHANCE: b = bonus.Bonus(hit.rect.center) all_sprites.add(b) powerups.add(b) create_asteroid() hits = pygame.sprite.spritecollide(player, powerups, False) for hit in hits: if not player.hidden and not player.invisible: if hit.type == 'shield': if player.lives < 3: heal_sound.play() player.lives += 1 else: repair_sound.play()
def generate_bonuses(self): x = random.randint(0, 10000) if x < 5: #print("SUKCES!") self.bonuses.append(bns.Bonus()) self.bonuses_group.add(self.bonuses[-1])
rul_dict, rul_data = excel.get_sheet("规则") clt_dict, clt_data = excel.get_sheet("客户编号") client_dict = {} # 映射关系:客户编号->该客户对应行 for row in clt_data: client_dict[row[clt_dict['客户编号']]] = row print(client_dict) sht2_head, sht2 = excel.get_sheet("指导价") price = [] for row in sht2: price.append([row[sht2_head['编号']],row[sht2_head['指导单价(未税)\n元/KG']],row[sht2_head['备注']],row[sht2_head['出货开始时间']],row[sht2_head['出货结束时间']]]) sht4_head, sht4= excel.get_sheet("主管表") slr_dict, slr_data = excel.get_sheet("售后员") excel.close() # 关闭输入文件 places = [] # 售后员表中的地点名 for row in slr_data: if row[1] != 'None': places.append([row[1], row[5], row[6]]) bs=bonus.Bonus(price) h1, r1, r2 = bs.calc_commission(src_dict, src_data, clt_dict, client_dict, rul_dict, rul_data, places, sht4) print(r1) print() print(h1)
def create_bonus(ai_settings, screen, stats, sb, bullets, set_bonus, explosions): new_bonus = bon.Bonus(ai_settings, screen, stats, sb, bullets, explosions) set_bonus.add(new_bonus)