【python游戏】这年头塔除了拆还能干什么?这款好玩上瘾的塔防游戏,了解一下嘛( 三 )

<= 0:returnfor event in pygame.event.get():if event.type == pygame.QUIT:pygame.quit()sys.exit()if event.type == pygame.MOUSEBUTTONUP:# 左键选物品if event.button == 1:# 鼠标点击在地图上if self.map_rect.collidepoint(event.pos):if self.mouseCarried:if self.mouseCarried[0] == 'turret':self.buildTurret(event.pos)elif self.mouseCarried[0] == 'XXX':self.sellTurret(event.pos)# 鼠标点击在工具栏elif self.toolbar_rect.collidepoint(event.pos):for button in self.buttons:if button.rect.collidepoint(event.pos):if button.text == 'T1':button.onClick()elif button.text == 'T2':button.onClick()elif button.text == 'T3':button.onClick()elif button.text == 'XXX':button.onClick()elif button.text == 'Pause':button.onClick(screen)elif button.text == 'Quit':button.onClick()# 显然只能有一个按钮被点击break# 右键释放物品if event.button == 3:self.mouseCarried = []# 按中间键手动控制炮塔射箭方向一次,否则自由射箭if event.button == 2:Manualshot = Trueif event.type == GenEnemiesEvent:genEnemiesFlag = Trueif event.type == GenEnemyEvent:genEnemyFlag = True# 生成敌人# 生成的敌人随当前已生成敌人的总次数的增加而变强变多if genEnemiesFlag:genEnemiesFlag = FalsegenEnemiesNum += 1idx = 0for key, value in difficulty_dict.items():idx += 1if idx == len(difficulty_dict.keys()):enemyRange = value['enemyRange']numEnemy = value['numEnemy']breakif genEnemiesNum <= int(key):enemyRange = value['enemyRange']numEnemy = value['numEnemy']breakif genEnemyFlag and numEnemy:genEnemyFlag = FalsenumEnemy -= 1enemy = Enemy.Enemy(random.choice(range(enemyRange)))self.EnemiesGroup.add(enemy)# 射箭for turret in self.builtTurretGroup:if not Manualshot:position = turret.position[0] + self.elementSize // 2, turret.position[1]arrow = turret.shot(position)else:position = turret.position[0] + self.elementSize // 2, turret.position[1]mouse_pos = pygame.mouse.get_pos()angle = math.atan((mouse_pos[1]-position[1])/(mouse_pos[0]-position[0]+1e-6))arrow = turret.shot(position, angle)has_control = Trueif arrow:self.arrowsGroup.add(arrow)else:has_control = Falseif has_control:has_control = FalseManualshot = False# 移动箭和碰撞检测for arrow in self.arrowsGroup:arrow.move()points = [(arrow.rect.left, arrow.rect.top), (arrow.rect.left, arrow.rect.bottom), (arrow.rect.right, arrow.rect.top), (arrow.rect.right, arrow.rect.bottom)]if (not self.map_rect.collidepoint(points[0])) and (not self.map_rect.collidepoint(points[1])) and \(not self.map_rect.collidepoint(points[2])) and (not self.map_rect.collidepoint(points[3])):self.arrowsGroup.remove(arrow)del arrowcontinuefor enemy in self.EnemiesGroup:if pygame.sprite.collide_rect(arrow, enemy):enemy.life_value -= arrow.attack_powerself.arrowsGroup.remove(arrow)del arrowbreakself.draw(screen, map_path)'''将场景画到游戏界面上'''def draw(self, screen, map_path):self.drawToolbar(screen)self.loadMap(screen, map_path)self.drawMouseCarried(screen)self.drawBuiltTurret(screen)self.drawEnemies(screen)self.drawArrows(screen)pygame.display.flip()'''画出所有射出的箭'''def drawArrows(self, screen):for arrow in self.arrowsGroup:screen.blit(arrow.image, arrow.rect)'''画敌人'''def drawEnemies(self, screen):for enemy in self.EnemiesGroup:if enemy.life_value <= 0:self.money += enemy.rewardself.EnemiesGroup.remove(enemy)del enemycontinueres = enemy.move(self.elementSize)if res:coord = self.find_next_path(enemy)if coord:enemy.reached_path.append(enemy.coord)enemy.coord = coordenemy.position = self.coord2pos(coord)enemy.rect.left, enemy.rect.top = enemy.positionelse:self.health -= enemy.damageself.EnemiesGroup.remove(enemy)del enemycontinue# 画血条greenLen = max(0, enemy.life_value / enemy.max_life_value) * self.elementSizeif greenLen > 0:pygame.draw.line(screen, green, (enemy.position), (enemy.position[0]+greenLen, enemy.position[1]), 1)if greenLen < self.elementSize:pygame.draw.line(screen, red, (enemy.position[0]+greenLen, enemy.position[1]), (enemy.position[0]+self.elementSize, enemy.position[1]), 1)screen.blit(enemy.image, enemy.rect)'''画已经建造好的炮塔'''def drawBuiltTurret(self, screen):for turret in self.builtTurretGroup:screen.blit(turret.image, turret.rect)'''画鼠标携带物'''def drawMouseCarried(self, screen):if self.mouseCarried:position = pygame.mouse.get_pos()coord = self.pos2coord(position)position = self.coord2pos(coord)# 在地图里再画if self.map_rect.collidepoint(position):if self.mouseCarried[0] == 'turret':screen.blit(self.mouseCarried[1].image, position)self.mouseCarried[1].coord = coordself.mouseCarried[1].position = positionself.mouseCarried[1].rect.left, self.mouseCarried[1].rect.top = positionelse:screen.blit(self.mouseCarried[1], position)'''画工具栏'''def drawToolbar(self, screen):# 信息显示框#左pygame.draw.rect(screen, info_color, self.leftinfo_rect)leftTitle = self.info_font.render('Player info:', True, white)moneyInfo = self.info_font.render('Money: ' + str(self.money), True, white)healthInfo = self.info_font.render('Health: ' + str(self.health), True, white)screen.blit(leftTitle, (self.leftinfo_rect.left+5, self.leftinfo_rect.top+5))screen.blit(moneyInfo, (self.leftinfo_rect.left+5, self.leftinfo_rect.top+35))screen.blit(healthInfo, (self.leftinfo_rect.left+5, self.leftinfo_rect.top+55))#右pygame.draw.rect(screen, info_color, self.rightinfo_rect)rightTitle = self.info_font.render('Selected info:', True, white)screen.blit(rightTitle, (self.rightinfo_rect.left+5, self.rightinfo_rect.top+5))# 中间部分pygame.draw.rect(screen, grey, self.toolbar_rect)for button in self.buttons:mouse_pos = pygame.mouse.get_pos()if button.rect.collidepoint(mouse_pos):self.showSelectedInfo(screen, button)button_color = button_color1else:button_color = button_color2pygame.draw.rect(screen, button_color, button.rect)buttonText = self.button_font.render(button.text, True, white)buttonText_rect = buttonText.get_rect()buttonText_rect.center = (button.rect.centerx, button.rect.centery)screen.blit(buttonText, buttonText_rect)'''显示被鼠标选中按钮的作用信息'''def showSelectedInfo(self, screen, button):if button.text == 'T1':T1 = Turret.Turret(0)selectedInfo1 = self.info_font.render('Cost: '+str(T1.price), True, white)selectedInfo2 = self.info_font.render('Damage: '+str(T1.arrow.attack_power), True, white)selectedInfo3 = self.info_font.render('Affordable: '+str(self.money>=T1.price), True, white)screen.blit(selectedInfo1, (self.rightinfo_rect.left+5, self.rightinfo_rect.top+35))screen.blit(selectedInfo2, (self.rightinfo_rect.left+5, self.rightinfo_rect.top+55))screen.blit(selectedInfo3, (self.rightinfo_rect.left+5, self.rightinfo_rect.top+75))elif button.text == 'T2':T2 = Turret.Turret(1)selectedInfo1 = self.info_font.render('Cost: '+str(T2.price), True, white)selectedInfo2 = self.info_font.render('Damage: '+str(T2.arrow.attack_power), True, white)selectedInfo3 = self.info_font.render('Affordable: '+str(self.money>=T2.price), True, white)screen.blit(selectedInfo1, (self.rightinfo_rect.left+5, self.rightinfo_rect.top+35))screen.blit(selectedInfo2, (self.rightinfo_rect.left+5, self.rightinfo_rect.top+55))screen.blit(selectedInfo3, (self.rightinfo_rect.left+5, self.rightinfo_rect.top+75))elif button.text == 'T3':T3 = Turret.Turret(2)selectedInfo1 = self.info_font.render('Cost: '+str(T3.price), True, white)selectedInfo2 = self.info_font.render('Damage: '+str(T3.arrow.attack_power), True, white)selectedInfo3 = self.info_font.render('Affordable: '+str(self.money>=T3.price), True, white)screen.blit(selectedInfo1, (self.rightinfo_rect.left+5, self.rightinfo_rect.top+35))screen.blit(selectedInfo2, (self.rightinfo_rect.left+5, self.rightinfo_rect.top+55))screen.blit(selectedInfo3, (self.rightinfo_rect.left+5, self.rightinfo_rect.top+75))elif button.text == 'XXX':selectedInfo = self.info_font.render('Sell a turret', True, white)screen.blit(selectedInfo, (self.rightinfo_rect.left+5, self.rightinfo_rect.top+35))elif button.text == 'Pause':selectedInfo = self.info_font.render('Pause game', True, white)screen.blit(selectedInfo, (self.rightinfo_rect.left+5, self.rightinfo_rect.top+35))elif button.text == 'Quit':selectedInfo = self.info_font.render('Quit game', True, white)screen.blit(selectedInfo, (self.rightinfo_rect.left+5, self.rightinfo_rect.top+35))'''出售炮塔(半价)'''def sellTurret(self, position):coord = self.pos2coord(position)for turret in self.builtTurretGroup:if coord == turret.coord:self.builtTurretGroup.remove(turret)self.money += int(turret.price * 0.5)del turretbreak'''建造炮塔'''def buildTurret(self, position):turret = self.mouseCarried[1]coord = self.pos2coord(position)position = self.coord2pos(coord)turret.position = positionturret.coord = coordturret.rect.left, turret.rect.top = positionif self.money - turret.price >= 0:if self.currentMap.get(turret.coord) in self.placeable.keys():self.money -= turret.priceself.builtTurretGroup.add(turret)if self.mouseCarried[1].turret_type == 0:self.mouseCarried = []self.takeT1()elif self.mouseCarried[1].turret_type == 1:self.mouseCarried = []self.takeT2()elif self.mouseCarried[1].turret_type == 2:self.mouseCarried = []self.takeT3()'''拿炮塔1'''def takeT1(self):T1 = Turret.Turret(0)if self.money >= T1.price:self.mouseCarried = ['turret', T1]'''拿炮塔2'''def takeT2(self):T2 = Turret.Turret(1)if self.money >= T2.price:self.mouseCarried = ['turret', T2]'''拿炮塔3'''def takeT3(self):T3 = Turret.Turret(2)if self.money >= T3.price:self.mouseCarried = ['turret', T3]'''出售炮塔'''def takeXXX(self):XXX = pygame.image.load('./resource/imgs/game/x.png')self.mouseCarried = ['XXX', XXX]'''找下一个路径单元'''def find_next_path(self, enemy):x, y = enemy.coord# 优先级: 下右左上neighbours = [(x, y+1), (x+1, y), (x-1, y), (x, y-1)]for neighbour in neighbours:if (neighbour in self.path_list) and (neighbour not in enemy.reached_path):return neighbourreturn None'''将真实坐标转为地图坐标, 20个单位长度的真实坐标=地图坐标'''def pos2coord(self, position):return (position[0]//self.elementSize, position[1]//self.elementSize)'''将地图坐标转为真实坐标, 20个单位长度的真实坐标=地图坐标'''def coord2pos(self, coord):return (coord[0]*self.elementSize, coord[1]*self.elementSize)'''导入地图'''def loadMap(self, screen, map_path):map_file = open(map_path, 'r')idx_j = -1for line in map_file.readlines():line = line.strip()if not line:continueidx_j += 1idx_i = -1for col in line:try:element_type = int(col)element_img = self.map_elements.get(element_type)element_rect = element_img.get_rect()idx_i += 1element_rect.left, element_rect.top = self.elementSize * idx_i, self.elementSize * idx_jself.map_surface.blit(element_img, element_rect)self.currentMap[idx_i, idx_j] = element_type# 把道路记下来if element_type == 1:self.path_list.append((idx_i, idx_j))except:continue# 放洞穴和大本营self.map_surface.blit(self.cave, (0, 0))self.map_surface.blit(self.nexus, (740, 400))# 大本营的血条nexus_width = self.nexus.get_rect().widthgreenLen = max(0, self.health / self.max_health) * nexus_widthif greenLen > 0:pygame.draw.line(self.map_surface, green, (740, 400), (740+greenLen, 400), 3)if greenLen