def update_physics(): """ All the physics of this game :return: """ global last_time, tank1 if health.damage == health.number_of_shots: root.quit() return # Надо вместо закрытия сделать всплывающее окно где будет спрашиваться у пользователя хочет он # перезапустить или нет cur_time = time.time() if last_time: dt = cur_time - last_time dx_tank = tank1.speed.x * dt dy_tank = tank1.speed.y * dt Tank.move_tank(tank1, Rectangle.create_point(dx_tank, dy_tank)) process_rotate_tower(mouse_position, tank1) contact_bullet_with_main_tank() bullets_movement(dt) tanks() tank_with_field(tank1) move_other_tanks(dt) contact_bullet_with_other_tanks() contact_tank_with_tanks() draw_tank(tank1) draw_tank(tank1) for i in range(len(arr_tanks)): draw_tank(arr_tanks[i]) last_time = cur_time # update physics as frequent as possible root.after(16, update_physics)
def shoot(b, t, sens): #calcul de la position de la balle pour faire une trajectoire parabolique b["t"] += 0.1 b["h"] = sens * math.cos(math.radians( Tank.getAngle(t))) * Tank.getV(t) * b["t"] b["x"] += math.ceil(b["h"]) b["p"] = -0.5 * b["t"] * b["t"] * 1.5 + math.sin( math.radians(Tank.getAngle(t))) * Tank.getV(t) * b["t"] b["y"] -= math.ceil(b["p"])
def set_zx_tank_msg(self): msg_data = self.data["msg_data"] tanks = [] for tank_msg in msg_data["players"]: if tank_msg["team"] == self.team_id: new_tank = Tank((tank_msg["x"], tank_msg["y"]), tank_msg["id"]) if tank_msg["super_bullet"] == 1: new_tank.set_super_bullet() tanks.append(new_tank) return tanks
def watering(): response=requests.get(url) condition=response.json()['field8'] #a value is read from field 8 in thingspeak channel, which has been written to using a HTTP post via webapp volume_dosage=float(condition) #sting is converted to float for variabel to be used. print(condition) pump_on_duration = volume_dosage / 0.06 #pump will pump 0.06 litres per second Tank.reading() #takes an initial tank level reading volume_before = Tank.reading() vol_before_round = round(volume_before,1) if volume_before < .02: #if the tank level is empty a message print("Tank is Empty, fill it up") elif volume_before < volume_dosage: #else if the requested water dosage is greater than current tank volume, another message print("There is not enough water in the tank for this water dosage, only", vol_before_round, "litres remaining") else: #when first 2 conditions of if statement are not true, then program continues Tank.pump_on() sleep(pump_on_duration) #using sleep fuction from time to pass variable from pump_on_duratiom calc in line 6 Tank.pump_off() #pump turns off anf then the tank readings are taken again and volume used confirmed sleep(2) #get away from any interferance from pump operation volume_after = round(Tank.reading(),2) volume_used = volume_before - volume_after volume_used = round(volume_used, 2)
def __init__(self, width=25, height=17): """Initialize""" """Initialize PyGame""" pygame.init() """Set the window Size""" self.width = width * 50 self.height = height * 50 """Create the Screen""" self.screen = pygame.display.set_mode((self.width, self.height)) self.tiles = [] self.tank = Tank() self.tank_sprites = pygame.sprite.RenderPlain((self.tank)) self.LoadBoard()
def updateBalle(): #mise à jour de la balle, gestion du tour en fonction de la situation de la balle global Balle if Tank.getIsShooting(tank) == True: Bullet.show(Balle) Bullet.shoot(Balle, tank, 1) Bullet.collide(background, Balle, tank, tank2) Tank.setIsPlaying(tank, False) Tank.setIsPlaying(tank2, True) if Tank.getIsShooting(tank2) == True: Bullet.show(Balle) Bullet.shoot(Balle, tank2, -1) Bullet.collide(background, Balle, tank2, tank) Tank.setIsPlaying(tank2, False) Tank.setIsPlaying(tank, True)
def init(): global tank, background, timeStep, tank2, menu, Fin1, Fin2, choixmap #initialisation de la partie timeStep = 0.05 # creation des elements du jeu tank = Tank.createTank(4, 46, "tank.txt", True) tank2 = Tank.createTank(196, 46, "tank2.txt", False) choixmap = ChooseMap.createChoix("ChoixMap.txt") background = Background.create("bg.txt") menu = Menu.createMenu("menu.txt") Fin1 = Fin.createFin("Win_1.txt") Fin2 = Fin.createFin("Win_2.txt") # interaction clavier tty.setcbreak(sys.stdin.fileno())
def tank_with_field(tank: Tank.Tank) -> None: """ Did the tank go out of the field :param tank: :return: """ arr_x, arr_y = Rectangle.points_rectangle(tank.body.rectangle) tank_max_x = FIELD_X + FIELD_WIDTH - BORDER_WIDTH - max(arr_x) tank_max_y = FIELD_Y + FIELD_HEIGHT - BORDER_WIDTH - max(arr_y) tank_min_x = FIELD_X + BORDER_WIDTH + max(arr_x) tank_min_y = FIELD_Y + BORDER_WIDTH + max(arr_y) touch = contact_with_field_boundaries(tank.body) if touch == "x": new_x = -tank.body.rectangle.centre.x + max(tank_min_x, min(tank.body.rectangle.centre.x, tank_max_x)) Tank.move_tank(tank, Rectangle.create_point(new_x, 0)) tank.speed.x = 0 elif touch == "y": new_y = -tank.body.rectangle.centre.y + max(tank_min_y, min(tank.body.rectangle.centre.y, tank_max_y)) Tank.move_tank(tank, Rectangle.create_point(0, new_y)) tank.speed.y = 0
def update_physics(): """ All the physics of this game :return: """ global last_time, tank1 cur_time = time.time() if last_time: dt = cur_time - last_time dx_tank = tank1.speed.x * dt dy_tank = tank1.speed.y * dt Tank.move_tank(tank1, Rectangle.create_point(dx_tank, dy_tank)) process_rotate_tower(mouse_position) bullets_movement(dt) accommodation_targets() contact_with_target() tank_with_field(tank1) draw_tank(tank1) last_time = cur_time # update physics as frequent as possible root.after(16, update_physics)
def loadSprites(self): self.tank = Tank(self.screen) self.exploration = Exploration(self.screen, (100, 100)) self.map = Map(self.height, self.height, 32, 32) enemy_tank0 = EnemyTank(self.screen) enemy_tank1 = EnemyTank(self.screen) enemy_tank2 = EnemyTank(self.screen) enemy_tank3 = EnemyTank(self.screen) enemy_tank4 = EnemyTank(self.screen) self.enemy_group = pygame.sprite.Group() self.enemy_group.add(enemy_tank0, enemy_tank1, enemy_tank2, enemy_tank3, enemy_tank4) self.empty_map = EmptyMap(self.screen, self.width, self.height) """currently it is tank_sprites,later, you should decouple these"""
def tanks(): global arr_tanks, time_for_tanks if time_for_tanks + TIME_RESPAWN_TANKS < last_time: if len(arr_tanks) < MAXIMUM_NUMBER_OF_TANKS: flag_of_tanks = False new_point = Rectangle.create_point(0, 0) counter = 0 while flag_of_tanks is False: if counter >= 5: return new_point.x, new_point.y = \ random.randrange(FIELD_X + BORDER_WIDTH + int(math.hypot(TANK_HEIGHT, TANK_WIDTH) + 1), FIELD_X + FIELD_WIDTH - BORDER_WIDTH - int(math.hypot(TANK_HEIGHT, TANK_WIDTH) + 1)), \ random.randrange(FIELD_Y + BORDER_WIDTH + int(math.hypot(TANK_HEIGHT, TANK_WIDTH) + 1), FIELD_Y + FIELD_HEIGHT - BORDER_WIDTH - int(math.hypot(TANK_HEIGHT, TANK_WIDTH) + 1)) flag_1 = False for i in range(len(arr_tanks)): if Rectangle.in_rectangle( arr_tanks[i].body.rectangle, new_point, int(math.hypot(TANK_HEIGHT, TANK_WIDTH) + 1)) is True: flag_1 = True break if flag_1 is True: counter += 1 continue if Rectangle.in_rectangle( tank1.body.rectangle, new_point, int(math.hypot(TANK_HEIGHT, TANK_WIDTH) + 1)) is True: counter += 1 continue flag_of_tanks = True arr_tanks.append( Tank.create_tank( new_point.x, new_point.y, TANK_HEIGHT, TANK_WIDTH, COLOR_TANKS, TOWER_TANK_SIZE, TOWER_TANK_SIZE, COLOR_TANKS_TOWER, GUN_HEIGHT, GUN_WIDTH, COLOR_TANKS_GUN, START_SPEED_TANK_X, START_SPEED_TANK_Y, START_ROTATE_TANKS[random.randint( 0, len(START_ROTATE_TANKS) - 1)], time.time())) time_for_tanks = last_time
def process_key(event) -> None: dspeed = 0 # event.char - regular symbols # event.keysym - special keys if event.keysym == "Up" or event.char == "w" or event.char == "ц": dspeed += TANK_ACCELERATION elif event.keysym == "Down" or event.char == "s" or event.char == "ы": dspeed -= TANK_ACCELERATION elif event.keysym == "Left" or event.char == "a" or event.char == "ф": Tank.rotate_tank(tank1, -TANK_TURNING_SPEED) elif event.keysym == "Right" or event.char == "d" or event.char == "в": Tank.rotate_tank(tank1, TANK_TURNING_SPEED) elif event.keysym == "Escape": root.quit() return Tank.speed_change(dspeed, tank1, MAXIMUM_SPEED)
def move_other_tanks( dt ) -> None: # Нужно, чтобы танки двигались не рывками, а плавно(добавить запоминание последнего # движения) global arr_tanks for i in range(len(arr_tanks)): direction = random.choice(['w', 'a', 's', 'd']) factor = random.randint(1, 3) dspeed = 0 if direction == 'w': dspeed += factor * TANK_ACCELERATION elif direction == 's': dspeed -= factor * TANK_ACCELERATION elif direction == 'a': Tank.rotate_tank(arr_tanks[i], -(factor * TANK_TURNING_SPEED)) elif direction == 'd': Tank.rotate_tank(arr_tanks[i], factor * TANK_TURNING_SPEED) Tank.speed_change(dspeed, arr_tanks[i], MAXIMUM_SPEED) dx_tank = arr_tanks[i].speed.x * dt dy_tank = arr_tanks[i].speed.y * dt Tank.move_tank(arr_tanks[i], Rectangle.create_point(dx_tank, dy_tank)) tank_with_field(arr_tanks[i]) process_rotate_tower(tank1.body.rectangle.centre, arr_tanks[i]) shots(arr_tanks[i], TIME_RESPAWN_BULLET_OTHER_TANK)
'$+#$+#2++#+$+++', '+$#$A+$@$++$#++', '++#$$+@@@+$$#++', '++#$++$@$++$#$+', '+++$+#+++#+$#+$', 'A+#$+*+$+4+$++B', '++#$$$$$$$$$+##', '##+++####+@@++$', '$++#++$++++E#+$', '$$$#B$++++A+#$$'] map_max_width = 15 map_max_high = 15 enemy_list = ( (0,6),(2,2),(0,8),(0,10),(0,11) ) me = Tank.Tank((0,4),0) list #局势判断逻辑 Tank def panduanjushi(me,tm,enmey_list,map_max_width,map_max_high): face_enmey_num = 0 enemy_flag = 0 for enemy in enmey_list: if enemy[0] == me.coordinate[0]: for lie in range(0,map_max_width): print("lie:" + str(lie)) if tm[ enemy[0]] [lie] == '$': if lie > me.coordinate[1]: #列 return face_enmey_num + enemy_flag enemy_flag = 0;
while Tank == True: DISPLAYSURF.fill(WHITE) DISPLAYSURF.blit(train1, (0 ,0)) Draw(player1tank) Draw(player1soldaat) for event in pygame.event.get(): if event.type == MOUSEMOTION: mousex, mousey = pygame.mouse.get_pos() if event.type == MOUSEBUTTONUP and mousex > player1.startPosX and mousex < (player1.startPosX + 42) and mousey > player1.startPosY and mousey < (player1.startPosY +42): player1tank = Node(Tank(tank1,(player1.startPosX+42),player1.startPosY),player1tank) pygame.display.update() while train == True: DISPLAYSURF.fill(WHITE) DISPLAYSURF.blit(train1, (0 ,0)) Draw(player1soldaat) Draw(player1tank) for event in pygame.event.get(): if event.type == MOUSEMOTION: mousex, mousey = pygame.mouse.get_pos() if event.type == KEYUP and event.key == K_ESCAPE or (mousex > 1198 and mousex < 1360 and mousey > 690 and mousey < 763): train = False if event.type == MOUSEBUTTONUP and mousex > 936 and mousex < 1114 and mousey > 259 and mousey < 296: soldaat = True train = False
def __init__(self, servDeetz, teamName, tankNames): self.teamName = teamName for tankName in tankNames: self.tanks.append(Tank(servDeetz, self, tankName))
class PyManMain: """The Main PyMan Class - This class handles the main initialization and creating of the Game.""" def __init__(self, width=25, height=17): """Initialize""" """Initialize PyGame""" pygame.init() """Set the window Size""" self.width = width * 50 self.height = height * 50 """Create the Screen""" self.screen = pygame.display.set_mode((self.width, self.height)) self.tiles = [] self.tank = Tank() self.tank_sprites = pygame.sprite.RenderPlain((self.tank)) self.LoadBoard() def MainLoop(self): """This is the Main Loop of the Game""" while 1: self.DrawBoard() for event in pygame.event.get(): """Load All of our Sprites""" self.LoadSprites() if event.type == pygame.QUIT: sys.exit() elif event.type == KEYDOWN: if (event.key == K_RIGHT) or (event.key == K_LEFT) or (event.key == K_UP) or (event.key == K_DOWN): self.tank.move(event.key) self.tank_sprites.draw(self.screen) pygame.display.flip() def LoadSprites(self): """Load the sprites that we need""" pygame.sprite.RenderPlain((self.tank)) def LoadBoard(self): y = 0 x = 0 level = open("levels/level1.lvl", "r").read() for row in level.split("\n"): print "newline" for element in row.split(","): tileMeta = element.split(":") rot = 1 if len(tileMeta) > 1: rot = tileMeta[1] newTile = "" if tileMeta[0] == "0": newTile = Tile(x, y) elif tileMeta[0] == "1": newTile = Tile_Conveyer(x, y, rot) tileSprite = pygame.sprite.RenderPlain(newTile) tileSprite.draw(self.screen) self.tiles.append((newTile, tileSprite)) x += 1 y += 1 self.width = x * 50 self.height = y * 50 x = 0 self.screen = pygame.display.set_mode((self.width, self.height)) def DrawBoard(self): for tile in self.tiles: tile[1].draw(self.screen)
def main(): Green = (34,139,34) White = (255,255,255) Blue = (0,0,255) #Initialize Everything screen_width = 1500 screen_height = 800 pygame.init() screen = pygame.display.set_mode((screen_width, screen_height)) pygame.display.set_caption('Navigation Simulation') #Sprite background bg = Background(0,0, 'b1.jpg') grass = Grass(700,120, 'grass.jpg') #Set game FPS FPS = 30 #Prepare Game Objects clock = pygame.time.Clock() #field Field_x1 = 700 Field_x2 = 1300 Field_y1 = 120 Field_y2 = 720 Buggy_Dimensions = 50 field_sprite_group = pygame.sprite.LayeredUpdates() z = Field_x2-Field_x1 w = Field_y2-Field_y1 Field = Collision_Line(Field_x1,Field_y1,z,w, Green) field_sprite_group.add(Field) Number_of_grids = round(((Field_x2-Field_x1)*(Field_y2-Field_y1))/(Buggy_Dimensions*Buggy_Dimensions)) percentage_per_grid = round((1/Number_of_grids)*100,4) #Field Boundary lines wall_sprite_group_horz_bottom = pygame.sprite.LayeredUpdates() wall_sprite_group_horz_top = pygame.sprite.LayeredUpdates() wall_sprite_group_vert_right = pygame.sprite.LayeredUpdates() wall_sprite_group_vert_left = pygame.sprite.LayeredUpdates() Bound_Line1 = Collision_Line(Field_x1,Field_y1,z,3, White) Inner_Bound_Line1 = Collision_Line(900,320,500,3, White) wall_sprite_group_horz_top.add(Bound_Line1) Bound_Line2 = Collision_Line(Field_x1,Field_y2,z,3, White) Inner_Bound_Line2 = Collision_Line(900,310,500,3, White) Inner_Bound_Line3 = Collision_Line(400,517,700,3, White) wall_sprite_group_horz_bottom.add(Bound_Line2) Bound_Line3 = Collision_Line(Field_x1,Field_y1,3,w, White) Inner_Bound_Line4 = Collision_Line(1100,517,3,400, White) wall_sprite_group_vert_left.add(Bound_Line3) Bound_Line4 = Collision_Line(Field_x2,Field_y1,3,w, White) wall_sprite_group_vert_right.add(Bound_Line4) #Field covering squares Field_Scanned_Squares_Group = pygame.sprite.LayeredUpdates() #text # initialize font; must be called after 'pygame.init()' to avoid 'Font not Initialized' error myfont = pygame.font.SysFont("monospace", 35) # render text label1 = myfont.render("Percentage of Field scanned: ", 1, (255,255,255)) label2 = myfont.render("Number of Grids: ", 1, (255,255,255)) label2_answer = myfont.render(str(Number_of_grids), 1, (255,255,255)) label3 = myfont.render("Each grid in % is apprx: ", 1, (255,255,255)) label3_answer = myfont.render(str(percentage_per_grid), 1, (255,255,255)) #player declarations tank = Tank(400,400, Field_x1, Field_x2, Field_y1, Field_y2, Buggy_Dimensions) #Adding to super group which will handle drawing allsprites = pygame.sprite.LayeredUpdates((bg, field_sprite_group,grass, wall_sprite_group_horz_bottom, wall_sprite_group_horz_top, wall_sprite_group_vert_left, wall_sprite_group_vert_right, Field_Scanned_Squares_Group, tank)) #Main Loop going = True Square_Paint_Bool = False #bgm.play() while going: clock.tick(FPS) '''square place on field for scanned stuff''' if tank.Place_Square_Bool==True and Square_Paint_Bool==True: Square = Collision_Line(tank.Square_X,tank.Square_Y,50,50, Blue) Field_Scanned_Squares_Group.add(Square) allsprites.add(Square) tank.Place_Square_Bool=False '''field scanned stuff''' field_scanned_percentage = tank.Fetch_Field_Percentage_Scanned() if field_scanned_percentage!='##': if field_scanned_percentage>100: field_scanned_percentage=100 label1_answer = myfont.render(str(field_scanned_percentage), 1, (255,255,255)) #Handle Input Events for event in pygame.event.get(): if event.type == QUIT: going = False elif event.type == KEYDOWN and event.key == K_ESCAPE: going = False elif event.type == KEYDOWN and event.key == K_q: tank.Current_X_position = 400 tank.Current_Y_position = 400 tank.Update_Field_Coordinates(Field_x1, Field_y1, Field_x2, Field_y2) tank.Navigate_Bool = False tank.Field_Scanned_Perc = 0 tank.Update_Animation('Reset') '''removing all the blue squares: get the list and then iterate over them removing each from allsprites''' Square_To_Remove_List = Field_Scanned_Squares_Group.sprites() for shape in Square_To_Remove_List: allsprites.remove(shape) elif event.type == KEYDOWN and event.key == K_DOWN: tank.Update_Animation('Move_Down') elif event.type == KEYUP and event.key == K_DOWN: tank.Update_Animation('Idle') elif event.type == KEYDOWN and event.key == K_UP: tank.Update_Animation('Move_Up') elif event.type == KEYUP and event.key == K_UP: tank.Update_Animation('Idle') elif event.type == KEYDOWN and event.key == K_LEFT: tank.Update_Animation('Move_Left') elif event.type == KEYUP and event.key == K_LEFT: tank.Update_Animation('Idle') elif event.type == KEYDOWN and event.key == K_RIGHT: tank.Update_Animation('Move_Right') elif event.type == KEYUP and event.key == K_RIGHT: tank.Update_Animation('Idle') elif event.type == KEYDOWN and event.key == K_p: tank.Current_X_position = Field_x1 tank.Current_Y_position = Field_y1 tank.Update_Animation('Navigate_Right') elif event.type == KEYDOWN and event.key == K_m: tank.Current_X_position = Field_x1+50 tank.Current_Y_position = Field_y1+50 tank.Update_Animation('Machine_Learning_Start') elif event.type == KEYDOWN and event.key == K_w: tank.Print_Ending_Array() elif event.type == KEYDOWN and event.key == K_z: tank.Update_Animation('Diagonal') elif event.type == KEYDOWN and event.key == K_a: wall_sprite_group_horz_top.add(Inner_Bound_Line1) wall_sprite_group_horz_bottom.add(Inner_Bound_Line2) wall_sprite_group_horz_bottom.add(Inner_Bound_Line3) wall_sprite_group_vert_left.add(Inner_Bound_Line4) allsprites.remove(wall_sprite_group_horz_bottom) allsprites.remove(wall_sprite_group_horz_top) allsprites.remove(wall_sprite_group_vert_left) allsprites.add(wall_sprite_group_horz_bottom) allsprites.add(wall_sprite_group_horz_top) allsprites.add(wall_sprite_group_vert_left) elif event.type == KEYDOWN and event.key == K_s: allsprites.remove(Inner_Bound_Line1) allsprites.remove(Inner_Bound_Line2) allsprites.remove(Inner_Bound_Line3) allsprites.remove(Inner_Bound_Line4) wall_sprite_group_horz_top.remove(Inner_Bound_Line1) wall_sprite_group_horz_bottom.remove(Inner_Bound_Line2) wall_sprite_group_horz_bottom.remove(Inner_Bound_Line3) wall_sprite_group_vert_left.remove(Inner_Bound_Line4) allsprites.remove(wall_sprite_group_horz_bottom) allsprites.remove(wall_sprite_group_horz_top) allsprites.remove(wall_sprite_group_vert_left) allsprites.add(wall_sprite_group_horz_bottom) allsprites.add(wall_sprite_group_horz_top) allsprites.add(wall_sprite_group_vert_left) elif event.type == KEYDOWN and event.key == K_r: Square_Paint_Bool=True elif event.type == KEYDOWN and event.key == K_t: Square_Paint_Bool=False allsprites.remove(tank) tank.update(wall_sprite_group_horz_bottom, wall_sprite_group_horz_top, wall_sprite_group_vert_left, wall_sprite_group_vert_right) allsprites.update() allsprites.add(tank) allsprites.move_to_back(bg) #Draw Everything allsprites.draw(screen) screen.blit(label1, (15, 100)) screen.blit(label1_answer, (600, 100)) screen.blit(label2, (15, 200)) screen.blit(label2_answer, (420, 200)) screen.blit(label3, (15, 300)) screen.blit(label3_answer, (520, 300)) pygame.display.flip() pygame.quit()
import random import os import time import sys import Physics #Preventing the recursion limit of the gameloop to close the game sys.setrecursionlimit(10000) Images = ["tankpic2.png", "tankpic.png"] barrier = Barrier.Barrier(random.randint(450, 600), 470) tank1 = Tank.Tank(Images[0], 800, 610, 1, 2) tank2 = Tank.Tank(Images[1], 300, 610, 0, 1) bg = Background.Background() # The introduction screen of the game def game_intro(): intro = True while intro: for event in pygame.event.get(): if event.type == pygame.QUIT:
def test_collide_False(self): tank = Tank.Tank("tankpic.png", 300, 400, 1, 1) assert (self.barrier.collide(tank) == False)
def test_collide_true(self): tank = Tank.Tank("tankpic.png", 400, 540, 1, 1) assert (self.barrier.collide(tank) == True)
for c in range(len(initial_board[r])): if initial_board[r][c] == 1: wall = Wall(initial_board[r][c], r, c, wall1_img) gameDisplay.blit(wall.image, (c * BLOCK_SIZE, r * BLOCK_SIZE)) unbreakableWallGroup.add(wall) elif initial_board[r][c] == 2: wall = Wall(initial_board[r][c], r, c, wall2_img) wallGroup.add(wall) allSprite.add(wall) elif initial_board[r][c] == 0: gameDisplay.blit(road_img, (c * BLOCK_SIZE, r * BLOCK_SIZE)) pygame.display.update() background = gameDisplay.copy() playerTank = Tank(50, 150, "R", playerHealth) allSprite.add(playerTank) enemy_tank1 = TankAI(900, 50, "l", "M", enemyHealth) #testmap = tankSprites.generateCurrentMap(wallGroup, playerTank) #enemy_tank1.findShortestPath((1, 3), testmap) #Helper.print_best_move_map(enemy_tank1.shortest_path_tree, testmap) tankSprites.add(enemy_tank1) allSprite.add(enemy_tank1) enemy_tank3 = TankAI(900, 350, "u", "M", enemyHealth) #enemy tank in class Tank.py tankSprites.add(enemy_tank3) allSprite.add(enemy_tank3) while not gameExit:
def run_game(): pygame.init() setinit = Game_Settings.Settings_of_Show() screen = pygame.display.set_mode( (setinit.screen_width, setinit.screen_height)) pygame.display.set_caption("联机坦克大战") tank1 = Tank.Tank1(screen) tank2 = Tank.Tank2(screen) bullets1 = Group() bullets2 = Group() start_button = Button.Button(screen, 80, 40, (0, 255, 0), (255, 255, 255), "开始游戏", (500, 200)) settings_button = Button.Button(screen, 80, 40, (164, 247, 151), (255, 255, 255), "游戏设置", (500, 300)) help_button = Button.Button(screen, 80, 40, (105, 194, 49), (255, 255, 255), "游戏帮助", (500, 400)) game_settings = Game_Settings.Settings(tank_speed=5, bullet_speed=1, bullet_allow_num=1) bullet_speed1 = Button.Button(screen, 80, 40, (164, 247, 151), (255, 255, 255), "炮弹速度1", (200, 150)) bullet_speed2 = Button.Button(screen, 80, 40, (164, 247, 151), (255, 255, 255), "炮弹速度2", (500, 150)) bullet_speed3 = Button.Button(screen, 80, 40, (164, 247, 151), (255, 255, 255), "炮弹速度3", (800, 150)) tank_speed1 = Button.Button(screen, 80, 40, (164, 247, 151), (255, 255, 255), "坦克速度1", (200, 300)) tank_speed2 = Button.Button(screen, 80, 40, (164, 247, 151), (255, 255, 255), "坦克速度2", (500, 300)) tank_speed3 = Button.Button(screen, 80, 40, (164, 247, 151), (255, 255, 255), "坦克速度3", (800, 300)) login_name_input = TextBox.TextBox(screen, None, None, 20, "隶书", (0, 0, 0), (255, 255, 255), (500, 300), "输入用户名") password_input = TextBox.TextBox(screen, None, None, 20, "隶书", (0, 0, 0), (255, 255, 255), (500, 300), "输入密码") sound_shoot = pygame.mixer.Sound("music//shoot.wav") flag = None login_name = "wsde" ''' while flag!=login_name: screen.fill(setinit.bg_color) for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() if event.type == pygame.KEYDOWN: flag = login_name_input.key_down_text(event) print(flag) login_name_input.draw_textbox() pygame.display.flip() flag = None password: str = "mmnf" print(password) while flag != password: screen.fill(setinit.bg_color) for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() if event.type == pygame.KEYDOWN: flag= password_input.key_down_text(event) password_input.draw_textbox() pygame.display.flip() ''' # 游戏主界面 while True: screen.fill(setinit.bg_color) flag = game_button(start_button, settings_button, help_button) if flag == 0: settings_button.draw() start_button.draw() help_button.draw() if flag == -1: pygame.display.flip() screen.fill(setinit.bg_color) #print("-1") pygame.display.flip() #print(game_settings.tank_speed, game_settings.bullet_speed) score_of_two = Score.Score(screen, tank1, tank2, bullets1, bullets2, setinit) # 进入游戏 main_flag = False while not main_flag: screen.fill(setinit.bg_color) score_of_two.score_change() for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() tank1_control_event(game_settings, tank1, bullets1, screen, sound_shoot) tank2_control_event(game_settings, tank2, bullets2, screen, sound_shoot) score_of_two.score_draw() for i in bullets1.copy(): if i.rect.centerx <= 0 or i.rect.centerx >= 1000: bullets1.remove(i) elif i.rect.centery >= 600 or i.rect.centery <= 0: bullets1.remove(i) for i in bullets1.sprites(): i.draw_bull() for i in bullets2.copy(): if i.rect.centerx <= 0 or i.rect.centerx >= 1000: bullets2.remove(i) elif i.rect.centery >= 600 or i.rect.centery <= 0: bullets2.remove(i) for i in bullets2.sprites(): i.draw_bull() update_screen(tank1, bullets1, tank2, bullets2) main_flag = score_of_two.who_win() pygame.display.flip() score_of_two.who_win() time.sleep(10) if flag == -2: pygame.display.flip() screen.fill(setinit.bg_color) # print("-2") temp_settings = -1 while True: # print("1") if temp_settings == -1: screen.fill(setinit.bg_color) # print("设定难度") bullet_speed1.draw() bullet_speed2.draw() bullet_speed3.draw() tank_speed1.draw() tank_speed2.draw() tank_speed3.draw() temp_settings: int = settings_mode_ui( game_settings, bullet_speed1, bullet_speed2, bullet_speed3, tank_speed1, tank_speed2, tank_speed3) pygame.display.flip() # print(temp_settings) if temp_settings == 1: screen.fill(setinit.bg_color) break if temp_settings == 2: screen.fill(setinit.bg_color) break if temp_settings == 3: screen.fill(setinit.bg_color) break if temp_settings == 4: screen.fill(setinit.bg_color) break if temp_settings == 5: screen.fill(setinit.bg_color) break if temp_settings == 6: screen.fill(setinit.bg_color) break if flag == -3: pygame.display.flip() screen.fill(setinit.bg_color) # print("-2") help_flag = -1 jump_end_button = Button.Button(screen, 40, 50, (164, 247, 151), (255, 255, 255), "结束", (800, 300)) while True: if help_flag == -1: screen.fill(setinit.bg_color) font = pygame.font.SysFont("隶书", 20) text = font.render("服务器端上线后,客户端才可以登录", True, (255, 255, 255), (0, 255, 0)) text_rect = text.get_rect() text_rect.center = screen.get_rect().center screen.blit(text, text_rect) jump_end_button.draw() help_flag = end_help(jump_end_button) pygame.display.flip() if help_flag == 1: break pygame.display.flip()
" use Esc to exit.", font=(FONT_TEXT, FONT_SIZE_TEXT), fill=TEXT_COLOR_ON_TOP) border = canvas.create_rectangle(FIELD_X, FIELD_Y, FIELD_X + FIELD_WIDTH, FIELD_Y + FIELD_HEIGHT, fill=COLOR_FIELD, outline=COLOR_BORDER, width=2 * BORDER_WIDTH) score = create_score(START_VALUE_SCORE, COLOR_SCORE, X_SCORE, Y_SCORE, FONT_SCORE, FONT_SIZE_SCORE) tank1 = Tank.create_tank(FIELD_X + FIELD_WIDTH / 2, FIELD_Y + FIELD_HEIGHT / 2, TANK_HEIGHT, TANK_WIDTH, COLOR_TANK, TOWER_TANK_SIZE, TOWER_TANK_SIZE, COLOR_TOWER_TANK, GUN_HEIGHT, GUN_WIDTH, COLOR_GUN, 0, 0, START_ROTATE_TANK, time.time()) draw_tank(tank1) health = create_health_bar(NUMBER_OF_SHOTS_TO_DESTROY_THE_MAIN_TANK, HEALTH_X, HEALTH_Y, LENGTH_HEALTH_BAR, COLOR_HEALTH_BAR, WIDTH_HEALTH_BAR) mouse_position = Rectangle.create_point(FIELD_X + FIELD_WIDTH / 2, FIELD_Y + FIELD_HEIGHT / 2) last_time = time.time() time_for_tanks = time.time() root.bind("<Key>", process_key) root.bind("<Button-1>", process_shot)
def rungame(): pygame.init() screen = pygame.display.set_mode((800, 600)) pygame.display.set_caption("xx游戏") pos1 = 1 pos2 = 1 tank1 = Tank.Tank1(screen) tank2 = Tank.Tank2(screen) tank1_bullts = Group() tank2_bullts = Group() screen.fill((230, 230, 230)) while True: screen.fill((230, 230, 230)) tank1.draw_tank() tank2.draw_tank() for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() mykeylist = pygame.key.get_pressed() if mykeylist[pygame.K_UP]: pos1 = 1 tank1.rect.centery -= 1 tank1.img = pygame.image.load("picture/坦克1.png") elif mykeylist[pygame.K_RIGHT]: pos1 = 2 tank1.rect.centerx += 1 tank1.img = pygame.image.load("picture/坦克2.png") elif mykeylist[pygame.K_DOWN]: pos1 = 3 tank1.rect.centery += 1 tank1.img = pygame.image.load("picture/坦克3.png") elif mykeylist[pygame.K_LEFT]: pos1 = 4 tank1.rect.centerx -= 1 tank1.img = pygame.image.load("picture/坦克4.png") elif mykeylist[pygame.K_SPACE]: if tank1_bullts.__len__() < 5: newbullet = Bullet.Bullet(screen, tank1, pos1) tank1_bullts.add(newbullet) if mykeylist[pygame.K_w]: pos2 = 1 tank2.rect.centery -= 1 tank2.img = pygame.image.load("picture/坦克_1.png") elif mykeylist[pygame.K_d]: pos2 = 2 tank2.rect.centerx += 1 tank2.img = pygame.image.load("picture/坦克_2.png") elif mykeylist[pygame.K_s]: pos2 = 3 tank2.rect.centery += 1 tank2.img = pygame.image.load("picture/坦克_3.png") elif mykeylist[pygame.K_a]: pos2 = 4 tank2.rect.centerx -= 1 tank2.img = pygame.image.load("picture/坦克_4.png") elif mykeylist[pygame.K_x]: if tank2_bullts.__len__() < 5: newbullet = Bullet.Bullet(screen, tank2, pos2) tank2_bullts.add(newbullet) if tank1.rect.centery < 0: tank1.rect.centery = 0 if tank1.rect.centery > 600: tank1.rect.centery = 600 if tank1.rect.centerx < 0: tank1.rect.centerx = 0 if tank1.rect.centerx > 800: tank1.rect.centerx = 800 tank1_bullts.update() for i in tank1_bullts.sprites(): i.draw_bullet() for i in tank1_bullts.copy(): if i.rect.centerx <= 0 or i.rect.centerx >= 800: tank1_bullts.remove(i) elif i.rect.centery >= 600 or i.rect.centery <= 0: tank1_bullts.remove(i) if tank2.rect.centery < 0: tank2.rect.centery = 0 if tank2.rect.centery > 600: tank2.rect.centery = 600 if tank2.rect.centerx < 0: tank2.rect.centerx = 0 if tank2.rect.centerx > 800: tank2.rect.centerx = 800 tank2_bullts.update() for i in tank2_bullts.sprites(): i.draw_bullet() for i in tank2_bullts.copy(): if i.rect.centerx <= 0 or i.rect.centerx >= 800: tank2_bullts.remove(i) elif i.rect.centery >= 600 or i.rect.centery <= 0: tank2_bullts.remove(i) score_change(tank1_bullts, tank2_bullts, tank1, tank2) pygame.display.flip()
def process_rotate_tower(mouse: Rectangle.Point, tank: Tank.Tank) -> None: """ The tower with the cannon should be rotated to the coordinates of the mouse, but in some way a problem arises and "inversion" :param mouse: :param tank: :return: """ if mouse.x - tank.tower.rectangle.centre.x > 0: angle = pi / 2 - math.atan((-mouse.y + tank.tower.rectangle.centre.y) / (mouse.x - tank.tower.rectangle.centre.x)) elif mouse.x - tank.tower.rectangle.centre.x < 0: angle = -pi / 2 - math.atan( (-mouse.y + tank.tower.rectangle.centre.y) / (mouse.x - tank.tower.rectangle.centre.x)) else: if mouse.y > tank.tower.rectangle.centre.y: angle = pi else: angle = 0 if abs(angle - tank.tower.rectangle.rotate) >= TOWER_TURNING_SPEED: if angle > 0: if angle - pi <= tank.tower.rectangle.rotate <= angle: Tank.rotate_tower_gun(tank, TOWER_TURNING_SPEED) elif -pi <= tank.tower.rectangle.rotate <= angle - pi or angle < tank.tower.rectangle.rotate < pi: Tank.rotate_tower_gun(tank, -TOWER_TURNING_SPEED) else: if angle <= tank.tower.rectangle.rotate <= angle + pi: Tank.rotate_tower_gun(tank, -TOWER_TURNING_SPEED) elif -pi <= tank.tower.rectangle.rotate <= angle or angle + pi < tank.tower.rectangle.rotate < pi: Tank.rotate_tower_gun(tank, TOWER_TURNING_SPEED) else: if angle > 0: if angle - pi <= tank.tower.rectangle.rotate <= angle: Tank.rotate_tower_gun(tank, pi / 360) elif -pi <= tank.tower.rectangle.rotate <= angle - pi or angle < tank.tower.rectangle.rotate < pi: Tank.rotate_tower_gun(tank, -pi / 360) else: if angle <= tank.tower.rectangle.rotate <= angle + pi: Tank.rotate_tower_gun(tank, -pi / 360) elif -pi <= tank.tower.rectangle.rotate <= angle or angle + pi < tank.tower.rectangle.rotate < pi: Tank.rotate_tower_gun(tank, pi / 360)
def registration(sock, team_id): reg_data = { "msg_name": "registration", "msg_data": { "team_id": team_id, "team_name": "test", }} send(sock, reg_data) all_tanks = [] log = log_zx.log for i in range(0,16): all_tanks.append(Tank()) class Game(object): data = None map_width = 0 map_height = 0 our_tank_id = [] enemy_tank_id = [] maps = None enemy_tank = [] star_list = [] coin_list = [] enemy_bullet_list = [] enemy_super_bullet = []
green = (34, 177, 76) light_green = (0, 255, 0) #Screen setup screenwidth = 500 screenheight = 500 size = (screenwidth, screenheight) screen = pygame.display.set_mode(size) pygame.display.set_caption("Tank") #puts all my sprites into a list for easy access all_sprites_list = pygame.sprite.Group() #creating first Tank wolf = Tank(20, 30, red) all_sprites_list.add(wolf) carryOn = True clock = pygame.time.Clock() while carryOn: #Option to keep the game going or quit out at anytime for event in pygame.event.get(): if event.type == pygame.QUIT: carryOn = False elif event.type == pygame.KEYDOWN: if event.kkey == pygame.k_z: carryOn == False #setting up the tank movements for Wolf
# initialize the flask application app = Flask(__name__) SAVE_FILE = "plants.csv" Plants = [] pump_time = 10 # initialize the gpio pin that # will control when the water pump # should run #pump = Pump.Pump(pin = 17, pump_rate = 1) # intialize the tank object tank = Tank.Tank(0, 0) ''' def water(pump_time): ''' '''function to water the plant chain by running the pump''' ''' # run water for specified amount of time pump.run(pump_time) # subtract the amount of water used from the tank tank.currentVol = tank.currentVol - (pump.pump_rate * pump_time) # test if the tank is empty if tank.currentVol == 0: # call the empty tank handler when the tank is empty tank_empty()
def del_tank_polygons(tank: Tank): if len(tank.polygons) != 0: for i in range(len(tank.polygons)): canvas.delete(tank.polygons[i]) tank.polygons = []
class PyManMain: """The Main PyMan Class - This class handles the main initialization and creating of the Game.""" def __init__(self, width=25, height=17): """Initialize""" """Initialize PyGame""" pygame.init() """Set the window Size""" self.width = width * 50 self.height = height * 50 """Create the Screen""" self.screen = pygame.display.set_mode((self.width, self.height)) self.tiles = [] self.tank = Tank() self.tank_sprites = pygame.sprite.RenderPlain((self.tank)) self.LoadBoard() def MainLoop(self): """This is the Main Loop of the Game""" while 1: self.DrawBoard() for event in pygame.event.get(): """Load All of our Sprites""" self.LoadSprites() if event.type == pygame.QUIT: sys.exit() elif event.type == KEYDOWN: if ((event.key == K_RIGHT) or (event.key == K_LEFT) or (event.key == K_UP) or (event.key == K_DOWN)): self.tank.move(event.key) self.tank_sprites.draw(self.screen) pygame.display.flip() def LoadSprites(self): """Load the sprites that we need""" pygame.sprite.RenderPlain((self.tank)) def LoadBoard(self): y = 0 x = 0 level = open("levels/level1.lvl", "r").read() for row in level.split("\n"): print "newline" for element in row.split(","): tileMeta = element.split(":") rot = 1 if len(tileMeta) > 1: rot = tileMeta[1] newTile = "" if (tileMeta[0] == "0"): newTile = Tile(x, y) elif (tileMeta[0] == "1"): newTile = Tile_Conveyer(x, y, rot) tileSprite = pygame.sprite.RenderPlain(newTile) tileSprite.draw(self.screen) self.tiles.append((newTile, tileSprite)) x += 1 y += 1 self.width = x * 50 self.height = y * 50 x = 0 self.screen = pygame.display.set_mode((self.width, self.height)) def DrawBoard(self): for tile in self.tiles: tile[1].draw(self.screen)