会员可以在此提问,百战程序员老师有问必答
对大家有帮助的问答会被标记为“推荐”
看完课程过来浏览一下别人提的问题,会帮你学得更全面
截止目前,同学们一共提了 132647个问题
Python 全系列/第二阶段:Python 深入与提高/游戏开发-坦克大战 2582楼
Python 全系列/第二阶段:Python 深入与提高/文件处理 2583楼
Python 全系列/第二阶段:Python 深入与提高/异常机制 2585楼

老师我的坦克就只能往上移动,摁下键,左键,右键都是往上运动

"""新增功能:
   1,我方坦克的方向
   2,我方坦克的移动
"""
#导入prcharm模块
import pygame
SCREEN_WIDTH=700    #设置宽度
SCREEN_HEIGHT=500   #设置高度
BG_COLOR=pygame.Color(0,0,0) #设置窗口颜色,0,0,0代表黑色
TEXT_COLOR=pygame.Color(255,0,0)  #设置字体颜色,255,0,0代表红色

#主类
class MainGame():
    window=None
    my_tank=None
    def __init__(self):
        pass
    #开始游戏
    def startGame(self):
        #加载主窗口
        #初始化窗口
        pygame.display.init()
        #设置窗口的大小及显示
        MainGame.window=pygame.display.set_mode([SCREEN_WIDTH,SCREEN_HEIGHT])
        #初始化我方坦克
        MainGame.my_tank=Tank(350,250)
        #设置窗口标题
        pygame.display.set_caption("坦克大战1.03")
        while True:
            #给窗口设置填充色
            MainGame.window.fill(BG_COLOR)
            #获取事件
            self.getEvent()
            #绘制文字
            MainGame.window.blit(self.getTextSuface("敌方坦克剩余数量%d"%6),(10,10))
            #调用坦克显示的方法
            MainGame.my_tank.displayTank()
            pygame.display.update()

    #结束游戏
    def endGame(self):
        print("谢谢使用,欢迎再次使用")
        exit()
    #左上角文字的绘制
    def getTextSuface(self,text):
        #初始化文字模块
        pygame.font.init()
        #查看所有的字体名称
        #print(pygame.font.get_fonts())
        #获取字体Font对象
        font=pygame.font.SysFont("kaiti",18)
        #绘制文字信息
        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 event.key==pygame.K_LEFT:
                    #切换方向
                    MainGame.my_tank.direction="L"
                    MainGame.my_tank.move()
                    print("按下左键,坦克向左移动")
                elif event.key==pygame.K_RIGHT:
                    #切换方向
                    MainGame.my_tank.direction = "R"
                    MainGame.my_tank.move()
                    print("按下右键,坦克向右移动")
                elif event.key==pygame.K_UP:
                    #切换方向
                    MainGame.my_tank.direction = "U"
                    MainGame.my_tank.move()
                    print("按下上键,坦克向上移动")
                elif event.key == pygame.K_DOWN:
                    #切换方向
                    MainGame.my_tank.direction = "D"
                    MainGame.my_tank.move()
                    print("按下下键,坦克向下移动")

#坦克类
class Tank():
    #添加距离左边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.dirction="R"
        #根据当前图片的方向获取图片 surface
        self.image=self.images[self.dirction]
        #根据图片获取区域
        self.rect=self.image.get_rect()
        #设置区域的left 和top
        self.rect.left=left
        self.rect.top=top
        #速度 决定移动的快慢
        self.speed=10



    #移动
    def move(self):
        #判断坦克的方向进行移动
        if self.dirction=="L":
            self.rect.left -= self.speed
        elif self.dirction == "U":
            self.rect.top -= self.speed
        elif self.dirction == "D":
            self.rect.top += self.speed
        elif self.dirction == "R":
            self.rect.left += self.speed
    #射击
    def shot(self):
        pass
    #展示坦克方法
    def displayTank(self):
        #获取展示的对象
        self.image=self.images[self.dirction]
        #调用blit方法展示
        MainGame.window.blit(self.image,self.rect)
#我方坦克
class MyTank(Tank):
    def __init__(self):
        pass
#敌方坦克
class EnemyTank(Tank):
    def __init__(self):
        pass

#子弹类
class Bullet():
    def __init__(self):
        pass
    #移动
    def move(self):
        pass
    #展示子弹的方法:
    def displayBullet(self):
        pass

class Wall():
    def __init__(self):
        pass
    #展示墙壁的方法
    def displayWall(self):
        pass
class Explode():
    def __init__(self):
        pass
    #展示爆炸效果的方法
    def displayExplode(self):
        pass
class Music():
    def __init__(self):
        pass
    #播放音乐
    def play(self):
        pass

if __name__=="__main__":
    MainGame().startGame()
    #MainGame().getTextSuface()


Python 全系列/第二阶段:Python 深入与提高/游戏开发-坦克大战 2586楼

QQ截图20190709131151.png

pygame已经存在,但导入不了

Python 全系列/第二阶段:Python 深入与提高/游戏开发-坦克大战 2588楼
Python 全系列/第二阶段:Python 深入与提高/文件处理 2589楼

当敌方子弹击中我方坦克时,游戏界面停止了,并没有出现爆炸效果
pygametimerandom
pygame.sprite Sprite

SCREEN_WIDTH SCREEN_HEIGHT BG_COLOR pygame.TEXT_COLOR pygame.BaseItemSpritepygame.sprite.Sprite.MainGamewindow my_tank enemyTankList enemyTankCount myBulletList enemyBulletList explodeList pygame.display.MainGame.window pygame.display.SCREEN_WIDTHSCREEN_HEIGHTMainGame.my_tank Tank.pygame.display.time.MainGame.window.BG_COLOR.MainGame.window..MainGame.enemyTankListMainGame.my_tank MainGame.my_tank.liveMainGame.my_tank.MainGame.my_tank
                MainGame.my_tank ....MainGame.my_tank MainGame.my_tank.liveMainGame.my_tank.stopMainGame.my_tank.pygame.display.top i MainGame.enemyTankCountleft random.speed random.enemy EnemyTanklefttopspeedMainGame.enemyTankList.enemyexplode MainGame.explodeListexplode.liveexplode.MainGame.explodeList.explodeenemyTank MainGame.enemyTankListenemyTank.liveenemyTank.enemyTank.enemyBullet enemyTank.enemyBulletMainGame.enemyBulletList.enemyBulletMainGame.enemyTankList.enemyTankmyBullet MainGame.myBulletListmyBullet.livemyBullet.myBullet.myBullet.MainGame.myBulletList.myBulletenemyBullet MainGame.enemyBulletListenemyBullet.liveenemyBullet.enemyBullet.enemyBullet.MainGame.enemyBulletList.enemyBulletpygame.font.font pygame.font.textSurface font.TEXT_COLORtextSurface

    eventList pygame.event.event eventListevent.type pygame.QUIT.event.type pygame.KEYDOWNMainGame.my_tank MainGame.my_tank.liveevent.key pygame.K_LEFTMainGame.my_tank.direction MainGame.my_tank.stop event.key pygame.K_RIGHTMainGame.my_tank.direction MainGame.my_tank.stop event.key pygame.K_UPMainGame.my_tank.direction MainGame.my_tank.stop event.key pygame.K_DOWNMainGame.my_tank.direction MainGame.my_tank.stop event.key pygame.K_SPACEMainGame.myBulletListmyBullet BulletMainGame.my_tankMainGame.myBulletList.myBulletevent.type pygame.KEYUPevent.key pygame.K_UP pygame.K_DOWN event.key pygame.K_LEFT event.key pygame.K_RIGHTMainGame.my_tank MainGame.my_tank.liveMainGame.my_tank.stop TankBaseItem.images pygame.image.pygame.image.pygame.image.pygame.image..direction .image .images.direction.rect .image..rect.left .rect.top .speed .stop .live .direction .rect.left .rect.left .speed
        .direction .rect.top .rect.top .speed
        .direction .rect.top .rect.height SCREEN_HEIGHT.rect.top .speed
        .direction .rect.left .rect.height SCREEN_WIDTH.rect.left .speed

    Bullet.image .images.directionMainGame.window..image.rectMyTankTankEnemyTankTankEnemyTank..images pygame.image.pygame.image.pygame.image.pygame.image..direction ..image .images.direction.rect .image..rect.left .rect.top .speed .flag .step num random.num num num num .step .direction ..step ..step num random.num BulletBulletBaseItem.image pygame.image..direction .direction
        .rect .image..direction .rect.left .rect.left .rect.width.rect.width.rect.top .rect.top .rect.height
        .direction .rect.left .rect.left .rect.width.rect.width.rect.top .rect.top .rect.height
        .direction .rect.left .rect.left .rect.width.rect.width.rect.top .rect.top .rect.width.rect.width.direction .rect.left .rect.left .rect.width
            .rect.top .rect.top .rect.width.rect.width.speed .live .direction .rect.top .rect.top .speed
            .live .direction .rect.left .rect.width SCREEN_WIDTH.rect.left .speed
            .live .direction .rect.top .rect.height SCREEN_HEIGHT.rect.top .speed
            .live .direction .rect.left .rect.left .speed
            .live MainGame.window..image.rectenemyTank MainGame.enemyTankListpygame.sprite.enemyTankenemyTank.live .live explode ExplodeenemyTankMainGame.explodeList.explodeMainGame.my_tank MainGame.my_tank.livepygame.sprite.MainGame.my_tankexplode ExplodeMainGame.my_tankMainGame.explodeList.explode.live MainGame.my_tank.live WallExplode.rect .rect
        .images pygame.image.pygame.image.pygame.image.pygame.image.pygame.image..step .image .images.step.live .step .images.image .images.step.step MainGame.window..image.rect.live .step Music__name__ MainGame.

11.jpg

22.jpg

Python 全系列/第二阶段:Python 深入与提高/游戏开发-坦克大战 2590楼

from tkinter import *
from tkinter.filedialog import *
from tkinter.colorchooser import *

class Application(Frame):
    def __init__(self, master=None):
        super().__init__(master)    # super代表的是父类的定义,而不是父类的对象
        self.master = master
        self.filename = None   # filename表示打开文本文件的名字
        self.contextMenu = None   # contextMenu表示上下文菜单
        self.textpad = None   # textpad表示文本框对象
        self.pack()
        self.createWidget()

    def createWidget(self):
        # 创建主菜单栏
        menuber = Menu(root)
        # 创建子菜单栏
        menuFlie = Menu(menuber)
        menuEdit = Menu(menuber)
        menuHelp = Menu(menuber)

        # 将子菜单加入到主菜单栏中
        menuber.add_cascade(label="文件(F)", menu=menuFlie)
        menuber.add_cascade(label="编辑(E)", menu=menuEdit)
        menuber.add_cascade(label="帮助(H)", menu=menuHelp)

        # 添加菜单选项

        menuFlie.add_command(label="新建", accelerator="ctrl+n", command=self.newfile)
        menuFlie.add_command(label="打开", accelerator="ctrl+o", command=self.openFile)
        menuFlie.add_command(label="保存", accelerator="ctrl+s", command=self.savefile)
        menuFlie.add_separator()  # 添加分割线
        menuFlie.add_command(label="退出", accelerator="ctrl+q", command=self.exit)

        # 将主菜单栏加到根窗口
        root["menu"] = menuber

        # 添加快捷键事件处理
        root.bind("<Control-n>", lambda event:self.newfile())
        root.bind("<Control-o>", lambda event: self.openFile())
        root.bind("<Control-s>", lambda event: self.savefile())
        root.bind("<Control-q>", lambda event: self.exit())
        # 文本编辑区
        self.textpad = Text(root, width=80, height=30)
        self.textpad.pack()

        # 创建上下文菜单
        self.contextMenu = Menu(root)
        self.contextMenu.add_command(label="背景颜色", command=self.openAsk)

        # 为右键绑定事件
        root.bind("<Button-3>", self.createContextMenu)

    def newfile(self):
        self.textpad.delete(1.0, END)
        self.filename = askopenfilename(title="另存为", initialfile="未命名.txt",
                                        filetypes=[("文本文档", "*.txt")],
                                        defaultextension=".txt")
        self.savefile()

    def openFile(self):
        self.textpad.delete(1.0,END)  # 把控件中的所有内容清空
        with askopenfile(title="打开文本文件") as f:
            self.textpad.insert(INSERT, f.read())
            self.filename = f.name
            #print(f.read())

    def savefile(self):
        with open(self.filename, "w") as f:
            c = self.textpad.get(1.0, END)
            f.write(c)

    def exit(self):
        root.quit()


    def openAsk(self):
        s1 = askcolor(color="red", title="选择背景色")
        self.textpad.config(bg=s1[1])

    def createContextMenu(self, event):
        # 菜单在鼠标右键单击坐标处显示
        self.contextMenu.post(event.x_root, event.y_root)
if __name__ == "__main__":
    root = Tk()
    root.geometry("450x300+300+300")
    root.title("简易记事本")
    app = Application(master=root)
    root.mainloop()

老师我的代码进行新建操作会报错,保存也会报错

image.png

image.png

Python 全系列/第二阶段:Python 深入与提高/GUI编程(隐藏) 2591楼

from tkinter.filedialog  import *
from tkinter.colorchooser import *
win_width=900
win_height=450


class Application(Frame):
    def __init__(self,master=None,bgcolor="#000000"):
        super().__init__(master)
        self.master = master
        self.bgcolor=bgcolor
        self.x = 0
        self.y = 0
        self.fgcolor = "#ff0000"
        self.pack()
        self.createWidget()

    def createWidget(self):
        self.drawpad = Canvas(root,width=win_width,height=win_height*0.9,bg=self.bgcolor)
        self.drawpad.pack()

        btn_start = Button(root,text="开始",name="start")
        btn_start.pack(side="left",padx="10")

        btn_pen = Button(root, text="画笔", name="pen")
        btn_pen.pack(side="left", padx="10")

        btn_line = Button(root,text="直线",name="line")
        btn_line.pack(side="left",padx="10")

        btn_circle = Button(root,text="圆",name="circle")
        btn_circle.pack(side="left",padx="10")

        btn_eraser = Button(root,text="橡皮擦",name="eraser")
        btn_eraser.pack(side="left",padx="10")

        btn_rect = Button(root,text="矩形",name="rect")
        btn_rect.pack(side="left",padx="10")

        btn_clear = Button(root,text="清屏",name="clear")
        btn_clear.pack(side="left",padx="10")

        btn_linearrow = Button(root, text="箭头线", name="linearrow")
        btn_linearrow.pack(side="left", padx="10")

        btn_color = Button(root,text="颜色",name="color")
        btn_color.pack(side="left",padx="10")

    def eventManager(self,event):
        name = event.widget.winfo_name()
        print(name)
        if name == "line":
            self.drawpad.bind("<B1-Motion>",self.myline)

    def myline(self,event):
        self.drawpad.create_line(self.x,self.y,event.x,event.y,fill=self.fgcolor)

if __name__ == '__main__':
    root = Tk()
    root.geometry(str(win_width)+"x"+str(win_height)+"+200+100")
    root.title("画图软件")
    app = Application(master=root)
    root.mainloop()

老师,这个运行下来不报错也没反应

Python 全系列/第二阶段:Python 深入与提高/GUI编程(隐藏) 2592楼
Python 全系列/第二阶段:Python 深入与提高/模块 2593楼
Python 全系列/第二阶段:Python 深入与提高/文件处理 2594楼
Python 全系列/第二阶段:Python 深入与提高/异常机制 2595楼

课程分类

百战程序员微信公众号

百战程序员微信小程序

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