会员可以在此提问,百战程序员老师有问必答
对大家有帮助的问答会被标记为“推荐”
看完课程过来浏览一下别人提的问题,会帮你学得更全面
截止目前,同学们一共提了 132462个问题
JAVA 全系列/第三阶段:数据库编程/SQL 语言 34473楼
JAVA 全系列/第一阶段:JAVA 快速入门/飞机大战小项目训练 34474楼
大数据全系列/第一阶段:Linux 操作系统/Linux操作系统概述与安装 34478楼
JAVA 全系列/第三阶段:数据库编程/SQL 语言 34479楼

老师,我按照课程将加载墙壁的代码写完后,为什么运行效果是只加载一个墙壁,并且没有按照left和top的坐标加载。能显示一张,证明显示的方法是对的,加载的方法应该也是对的。

我后来全程跟着视频将代码重敲一遍,还是这个效果。希望老师帮忙看看问题在哪。

"""
新增功能:
    添加墙壁类
    1. 完善墙壁类,初始化方法
    2. 初始化墙壁,并将墙壁存储到列表中,在窗口中加载墙壁
"""

# 导入pygame模块
import pygame
import time
import random
from tkinter import messagebox

SCREEN_WIDTH = 1000
SCREEN_HEIGHT = 800
BG_COLOR = pygame.Color(0, 0, 0)
text_color = pygame.Color(255, 0, 0)


# 定义一个基类
class BaseItem(pygame.sprite.Sprite):
    def __init__(self, color, width, height):
        # Call the parent class (Sprite) constructor
        pygame.sprite.Sprite.__init__(self)


# 主类
class MainGame():

    window = None
    my_tank = None
    # 创建存储敌方坦克的列表
    enemy_tank_list = []
    # 定义敌方坦克的数量
    enemy_tank_count = 5
    # 存储我方子弹的列表
    my_bullet_list = []
    # 存储敌方子弹的列表
    enemy_bullet_list = []
    # 存储爆炸效果的列表
    explode_list = []
    # 创建存储墙壁的列表
    wall_list = []

    def __init__(self):
        pass

    # 开始游戏
    def start_game(self):

        # 加载主窗口
        # 初始化窗口
        pygame.display.init()

        # 设置窗口的大小及显示
        MainGame.window = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT])

        # 设置窗口的标题
        pygame.display.set_caption('坦克大战1.03')

        # 初始化我方坦克
        MainGame.my_tank = Tank(600, 500)
        # 初始化敌方坦克, 并将点坦克添加到列表中
        self.create_enemy_tank()

        # 初始化墙壁
        self.create_wall()

        while True:

            # 使用time模块使循环的速度慢一点,以实现坦克运行的速度慢一些
            time.sleep(0.02)

            # 给窗口设置颜色
            MainGame.window.fill(BG_COLOR)

            # 获取事件
            self.get_event()

            # 绘制文字
            MainGame.window.blit(self.get_text_surface("地方坦克剩余数量:{0}".format(len(MainGame.enemy_tank_list))), (10, 10))

            # 调用我方坦克
            # 判断我方坦克是否存活
            if MainGame.my_tank and MainGame.my_tank.live:
                MainGame.my_tank.display_tank()
            else:
                # 删除我方坦克
                del MainGame.my_tank
                MainGame.my_tank = None
            # 循环遍历敌方坦克列表,展示敌方坦克
            self.blit_enemy_tank()

            # 循环遍历显示我方坦克发射的子弹
            self.blit_my_bullet()
            # 循环遍历显示敌方坦克发射的子弹,展示敌方子弹
            self.blit_enemy_bullet()
            # 循环遍历爆炸列表,展示爆炸效果
            self.blit_explode()
            # 循环遍历墙壁列表,展示墙壁
            self.blit_wall()
            # 调用移动方法
            # 如果坦克的开关是开启,才可以移动
            if MainGame.my_tank and MainGame.my_tank.live:
                if not MainGame.my_tank.stop:
                    MainGame.my_tank.move()

            pygame.display.update()

    # 循环遍历墙壁列表,展示墙壁
    def blit_wall(self):
        for wall in MainGame.wall_list:
            # 调用墙壁显示方法
            wall.display_wall()

    # 初始化墙壁
    def create_wall(self):
        for i in range(6):
            # 初始化墙壁
            wall = Wall(i*130, 400)
            # 将墙壁添加到列表中
            MainGame.wall_list.append(wall)

    # 初始化敌方坦克, 并将敌方坦克数量添加到列表中
    def create_enemy_tank(self):
        top = 100
        # 循环生成敌方坦克
        for i in range(MainGame.enemy_tank_count):
            left = random.randint(0, 600)
            speed = random.randint(1, 4)
            enemy = EnemyTank(left, top, speed)
            MainGame.enemy_tank_list.append(enemy)

    # 循环展示爆炸效果
    def blit_explode(self):
        for explode in MainGame.explode_list:
            # 判断是否活着
            if explode.live:
                # 展示
                explode.display_explode()
            else:
                # 在爆炸列表中移除
                MainGame.explode_list.remove(explode)

    # 循环遍历敌方坦克列表,展示敌方坦克
    def blit_enemy_tank(self):
        for enemy_tank in MainGame.enemy_tank_list:
            # 判断当前敌方坦克是否活着
            if enemy_tank.live:
                enemy_tank.display_tank()
                enemy_tank.rand_move()
                # 发射子弹
                enemy_bullet = enemy_tank.shot()
                # 敌方子弹是否为None,如果不为None则添加到敌方子弹列表中
                if enemy_bullet:
                    # 将敌方子弹存储到敌方子弹列表中
                    MainGame.enemy_bullet_list.append(enemy_bullet)
            else:    # 不活着,从敌方坦克列表中移除
                MainGame.enemy_tank_list.remove(enemy_tank)

    # 循环遍历我方子弹存储列表
    def blit_my_bullet(self):
        for my_bullet in MainGame.my_bullet_list:
            # 判断当前的子弹是否是活着的状态,如果是则进行显示及移动
            if my_bullet.live:
                my_bullet.display_bullet()
                my_bullet.move()
                # 调用检测我方子弹是否与地方子弹发生碰撞
                my_bullet.my_bullet_hit_enemy_tank()
            # 否则在列表中删除
            else:
                MainGame.my_bullet_list.remove(my_bullet)

    # 循环遍历显示敌方坦克发射的子弹,展示敌方子弹
    def blit_enemy_bullet(self):
        for enemy_bullet in MainGame.enemy_bullet_list:
            # 判断敌方子弹是否存活
            if enemy_bullet.live:
                enemy_bullet.display_bullet()
                enemy_bullet.move()
                # 调用敌方子弹与我方坦克碰撞的方法
                enemy_bullet.enemy_bullet_hit_my_tank()
            else:
                MainGame.enemy_bullet_list.remove(enemy_bullet)

    # 结束游戏
    def end_game(self):
        print("谢谢使用,欢迎再来!")
        exit()

    # 左上角文字的绘制
    def get_text_surface(self, text):
        # 初始化字体模块
        pygame.font.init()
        # 查看所有的字体名称
        # print(pygame.font.get_fonts())
        # 获取字体font对象
        font = pygame.font.SysFont("kaiti", 18)
        # 绘制文字信息
        text_surface = font.render(text, True, text_color)
        return text_surface

    def get_event(self):
        # 获取所有事件
        eventList = pygame.event.get()
        # 遍历事件
        for event in eventList:
            # 判断按下的键是关闭还是键盘按下
            # 如果按的是退出,关闭窗口
            if event.type == pygame.QUIT:
                self.end_game()

            if MainGame.my_tank and MainGame.my_tank.live:
                if event.type == pygame.KEYDOWN:
                    # 判断按下的是上下左右
                    if event.key == pygame.K_LEFT:
                        # 切换方向
                        MainGame.my_tank.direction = "L"
                        # 修改坦克的开关状态
                        MainGame.my_tank.stop = False
                        # MainGame.my_tank.move()
                        print("按下左键,坦克向左移动")
                    elif event.key == pygame.K_RIGHT:
                        # 切换方向
                        MainGame.my_tank.direction = "R"
                        # 修改坦克的开关状态
                        MainGame.my_tank.stop = False
                        # MainGame.my_tank.move()
                        print("按下右键,坦克向右移动")
                    elif event.key == pygame.K_UP:
                        # 切换方向
                        MainGame.my_tank.direction = "U"
                        # 修改坦克的开关状态
                        MainGame.my_tank.stop = False
                        # MainGame.my_tank.move()
                        print("按下上键,坦克向上移动")
                    elif event.key == pygame.K_DOWN:
                        # 切换方向
                        MainGame.my_tank.direction = "D"
                        # 修改坦克的开关状态
                        MainGame.my_tank.stop = False
                        # MainGame.my_tank.move()
                        print("按下下键,坦克向下移动")
                    elif event.key == pygame.K_SPACE:
                        print("发射子弹")
                        # 如果当前我方子弹列表的大小 小于3时,才可以创建子弹
                        if len(MainGame.my_bullet_list) < 3:
                            # 创建我方坦克发射的子弹
                            my_bullet = Bullet(MainGame.my_tank)
                            MainGame.my_bullet_list.append(my_bullet)

            if MainGame.my_tank and MainGame.my_tank.live:
                # 松开方向键,坦克停止移动,修改坦克的开关状态
                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:
                        MainGame.my_tank.stop = True


# 坦克类
class Tank(BaseItem):
    # 添加距离左边left 距离上边top
    def __init__(self, left, top):
        # 保存加载的坦克图片
        self.images = {
            "U": pygame.image.load("img/p1tankU.gif"),
            "D": pygame.image.load("img/p1tankD.gif"),
            "L": pygame.image.load("img/p1tankL.gif"),
            "R": pygame.image.load("img/p1tankR.gif"),
                       }

        # 方向
        self.direction = "L"
        # 根据当前图片的方向获取图片 surface
        self.image = self.images[self.direction]
        # 获取区域
        self.rect = self.image.get_rect()
        # 设置区域的left和top
        self.rect.left = left
        self.rect.top = top

        # 我方坦克移动速度 决定移动的快慢
        self.speed = 5
        # 坦克移动的开关
        self.stop = True
        # 是否活着
        self.live = True

    # 移动
    def move(self):
        # 判断坦克的方向进行移动
        if self.direction == "L":
            if self.rect.left > 0:
                self.rect.left -= self.speed
        elif self.direction == "R":
            if self.rect.height+self.rect.left < SCREEN_WIDTH:
                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_HEIGHT:
                self.rect.top += self.speed

    # 射击
    def shot(self):
        return Bullet(self)

    # 展示坦克的方法
    def display_tank(self):
        # 获取展示的对象
        self.image = self.images[self.direction]
        # 调用blit方法展示
        MainGame.window.blit(self.image, self.rect)

# 我方坦克
class MyTank(Tank):

    def __init__(self):
        pass


# 敌方坦克
class EnemyTank(Tank):

    def __init__(self, left, top, speed):
        # 调用父类的初始化方法
        super(EnemyTank, self).__init__(left, top)
        # 加载图片集
        self.images = {
            "U": pygame.image.load("img/enemy1U.gif"),
            "D": pygame.image.load("img/enemy1D.gif"),
            "L": pygame.image.load("img/enemy1L.gif"),
            "R": pygame.image.load("img/enemy1R.gif")
        }
        # 方向,随机生成敌方坦克的方向
        self.direction = self.rand_direction()

        # 根据方向获取图片
        self.image = self.images[self.direction]
        # 获取敌方坦克区域
        self.rect = self.image.get_rect()
        # 对left和top进行赋值
        self.rect.left = left
        self.rect.top = top
        # 速度
        self.speed = speed
        # 移动开关
        self.flag = True
        # 新增一个步数变量
        self.step = 100

    # 随机生成敌方坦克的方向
    def rand_direction(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 rand_move(self):
        if self.step <= 0:
            # 修改敌方坦克方向
            self.direction = self.rand_direction()
            # 让步数复位
            self.step = 100

        else:
            self.move()
            # 让步数递减
            self.step -= 1

    # 重写shot
    def shot(self):
        # 随机生成100以内的书
        num = random.randint(1, 100)
        if num < 2:
            return Bullet(self)


# 子弹类
class Bullet(BaseItem):

    def __init__(self, tank):
        # 加载图片
        self.image = pygame.image.load("img/enemymissile.gif")
        # 坦克的方向决定子弹的方向
        self.direction = tank.direction
        # 获取区域
        self.rect = self.image.get_rect()
        # 子弹的left和top与坦克的方向有关
        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.width
        elif self.direction == "L":
            self.rect.left = tank.rect.left - self.rect.width
            self.rect.top = tank.rect.top + tank.rect.width//2 - self.rect.height//2
        elif self.direction == "R":
            self.rect.left = tank.rect.left + tank.rect.width
            self.rect.top = tank.rect.top + tank.rect.width//2 - self.rect.height//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 == "D":
            if self.rect.top+self.rect.height < SCREEN_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
        elif self.direction == "R":
            if self.rect.left+self.rect.height < SCREEN_WIDTH:
                self.rect.left += self.speed
            else:
                # 修改子弹的状态
                self.live = False

    # 展示子弹
    def display_bullet(self):
        # 将图片加载到窗口
        MainGame.window.blit(self.image, self.rect)

    # 我方子弹与地方坦克的碰撞
    def my_bullet_hit_enemy_tank(self):
        # 循环遍历敌方坦克列表,判断是否发生碰撞
        for enemy_tank in MainGame.enemy_tank_list:
            if pygame.sprite.collide_rect(enemy_tank, self):
                # 修改敌方坦克和我方子弹的状态
                enemy_tank.live = False
                self.live = False
                # 创建爆炸对象
                explode = Explode(enemy_tank)
                # 将爆炸对象添加到爆炸列表中
                MainGame.explode_list.append(explode)

    # 敌方子弹与我方坦克碰撞
    def enemy_bullet_hit_my_tank(self):
        if MainGame.my_tank and MainGame.my_tank.live:
            if pygame.sprite.collide_rect(MainGame.my_tank, self):
                # 创建爆炸对象
                explode = Explode(MainGame.my_tank)
                # 将爆炸对象添加到爆炸列表中
                MainGame.explode_list.append(explode)
                # 修改我方坦克和敌方子弹的状态
                MainGame.my_tank.live = False
                self.live = False


# 墙壁类
class Wall():

    def __init__(self, left, top):
        # 加载墙壁图片
        self.image = pygame.image.load("img/steels.gif")
        # 获取墙壁的区域
        self.rect = self.image.get_rect()
        # 设置left和top
        self.left = left
        self.top = top
        # 是否活着
        self.live = True
        # 设置生命值
        self.hp = 3

    # 展示墙壁的方法
    def display_wall(self):
        MainGame.window.blit(self.image, self.rect)


# 爆炸类
class Explode():
    def __init__(self, tank):
        # 爆炸位置由当前子弹打中的坦克位置决定
        self.rect = tank.rect
        self.images = [
            pygame.image.load("img/blast0.gif"),
            pygame.image.load("img/blast1.gif"),
            pygame.image.load("img/blast2.gif"),
            pygame.image.load("img/blast3.gif"),
            pygame.image.load("img/blast4.gif")
        ]
        self.step = 0
        self.image = self.images[self.step]
        # 是否活着
        self.live = True

    # 展示爆炸类
    def display_explode(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 Music():

    def __init__(self):
        pass

    # 播放音效类
    def display_music(self):
        pass


if __name__ == "__main__":
    MainGame().start_game()
    # MainGame().get_text_surface()

运行结果图:

1580978866337187.png


Python 全系列/第二阶段:Python 深入与提高/游戏开发-坦克大战 34480楼
Python 全系列/第一阶段:Python入门/面向对象 34481楼
JAVA 全系列/第一阶段:JAVA 快速入门/面向对象详解和JVM底层内存分析 34483楼
Python 全系列/第二阶段:Python 深入与提高/模块 34485楼

课程分类

百战程序员微信公众号

百战程序员微信小程序

©2014-2025百战汇智(北京)科技有限公司 All Rights Reserved 北京亦庄经济开发区科创十四街 赛蒂国际工业园
网站维护:百战汇智(北京)科技有限公司
京公网安备 11011402011233号    京ICP备18060230号-3    营业执照    经营许可证:京B2-20212637