Complete a simple tank battle game based on the idea of object-oriented programming. The main purpose is to train the object-oriented programming ideas
The same pygame module needs to be installed when using python for game writing
installation method:
pycharm installation method: File — setting
The main objects in the game are:
Tank parent class: BaseTank
Our tank: HeroTank
Enemy tank: EnemyTank
Bullet: Bullet
Explosion class: Explode
Wall category: Wall
Main process: MainGame
**Define a sprite class: **
# Define a sprite class
classBaseItem(Sprite):
def __init__(self, color, width, height):
# Call the parent class(Sprite) constructor
pygame.sprite.Sprite.__init__(self)
**Tank parent class: **
# Tank parent
classBaseTank(BaseItem):
# Define class attributes, all tank objects have the same height and width
width =60
height =60
def __init__(self, left, top):
self.direction ='U' #The direction of the tank is up by default
# Dictionary to store pictures
self.images ={'U': pygame.image.load('tank_img/p1tankU.gif'),'D': pygame.image.load('tank_img/p1tankD.gif'),'L': pygame.image.load('tank_img/p1tankL.gif'),'R': pygame.image.load('tank_img/p1tankR.gif')}
self.image = self.images[self.direction] #The picture of the tank is determined by the direction
self.speed =5 #The speed of the tank
self.rect = self.image.get_rect()
# Set the placement location
self.rect.left = left
self.rect.top = top
self.stop = True #Does the tank stop
self.live = True #Decide whether the tank is destroyed
# Keep the original position
self.oldLeft = self.rect.left
self.oldTop = self.rect.top
# Shooting method
def shot(self):returnBullet(self)
# The movement of the tank
def move(self):
# Keep the original state
self.oldLeft = self.rect.left
self.oldTop = self.rect.top
# Determine the direction of the tank
if self.direction =='U':if self.rect.top 0:
self.rect.top -= self.speed
elif self.direction =='D':if self.rect.top + self.rect.height < WINDOW_HEIGHT:
self.rect.top += self.speed
elif self.direction =='L':if self.rect.left 0:
self.rect.left -= self.speed
elif self.direction =='R':if self.rect.left+self.rect.height < WINDOW_WIDTH:
self.rect.left += self.speed
# Load tank
def displayTank(self):
self.image = self.images[self.direction]
MainGame.window.blit(self.image, self.rect)
# Hit the wall
def hitWall(self):for wall in MainGame.wallList:if pygame.sprite.collide_rect(wall, self):
self.stay()
# Processing position unchanged
def stay(self):
self.rect.left = self.oldLeft
self.rect.top = self.oldTop
Our tank class ():
# Our tank
classHeroTank(BaseTank):
def __init__(self, left, top):super().__init__(left, top)
# Our tank collides with an enemy tank
def myTank_hit_enemyTank(self):for enemyTank in MainGame.EnemyTankList:if pygame.sprite.collide_rect(enemyTank, self):
self.stay()
Enemy tank type ():
# Enemy tank
classEnemyTank(BaseTank):
def __init__(self, left, top, speed):super(EnemyTank, self).__init__(left, top)
self.images ={'U': pygame.image.load('tank_img/enemy1U.gif'),'D': pygame.image.load('tank_img/enemy1D.gif'),'L': pygame.image.load('tank_img/enemy1L.gif'),'R': pygame.image.load('tank_img/enemy1R.gif')}
self.direction = self.RandomDirection()
self.image = self.images[self.direction]
self.rect = self.image.get_rect()
self.rect.left = left
self.rect.top = top
self.speed = speed
self.step =60
self.enemy_flag = False
# Random direction of tank birth
def RandomDirection(self):
num = random.randint(1,4)if num ==1:return'U'
elif num ==2:return'D'
elif num ==3:return'L'else:return'R'
# The tank moves randomly
def randomMove(self):if self.step <0:
self.direction = self.RandomDirection()
self.step =60else:
self.move()
self.step -=1
# Tank shooting
def shot(self):
num = random.randint(1,100)if num <4:returnBullet(self)
# Enemy tank collided with our tank
def enemyTank_hit_MyTank(self):for enemy in MainGame.EnemyTankList:if MainGame.my_tank and MainGame.my_tank.live:if pygame.sprite.collide_rect(MainGame.my_tank, enemy):
self.stay()
**Bullet (): **
# Bullet
classBullet(BaseItem):
def __init__(self, tank):
self.image = pygame.image.load('tank_img/tankmissile.gif')
self.direction = tank.direction
self.rect = self.image.get_rect()
# According to the tank direction, generate the bullet position
if self.direction =='U':
self.rect.left = tank.rect.left + tank.rect.width /2- self.rect.width /2
self.rect.top = tank.rect.top - self.rect.height
elif self.direction =='D':
self.rect.left = tank.rect.left + tank.rect.width /2- self.rect.width /2
self.rect.top = tank.rect.top + tank.rect.height
elif self.direction =='L':
self.rect.left = tank.rect.left - self.rect.width /2- self.rect.width /2
self.rect.top = tank.rect.top + tank.rect.height /2- self.rect.width /2
elif self.direction =='R':
self.rect.left = tank.rect.left + tank.rect.width
self.rect.top = tank.rect.top + tank.rect.height /2- self.rect.width /2
# Bullet speed
self.speed =6
# Bullet status
self.live = True
# Load bullet
def displayBullet(self):
MainGame.window.blit(self.image, self.rect)
# Bullet movement
def move(self):if self.direction =='U':if self.rect.top 0:
self.rect.top -= self.speed
else:
self.live = False
elif self.direction =='R':if self.rect.left + self.rect.width < WINDOW_WIDTH:
self.rect.left += self.speed
else:
self.live = False
elif self.direction =='D':if self.rect.top + self.rect.height < WINDOW_HEIGHT:
self.rect.top += self.speed
else:
self.live = False
elif self.direction =='L':if self.rect.left 0:
self.rect.left -= self.speed
else:
self.live = False
# Our bullet hit the enemy tank
def myBullet_hit_enemy(self):for enemytank in MainGame.EnemyTankList:if pygame.sprite.collide_rect(enemytank, self):
enemytank.live = False
self.live = False
# Create an exploded object
explode =Explode(enemytank)
MainGame.explodeList.append(explode)
# The enemy tank hits our tank
def enemyBullet_hit_myTank(self):if MainGame.my_tank and MainGame.my_tank.live:if pygame.sprite.collide_rect(MainGame.my_tank, self):
MainGame.my_tank.live = False
self.live = False
# Create an exploded object
explode =Explode(MainGame.my_tank)
MainGame.explodeList.append(explode)
# Shooting wall
def wall_bullet(self):for wall in MainGame.wallList:if pygame.sprite.collide_rect(wall, self):
wall.hg -=1
self.live = False
if wall.hg <=0:
wall.live = False
Wall type ():
# Wall class
classWall:
def __init__(self, left, top):
self.image = pygame.image.load('tank_img/steels.gif')
self.rect = self.image.get_rect()
self.rect.left = left
self.rect.top = top
self.live = True
self.hg =100000000000000
# Load wall
def displayWall(self):if self.live:
MainGame.window.blit(self.image, self.rect)
**Explosion class: **
# Explosive
classExplode:
def __init__(self, tank):
# The location of the explosion is determined by the tank
self.rect = tank.rect
self.images =[
pygame.image.load('tank_img/blast0.gif'),
pygame.image.load('tank_img/blast1.gif'),
pygame.image.load('tank_img/blast2.gif'),
pygame.image.load('tank_img/blast3.gif'),
pygame.image.load('tank_img/blast4.gif'),
pygame.image.load('tank_img/blast5.gif'),
pygame.image.load('tank_img/blast6.gif'),
pygame.image.load('tank_img/blast7.gif')]
self.step =0
self.image = self.images[self.step]
self.live = True
# Load explosion class
def displayExplode(self):if self.step <len(self.images):
self.image = self.images[self.step]
self.step +=1
MainGame.window.blit(self.image, self.rect)else:
self.live = False
self.step =0
The main process ():
# Games
classMainGame:
# Class attribute
window = None
my_tank = None
# Enemy tank initialization
EnemyTankList =[]
EnemyTankCount =5
# Store our bullet list
myBulleList =[]
# Store a list of enemy bullets
EnemyBulletList =[]
# Create a list of exploded objects
explodeList =[]
# Create wall list
wallList =[]
# How to start the game
def start_game(self):
# Initialize the display module
pygame.display.init()
# Call the method of creating a window
self.creat_window()
# Set the title of the game window
pygame.display.set_caption('Tank battle')
# Initialize our tank
self.createMyTank()
# Initialize enemy tanks
self.creatEnemyTank()
# Initialize the wall
self.creatWall()
# The program continues
while True:
# Change background color
MainGame.window.fill(COLOR_GREEN)
# Background music
# Get events
self.getEvent()
# Call our tank for display
if MainGame.my_tank and MainGame.my_tank.live:
MainGame.my_tank.displayTank()if not MainGame.my_tank.stop:
MainGame.my_tank.move()
MainGame.my_tank.hitWall()
MainGame.my_tank.myTank_hit_enemyTank()else:
del MainGame.my_tank
MainGame.my_tank = None
# Load our bullet
self.biltMyBullet()
# Show enemy tanks
self.biltEnemyTank()
# Show enemy bullets
self.biltEnemyBullet()
# Display wall
self.blitWall()
# Show explosion effect
self.blitExplode()
self.put_more_enemytank()
# The window keeps refreshing
pygame.display.update()
time.sleep(0.02)
# Add enemy tanks repeatedly
def put_more_enemytank(self):whilelen(MainGame.EnemyTankList)<5:
self.more()
# Method of creating game window:
def creat_window(self):if not MainGame.window:
# Create window
MainGame.window = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))return MainGame.window
# Create our tank
def createMyTank(self):
MainGame.my_tank =HeroTank((WINDOW_WIDTH - HeroTank.width)/2, WINDOW_HEIGHT - HeroTank.height)
music =Music('tank_img/start.wav')
music.play()
# Create walls
def creatWall(self):for i inrange(60, WINDOW_WIDTH,60):
top = WINDOW_WIDTH // 3
left = i
wall =Wall(left, top)
MainGame.wallList.append(wall)
# Display wall
def blitWall(self):for b in MainGame.wallList:if b.live:
b.displayWall()else:
MainGame.wallList.remove(b)
# Load our bullet
def biltMyBullet(self):for bullet in MainGame.myBulleList:if bullet.live:
bullet.displayBullet()
bullet.move()
bullet.myBullet_hit_enemy()
bullet.wall_bullet()else:
MainGame.myBulleList.remove(bullet)
# Subsequent tank addition
def more(self):
top =0for i inrange(5-len(MainGame.EnemyTankList)):
left = random.randint(0,750)
speed = random.randint(1,4)
enemy =EnemyTank(left, top, speed)
MainGame.EnemyTankList.append(enemy)
# Create enemy tanks
def creatEnemyTank(self):
top =0for i inrange(MainGame.EnemyTankCount):
left = random.randint(0,750)
speed = random.randint(1,4)
enemy =EnemyTank(left, top, speed)
MainGame.EnemyTankList.append(enemy)
# Loop through to show enemy tanks
def biltEnemyTank(self):for enemytank in MainGame.EnemyTankList:if enemytank.live:
enemytank.displayTank()
EnemyBullet = enemytank.shot()
enemytank.randomMove()
enemytank.hitWall()
enemytank.enemyTank_hit_MyTank()
# Store enemy bullets
if EnemyBullet:
MainGame.EnemyBulletList.append(EnemyBullet)else:
MainGame.EnemyTankList.remove(enemytank)
MainGame.EnemyTankCount -=1
# Load enemy bullets
def biltEnemyBullet(self):for bullet in MainGame.EnemyBulletList:if bullet.live:
bullet.displayBullet()
bullet.move()
bullet.enemyBullet_hit_myTank()
bullet.wall_bullet()else:
MainGame.EnemyBulletList.remove(bullet)
# Loading explosion effect
def blitExplode(self):for explode in MainGame.explodeList:if explode.live:
explode.displayExplode()else:
MainGame.explodeList.remove(explode)
# Get all events in the game
def getEvent(self):
# Get a list of events in the game
even_list = pygame.event.get()for e in even_list:
# Click the cross in the window to end the game
if e.type == pygame.QUIT:
sys.exit()
# Control the movement of the tank with the up, down, left and right keys
if e.type == pygame.KEYDOWN:if MainGame.my_tank and MainGame.my_tank.live:if e.key == pygame.K_DOWN or e.key == pygame.K_s:
MainGame.my_tank.direction ='D'
MainGame.my_tank.stop = False
print("Press the down button to move down")
elif e.key == pygame.K_UP or e.key == pygame.K_w:
MainGame.my_tank.direction ='U'
MainGame.my_tank.stop = False
print("Press the up key to move up")
elif e.key == pygame.K_LEFT or e.key == pygame.K_a:
MainGame.my_tank.direction ='L'
MainGame.my_tank.stop = False
print("Press the left key to move left")
elif e.key == pygame.K_RIGHT or e.key == pygame.K_d:
MainGame.my_tank.direction ='R'
MainGame.my_tank.stop = False
print("Press the right key to move to the right")
elif e.key == pygame.K_SPACE:print('Fire a bullet')
# Create our bullet
iflen(MainGame.myBulleList)<10:
mybullet =Bullet(MainGame.my_tank)
MainGame.myBulleList.append(mybullet)
# Shooting sound
Shot_music =Music('tank_img/fire.wav')
Shot_music.play()
elif e.type == pygame.KEYUP:if e.key == pygame.K_UP or e.key == pygame.K_DOWN or e.key == pygame.K_LEFT or e.key == pygame.K_RIGHT \
or e.key == pygame.K_w or e.key == pygame.K_s or e.key == pygame.K_a or e.key == pygame.K_d:if MainGame.my_tank and MainGame.my_tank.live:
MainGame.my_tank.stop = True
Program running results:
Source download: python realizes simple tank battle
For more wonderful articles about python games, please click to view the following topics:
python tetris game collection
Python classic games summary
Python WeChat Jump Jump Game Collection
The above is the whole content of this article, I hope it will be helpful to everyone's study.
Recommended Posts