当前位置:网站首页>[pyGame] this classic bomber super game is online. Do you love it? (source code attached)

[pyGame] this classic bomber super game is online. Do you love it? (source code attached)

2022-06-10 23:59:00 Programmer pear

Preface

author :“ Programmer pear ”

** The article brief introduction **: This article is mainly about pygame Realize the little game of bomber !

** article Source code Free access : In order to thank everyone who pays attention to me, the project source code of each article is none

Compensation sharing drop

Click here for the blue line font , If you need any source code, remember to say the title and name ! I can also !

Welcome friends give the thumbs-up 、 Collection 、 Leaving a message.

Text

In this impetuous age : Every time Xiaobian lands in the glory of the king , And every landing stimulates the battlefield Z!

Look at the chat interface inside , All kinds of substitute 、 All kinds of search cp. Xiaobian thinks , We have lost the original intention of playing games .

Next , Xiaobian will lead you back to your childhood , Let's enjoy our original play 4399 Innocence and innocence !

Today I'll take you to recall your childhood and make a classic Bomber game !​

1) material

The rules of the game are still clear , I won't introduce more. Those who don't know how to play can baidu !

First, prepare the corresponding materials :【 Some of them are as follows 】

​ Bomber main program :

The starting interface is as follows :

​ Define map class :

class mapParser():
	def __init__(self, mapfilepath, bg_paths, wall_paths, blocksize, **kwargs):
		self.instances_list = self.__parse(mapfilepath)
		self.bg_paths = bg_paths
		self.wall_paths = wall_paths
		self.blocksize = blocksize
		self.height = len(self.instances_list)
		self.width = len(self.instances_list[0])
		self.screen_size = (blocksize * self.width, blocksize * self.height)
	''' Draw the map on the screen '''
	def draw(self, screen):
		for j in range(self.height):
			for i in range(self.width):
				instance = self.instances_list[j][i]
				if instance == 'w':
					elem = Wall(self.wall_paths[0], [i, j], self.blocksize)
				elif instance == 'x':
					elem = Wall(self.wall_paths[1], [i, j], self.blocksize)
				elif instance == 'z':
					elem = Wall(self.wall_paths[2], [i, j], self.blocksize)
				elif instance == '0':
					elem = Background(self.bg_paths[0], [i, j], self.blocksize)
				elif instance == '1':
					elem = Background(self.bg_paths[1], [i, j], self.blocksize)
				elif instance == '2':
					elem = Background(self.bg_paths[2], [i, j], self.blocksize)
				else:
					raise ValueError('instance parse error in mapParser.draw...')
				elem.draw(screen)
	''' Randomly obtain an open space '''
	def randomGetSpace(self, used_spaces=None):
		while True:
			i = random.randint(0, self.width-1)
			j = random.randint(0, self.height-1)
			coordinate = [i, j]
			if used_spaces and coordinate in used_spaces:
				continue
			instance = self.instances_list[j][i]
			if instance in ['0', '1', '2']:
				break
		return coordinate
	''' Get the element type according to the coordinates '''
	def getElemByCoordinate(self, coordinate):
		return self.instances_list[coordinate[1]][coordinate[0]]
	''' analysis .map file '''
	def __parse(self, mapfilepath):
		instances_list = []
		with open(mapfilepath) as f:
			for line in f.readlines():
				instances_line_list = []
				for c in line:
					if c in ['w', 'x', 'z', '0', '1', '2']:
						instances_line_list.append(c)
				instances_list.append(instances_line_list)
		return instances_list

Define some necessary sprite classes : role , Fruit and so on .

''' Wall class '''
class Wall(pygame.sprite.Sprite):
	def __init__(self, imagepath, coordinate, blocksize, **kwargs):
		pygame.sprite.Sprite.__init__(self)
		self.image = pygame.image.load(imagepath)
		self.image = pygame.transform.scale(self.image, (blocksize, blocksize))
		self.rect = self.image.get_rect()
		self.rect.left, self.rect.top = coordinate[0] * blocksize, coordinate[1] * blocksize
		self.coordinate = coordinate
		self.blocksize = blocksize
	''' Draw it on the screen '''
	def draw(self, screen):
		screen.blit(self.image, self.rect)
		return True


''' Background class '''
class Background(pygame.sprite.Sprite):
	def __init__(self, imagepath, coordinate, blocksize, **kwargs):
		pygame.sprite.Sprite.__init__(self)
		self.image = pygame.image.load(imagepath)
		self.image = pygame.transform.scale(self.image, (blocksize, blocksize))
		self.rect = self.image.get_rect()
		self.rect.left, self.rect.top = coordinate[0] * blocksize, coordinate[1] * blocksize
		self.coordinate = coordinate
		self.blocksize = blocksize
	''' Draw it on the screen '''
	def draw(self, screen):
		screen.blit(self.image, self.rect)
		return True


''' Fruits '''
class Fruit(pygame.sprite.Sprite):
	def __init__(self, imagepath, coordinate, blocksize, **kwargs):
		pygame.sprite.Sprite.__init__(self)
		self.kind = imagepath.split('/')[-1].split('.')[0]
		if self.kind == 'banana':
			self.value = 5
		elif self.kind == 'cherry':
			self.value = 10
		else:
			raise ValueError('Unknow fruit %s...' % self.kind)
		self.image = pygame.image.load(imagepath)
		self.image = pygame.transform.scale(self.image, (blocksize, blocksize))
		self.rect = self.image.get_rect()
		self.rect.left, self.rect.top = coordinate[0] * blocksize, coordinate[1] * blocksize
		self.coordinate = coordinate
		self.blocksize = blocksize
	''' Draw it on the screen '''
	def draw(self, screen):
		screen.blit(self.image, self.rect)
		return True


''' Bomb class '''
class Bomb(pygame.sprite.Sprite):
	def __init__(self, imagepath, coordinate, blocksize, digitalcolor, explode_imagepath, **kwargs):
		pygame.sprite.Sprite.__init__(self)
		self.image = pygame.image.load(imagepath)
		self.image = pygame.transform.scale(self.image, (blocksize, blocksize))
		self.explode_imagepath = explode_imagepath
		self.rect = self.image.get_rect()
		#  Pixel position 
		self.rect.left, self.rect.top = coordinate[0] * blocksize, coordinate[1] * blocksize
		#  coordinate ( The element block is in unit length )
		self.coordinate = coordinate
		self.blocksize = blocksize
		#  The countdown to the explosion 
		self.explode_millisecond = 6000 * 1 - 1
		self.explode_second = int(self.explode_millisecond / 1000)
		self.start_explode = False
		#  Explosion duration 
		self.exploding_count = 1000 * 1
		#  Bomb damage ability 
		self.harm_value = 1
		#  Whether the bomb still exists 
		self.is_being = True
		self.font = pygame.font.SysFont('Consolas', 20)
		self.digitalcolor = digitalcolor
	''' Draw it on the screen '''
	def draw(self, screen, dt, map_parser):
		if not self.start_explode:
			#  The countdown to the explosion 
			self.explode_millisecond -= dt
			self.explode_second = int(self.explode_millisecond / 1000)
			if self.explode_millisecond < 0:
				self.start_explode = True
			screen.blit(self.image, self.rect)
			text = self.font.render(str(self.explode_second), True, self.digitalcolor)
			rect = text.get_rect(center=(self.rect.centerx-5, self.rect.centery+5))
			screen.blit(text, rect)
			return False
		else:
			#  The explosion continues to count down 
			self.exploding_count -= dt
			if self.exploding_count > 0:
				return self.__explode(screen, map_parser)
			else:
				self.is_being = False
				return False
	''' Explosive effect '''
	def __explode(self, screen, map_parser):
		explode_area = self.__calcExplodeArea(map_parser.instances_list)
		for each in explode_area:
			image = pygame.image.load(self.explode_imagepath)
			image = pygame.transform.scale(image, (self.blocksize, self.blocksize))
			rect = image.get_rect()
			rect.left, rect.top = each[0] * self.blocksize, each[1] * self.blocksize
			screen.blit(image, rect)
		return explode_area
	''' Calculate the explosion area '''
	def __calcExplodeArea(self, instances_list):
		explode_area = []
		#  The area calculation rule is that the wall can prevent the explosion from spreading ,  And the explosion range is only within the scope of the game map 
		for ymin in range(self.coordinate[1], self.coordinate[1]-5, -1):
			if ymin < 0 or instances_list[ymin][self.coordinate[0]] in ['w', 'x', 'z']:
				break
			explode_area.append([self.coordinate[0], ymin])
		for ymax in range(self.coordinate[1]+1, self.coordinate[1]+5):
			if ymax >= len(instances_list) or instances_list[ymax][self.coordinate[0]] in ['w', 'x', 'z']:
				break
			explode_area.append([self.coordinate[0], ymax])
		for xmin in range(self.coordinate[0], self.coordinate[0]-5, -1):
			if xmin < 0 or instances_list[self.coordinate[1]][xmin] in ['w', 'x', 'z']:
				break
			explode_area.append([xmin, self.coordinate[1]])
		for xmax in range(self.coordinate[0]+1, self.coordinate[0]+5):
			if xmax >= len(instances_list[0]) or instances_list[self.coordinate[1]][xmax] in ['w', 'x', 'z']:
				break
			explode_area.append([xmax, self.coordinate[1]])
		return explode_area


''' Character class '''
class Hero(pygame.sprite.Sprite):
	def __init__(self, imagepaths, coordinate, blocksize, map_parser, **kwargs):
		pygame.sprite.Sprite.__init__(self)
		self.imagepaths = imagepaths
		self.image = pygame.image.load(imagepaths[-1])
		self.image = pygame.transform.scale(self.image, (blocksize, blocksize))
		self.rect = self.image.get_rect()
		self.rect.left, self.rect.top = coordinate[0] * blocksize, coordinate[1] * blocksize
		self.coordinate = coordinate
		self.blocksize = blocksize
		self.map_parser = map_parser
		self.hero_name = kwargs.get('hero_name')
		#  Health value 
		self.health_value = 50
		#  Bomb cooldown 
		self.bomb_cooling_time = 5000
		self.bomb_cooling_count = 0
		#  Random movement cooldown ( only AI For computers )
		self.randommove_cooling_time = 100
		self.randommove_cooling_count = 0
	''' Character movement '''
	def move(self, direction):
		self.__updateImage(direction)
		if direction == 'left':
			if self.coordinate[0]-1 < 0 or self.map_parser.getElemByCoordinate([self.coordinate[0]-1, self.coordinate[1]]) in ['w', 'x', 'z']:
				return False
			self.coordinate[0] = self.coordinate[0] - 1
		elif direction == 'right':
			if self.coordinate[0]+1 >= self.map_parser.width or self.map_parser.getElemByCoordinate([self.coordinate[0]+1, self.coordinate[1]]) in ['w', 'x', 'z']:
				return False
			self.coordinate[0] = self.coordinate[0] + 1
		elif direction == 'up':
			if self.coordinate[1]-1 < 0 or self.map_parser.getElemByCoordinate([self.coordinate[0], self.coordinate[1]-1]) in ['w', 'x', 'z']:
				return False
			self.coordinate[1] = self.coordinate[1] - 1
		elif direction == 'down':
			if self.coordinate[1]+1 >= self.map_parser.height or self.map_parser.getElemByCoordinate([self.coordinate[0], self.coordinate[1]+1]) in ['w', 'x', 'z']:
				return False
			self.coordinate[1] = self.coordinate[1] + 1
		else:
			raise ValueError('Unknow direction %s...' % direction)
		self.rect.left, self.rect.top = self.coordinate[0] * self.blocksize, self.coordinate[1] * self.blocksize
		return True
	''' Random action (AI For computers )'''
	def randomAction(self, dt):
		#  Cooling down countdown 
		if self.randommove_cooling_count > 0:
			self.randommove_cooling_count -= dt
		action = random.choice(['left', 'left', 'right', 'right', 'up', 'up', 'down', 'down', 'dropbomb'])
		flag = False
		if action in ['left', 'right', 'up', 'down']:
			if self.randommove_cooling_count <= 0:
				flag = True
				self.move(action)
				self.randommove_cooling_count = self.randommove_cooling_time
		elif action in ['dropbomb']:
			if self.bomb_cooling_count <= 0:
				flag = True
				self.bomb_cooling_count = self.bomb_cooling_time
		return action, flag
	''' Generate a bomb '''
	def generateBomb(self, imagepath, digitalcolor, explode_imagepath):
		return Bomb(imagepath=imagepath, coordinate=copy.deepcopy(self.coordinate), blocksize=self.blocksize, digitalcolor=digitalcolor, explode_imagepath=explode_imagepath)
	''' Draw it on the screen '''
	def draw(self, screen, dt):
		#  Cooling down countdown 
		if self.bomb_cooling_count > 0:
			self.bomb_cooling_count -= dt
		screen.blit(self.image, self.rect)
		return True
	''' Eat fruit '''
	def eatFruit(self, fruit_sprite_group):
		eaten_fruit = pygame.sprite.spritecollide(self, fruit_sprite_group, True, None)
		for fruit in eaten_fruit:
			self.health_value += fruit.value
	''' Update character orientation '''
	def __updateImage(self, direction):
		directions = ['left', 'right', 'up', 'down']
		idx = directions.index(direction)
		self.image = pygame.image.load(self.imagepaths[idx])
		self.image = pygame.transform.scale(self.image, (self.blocksize, self.blocksize))

The effect is as follows :

This exquisite picture is OK ~ Ha ha ha ha Praise me. Praise me ~

summary

An LA ! This is the article , Your support is my biggest motivation , Remember Sanlian ~

Follow Xiaobian for more wonderful content ! Remember to click on the portal

Remember Sanlian ! If you need packaged source code + Free sharing of materials ! Portal

原网站

版权声明
本文为[Programmer pear]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/161/202206102242246681.html