import pygame
import time
import random
from pygame.sprite import Sprite
screen_width=600
screen_lenth=400
main_color=pygame.Color(127,255,0)
text_color=pygame.Color(255,0,0)
class BaseItem(Sprite):
def __init__(self, color, width, height):
pygame.sprite.Sprite.__init__(self)
class MainGame():
window = None
p1_role = None
p2_role = None
targetlist = []
targetcount = 10
p1_bulletlist = []
p2_bulletlist = []
targetbullet = []
explodelist = []
targetbulletlist=[]
walllist = []
s_pic = 'images/开始.png'
e_pic = 'images/结束.png'
def __init__(self):
pass
def startsurface(self):
button_1=Button(300,150,MainGame.s_pic)
button_2=Button(300,250,MainGame.e_pic)
var = pygame.display.init
MainGame.window = pygame.display.set_mode([screen_width,screen_lenth])
pygame.display.set_caption('双人射击')
while True:
MainGame.window.fill(main_color)
button_1.displayButton()
button_2.displayButton()
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
if button_1.isOver() == True:
self.startGame()
if button_2.isOver() == True:
self.endGame()
if event.type == pygame.QUIT:
self.endGame()
pygame.display.update()
def startGame(self):
var = pygame.display.init
MainGame.window = pygame.display.set_mode([screen_width, screen_lenth])
pygame.display.set_caption('双人射击')
self.createp1()
self.createp2()
self.createtarget()
self.createWall()
while True:
time.sleep(0.02) # 循环变慢
MainGame.window.fill(main_color) # 设置主窗口的填充色
self.getEvent() # 获取事件
MainGame.window.blit(self.getTextSurface("剩余目标数量:%d" % len(MainGame.targetlist)),
(10, 10)) # 绘制文字
if MainGame.p1_role and MainGame.p1_role.live:
MainGame.p1_role.displayRole() # 调用我方显示方法,只需要初始化一次,一直显示即可
else:
del MainGame.p1_role # 删除我方
MainGame.p1_role = None
if MainGame.p1_role and MainGame.p1_role.live:
if not MainGame.p1_role.stop:
MainGame.p1_role.move() # 我方坦克的移动,按下方向键一直移动
MainGame.p1_role.hitWall() # 检测我方是否与墙壁发生碰撞
MainGame.p1_role.p1_hit_target()
if MainGame.p2_role and MainGame.p2_role.live:
MainGame.p2_role.displayRole() # 调用我方坦克显示方法,只需要初始化一次,一直显示即可
else:
del MainGame.p2_role # 删除我方坦克
MainGame.p2_role = None
if MainGame.p2_role and MainGame.p2_role.live:
if not MainGame.p2_role.stop:
MainGame.p2_role.move() # 我方坦克的移动,按下方向键一直移动
MainGame.p2_role.hitWall() # 检测我方是否与墙壁发生碰撞
MainGame.p2_role.p2_hit_target()
#调用敌方坦克显示方法
self.p1_bullet() # 调用我方坦克子弹显示方法
self.p2_bullet()
self.blitTarget()
self.blittargetbullet() # 调用敌方坦克子弹显示方法
self.blitExplode() # 调用爆炸效果的显示方法
self.blitWall() # 调用墙壁的显示方法
pygame.display.update() # 主窗口的更新,用于一直存在
def endGame(self):
print('game over')
exit()
def getTextSurface(self, text):
pygame.font.init() # 初始化字体模块
font = pygame.font.SysFont("SimHei", 12) # 获取系统字体对象并设置字体和大小
textSurface = font.render(text, True, text_color) # 绘制文字信息
return textSurface
def getEvent(self):
eventList = pygame.event.get() # 获取所有事件
for event in eventList: # 遍历事件
if event.type == pygame.QUIT: # 关闭键
self.endGame()
if event.type == pygame.KEYDOWN: # 键盘按下
if not MainGame.p1_role:
if event.key == pygame.K_r:
self.createp1()
if MainGame.p1_role and MainGame.p1_role.live:
if event.key == pygame.K_LEFT:
MainGame.p1_role.direction = 'L' # 切换方向
MainGame.p1_role.stop = False
print("按下左键,向左移动")
elif event.key == pygame.K_RIGHT:
MainGame.p1_role.direction = 'R' # 切换方向
MainGame.p1_role.stop = False
print("按下右键,向右移动")
elif event.key == pygame.K_UP:
MainGame.p1_role.direction = 'U' # 切换方向
MainGame.p1_role.stop = False
print("按下上键,向上移动")
elif event.key == pygame.K_DOWN:
MainGame.p1_role.direction = 'D' # 切换方向
MainGame.p1_role.stop = False
print("按下下键,向下移动")
elif event.key == pygame.K_l:
if len(MainGame.p1_bulletlist) < 3:
p1bullet = Bullet(MainGame.p1_role)
MainGame.p1_bulletlist.append(p1bullet)
print('发射子弹')
if not MainGame.p2_role:
if event.key == pygame.K_e:
self.createp2()
if MainGame.p2_role and MainGame.p2_role.live:
if event.key == pygame.K_a:
MainGame.p2_role.direction = 'L' # 切换方向
MainGame.p2_role.stop = False
print("按下左键,向左移动")
elif event.key == pygame.K_d:
MainGame.p2_role.direction = 'R' # 切换方向
MainGame.p2_role.stop = False
print("按下右键,向右移动")
elif event.key == pygame.K_w:
MainGame.p2_role.direction = 'U' # 切换方向
MainGame.p2_role.stop = False
print("按下上键,向上移动")
elif event.key == pygame.K_s:
MainGame.p2_role.direction = 'D' # 切换方向
MainGame.p2_role.stop = False
print("按下下键,向下移动")
elif event.key == pygame.K_SPACE:
if len(MainGame.p2_bulletlist) < 3:
p2bullet = Bullet(MainGame.p2_role)
MainGame.p2_bulletlist.append(p2bullet)
print('发射子弹')
if event.type == pygame.KEYUP:
# 判断松开的键是上、下、左、右键时候才停止移动
if event.key == pygame.K_UP \
or event.key == pygame.K_DOWN \
or event.key == pygame.K_LEFT \
or event.key == pygame.K_RIGHT:
if MainGame.p1_role and MainGame.p1_role.live:
MainGame.p1_role.stop = True
if event.type == pygame.KEYUP:
# 判断松开的键是上、下、左、右键时候才停止移动
if event.key == pygame.K_w \
or event.key == pygame.K_s \
or event.key == pygame.K_a \
or event.key == pygame.K_d:
if MainGame.p2_role and MainGame.p2_role.live:
MainGame.p2_role.stop = True
def createp1(self):
MainGame.p1_role = P1(350, 300)
def createp2(self):
MainGame.p2_role= P2(350, 300)
def createtarget(self):
top = 100
for i in range(MainGame.targetcount): # 循环生成敌方坦克
left = random.randint(0, 600)
speed = random.randint(1, 4)
tar = Target(top, left, speed)
MainGame.targetlist.append(tar)
def blitTarget(self):
for target in MainGame.targetlist:
if target.live:
target.displayRole()
target.randMove()
target.hitWall()
targetbullet = target.shoot()
if MainGame.p1_role and MainGame.p1_role.live:
target.target_hit_p1()
if targetbullet: # 敌方子弹是否是None,如果不为None则添加到敌方子弹列表中#3.13.2024
MainGame.targetlist.append(targetbullet)
else:
MainGame.targetlist.remove(target)
def p1_bullet(self):
for p1_bullet in MainGame.p1_bulletlist:
if p1_bullet.live:
p1_bullet.displayBullet()
p1_bullet.move()
p1_bullet.myBullet_hit_target()
p1_bullet.bullethitWall()
else:
MainGame.p1_bulletlist.remove(p1_bullet)
def p2_bullet(self):
for p2_bullet in MainGame.p2_bulletlist:
if p2_bullet.live:
p2_bullet.displayBullet()
p2_bullet.move()
p2_bullet.myBullet_hit_target()
p2_bullet.bullethitWall()
else:
MainGame.p2_bulletlist.remove(p2_bullet)
def blittargetbullet(self):
for targetbullet in MainGame.targetbulletlist:
if targetbullet.live:
targetbullet.displayBullet()
targetbullet.move()
targetbullet.target_hit_p1() # 调用子弹与我方碰撞的方法
targetbullet.bullethitWall() # 调用敌方子弹与墙壁碰撞方法
else:
MainGame.targetbulletlist.remove(targetbullet)
def blitExplode(self):
for explode in MainGame.explodelist:
if explode.live:
explode.displayExplode()
else:
MainGame.explodelist.remove(explode)
def createWall(self):
for i in range(6):
wall = Wall(i * 130, 220)
MainGame.walllist.append(wall)
def blitWall(self):
for wall in MainGame.walllist:
if wall.live:
wall.displayWall()
else:
MainGame.walllist.remove(wall)
class Button():
def __init__(self, left, top, filename): # 初始化该按钮,包括加载图片,初始位置,按钮大小
self.image = pygame.image.load(filename)
self.rect = self.image.get_rect() # 获取图片的区域
self.rect.left = left
self.rect.top = top
def isOver(self): # 判断鼠标是否放在该按钮上
point_x, point_y = pygame.mouse.get_pos()
x = self.rect.left
y = self.rect.top
w, h = self.image.get_size()
in_x = x < point_x < x + w
in_y = y < point_y < y + h
return in_x and in_y
def displayButton(self):
MainGame.window.blit(self.image, self.rect)
class Role_p1(BaseItem):
def __init__(self,top,left):
self.images = {
"U": pygame.image.load("images/p1up.png"),
"D": pygame.image.load("images/p1down.png"),
"L": pygame.image.load("images/p1left.png"),
"R": pygame.image.load("images/p1right.png"),
}
self.direction = "U"
self.image = self.images[self.direction] # 初始化方向
self.rect = self.image.get_rect() # 获取图片的区域
self.rect.left = left
self.rect.top = top
self.speed = 5 # 初始化速度
self.stop = True
self.live = True
self.oldLeft = self.rect.left
self.oldTop = self.rect.top
def move(self):
self.oldLeft = self.rect.left
self.oldTop = self.rect.top
if self.direction == 'L':
if self.rect.left > 0:
self.rect.left -= self.speed
elif self.direction == 'U':
if self.rect.top > 0:
self.rect.top -= self.speed
elif self.direction == 'D':
if self.rect.top + self.rect.height < screen_lenth:
self.rect.top += self.speed
elif self.direction == 'R':
if self.rect.left + self.rect.height < screen_width:
self.rect.left += self.speed
def shoot(self):
return Bullet(self)
def stay(self):
self.rect.left = self.oldLeft
self.rect.top = self.oldTop
def hitWall(self):
for wall in MainGame.walllist:
if pygame.sprite.collide_rect(self, wall):
self.stay()
def displayRole(self):
self.image = self.images[self.direction]
MainGame.window.blit(self.image, self.rect)
class P1(Role_p1):
def __init__(self, top,left):
super(P1, self).__init__(top,left)
def p1_hit_target(self): # 检测是否与目标相撞
for target in MainGame.targetlist:
if pygame.sprite.collide_rect(self, target):
self.stay()
class Role_p2(BaseItem):
def __init__(self,top,left):
self.images = {
"U": pygame.image.load("images/p2up.png"),
"D": pygame.image.load("images/p2down.png"),
"L": pygame.image.load("images/p2left.png"),
"R": pygame.image.load("images/p2right.png"),
}
self.direction = "U"
self.image = self.images[self.direction] # 初始化方向
self.rect = self.image.get_rect() # 获取图片的区域
self.rect.left = left
self.rect.top = top
self.speed = 5 # 初始化速度
self.stop = True
self.live = True
self.oldLeft = self.rect.left
self.oldTop = self.rect.top
def move(self):
self.oldLeft = self.rect.left
self.oldTop = self.rect.top
if self.direction == 'L':
if self.rect.left > 0:
self.rect.left -= self.speed
elif self.direction == 'U':
if self.rect.top > 0:
self.rect.top -= self.speed
elif self.direction == 'D':
if self.rect.top + self.rect.height < screen_lenth:
self.rect.top += self.speed
elif self.direction == 'R':
if self.rect.left + self.rect.height < screen_width:
self.rect.left += self.speed
def shoot(self):
return Bullet(self)
def stay(self):
self.rect.left = self.oldLeft
self.rect.top = self.oldTop
def hitWall(self):
for wall in MainGame.walllist:
if pygame.sprite.collide_rect(self, wall):
self.stay()
def displayRole(self):
self.image = self.images[self.direction]
MainGame.window.blit(self.image, self.rect)
class P2(Role_p2):
def __init__(self, top,left):
super(P2, self).__init__(top,left)
def p2_hit_target(self): # 检测是否与目标相撞
for target in MainGame.targetlist:
if pygame.sprite.collide_rect(self, target):
self.stay()
class Target(Role_p1):
def __init__(self, top,left,speed):
super(Target, self).__init__(top,left)
self.images = {
'U': pygame.image.load('images/pig.png'),
'D': pygame.image.load('images/pig.png'),
'L': pygame.image.load('images/pig.png'),
'R': pygame.image.load('images/pig.png'),
}
self.direction = self.randDirection() # 方向,随机生成目标
self.image = self.images[self.direction] # 根据方向获取图片
self.rect = self.image.get_rect()
self.rect.left = left
self.rect.top = top
self.speed = speed
self.flag = True # 移动开关
self.step = 60 # 移动步数
def target_hit_p1(self): # 检测目标是否与角色相撞
if pygame.sprite.collide_rect(self, MainGame.p1_role):
self.stay()
def target_hit_p2(self): # 检测目标是否与角色相撞
if pygame.sprite.collide_rect(self, MainGame.p2_role):
self.stay()
def randDirection(self): # 随机方向
num = random.randint(1, 4)
if num == 1:
return 'U'
elif num == 2:
return 'D'
elif num == 3:
return "L"
elif num == 4:
return 'R'
def randMove(self): # 随机移动
if self.step <= 0:
self.direction = self.randDirection()
self.step = 60 # 步数复位
else:
self.move()
self.step -= 1
def shoot(self):
num = random.randint(1, 50) # 随机生成50以内的数
if num < 3:
return Bullet(self)
class Bullet(BaseItem):
def __init__(self,role):
self.image = pygame.image.load("images/zidan.png")
self.direction =role.direction # 坦克的方向决定子弹的方向
self.rect = self.image.get_rect()
if self.direction == 'U':
self.rect.left = int(role.rect.left + role.rect.width / 2 - self.rect.width / 2)
self.rect.top = role.rect.top - self.rect.height
elif self.direction == 'D':
self.rect.left = int(role.rect.left + role.rect.width / 2 - self.rect.width / 2)
self.rect.top = role.rect.top + role.rect.height
elif self.direction == 'L':
self.rect.left = int(role.rect.left - self.rect.width / 2 - self.rect.width / 2)
self.rect.top = int(role.rect.top + role.rect.width / 2 - self.rect.width / 2)
elif self.direction == 'R':
self.rect.left = role.rect.left + role.rect.width
self.rect.top = int(role.rect.top + role.rect.width / 2 - self.rect.width / 2)
self.speed = 6
self.live = True
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 < screen_width:
self.rect.left += self.speed
else:
self.live = False
elif self.direction == 'D':
if self.rect.top + self.rect.height < screen_lenth:
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
def bullethitWall(self): # 检测子弹与墙壁碰撞
for wall in MainGame.walllist:
if pygame.sprite.collide_rect(self, wall):
self.live = False
wall.hp -= 1 # 墙壁的生命值减小
if wall.hp <= 0:
wall.live = False
def displayBullet(self):
MainGame.window.blit(self.image, self.rect)
def myBullet_hit_target(self): # 我方子弹与目标发生碰撞
for target in MainGame.targetlist:
if pygame.sprite.collide_rect(target, self):
self.live = False # 修改目标和我方子弹的状态
target.live = False
explode = Explode(target) # 创建爆炸对象
MainGame.explodelist.append(explode)
def target_hit_p1(self): # 敌方子弹与我方的碰撞
if MainGame.p1_role and MainGame.p1_role.live:
if pygame.sprite.collide_rect(MainGame.p1_role, self):
self.live = False
MainGame.p1_role.live = False
explode = Explode(MainGame.p1_role)
MainGame.explodelist.append(explode)
def target_hit_p2(self): # 敌方子弹与我方的碰撞
if MainGame.p2_role and MainGame.p2_role.live:
if pygame.sprite.collide_rect(MainGame.p2_role, self):
self.live = False
MainGame.p2_role.live = False
explode = Explode(MainGame.p2_role)
MainGame.explodelist.append(explode)
class Explode():
def __init__(self,role):
self.rect = role.rect # 爆炸的位置由当前子弹打中的位置决定
self.images = [
pygame.image.load('images/boom.png'),
pygame.image.load('images/boom.png'),
pygame.image.load('images/boom.png'),
pygame.image.load('images/boom.png'),
pygame.image.load('images/boom.png'),
]
self.step = 0
self.image = self.images[self.step]
self.live = True
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 # 复位
class Wall():
def __init__(self, left, top):
self.image = pygame.image.load('images/wall.png')
self.rect = self.image.get_rect()
self.rect.left = left
self.rect.top = top
self.live = True
self.hp = 3 # 设置墙壁生命值
def displayWall(self):
MainGame.window.blit(self.image, self.rect)
if __name__ == "__main__":
MainGame().startsurface()
![img](https://img-mid.csdnimg.cn/release/static/image/mid/ask/9581cfb5dd0842d4ac5f4445301a7ca0.png "#left")
接上个问题进行提问 实在找不出来bug了