会员可以在此提问,百战程序员老师有问必答
对大家有帮助的问答会被标记为“推荐”
看完课程过来浏览一下别人提的问题,会帮你学得更全面
截止目前,同学们一共提了 132463个问题
JAVA 全系列/第一阶段:JAVA 快速入门/JAVA入门和背景知识 35341楼
JAVA 全系列/第一阶段:JAVA 快速入门/JAVA入门和背景知识 35342楼
Python 全系列/第一阶段:Python入门/面向对象 35343楼
Python 全系列/第二阶段:Python 深入与提高/模块 35344楼

老师,运行没报错,也显示坦克了,可是坦克不能移动,帮我看看哪里错了?

"""
新增功能:
    1.我方坦克切换方向
    2.我方坦克移动
"""

import pygame    # 导入pygame模块

SCREEN_WIDTH = 700
SCREEN_HEIGHT = 500
BG_COLOR = pygame.Color(0, 0, 0)
TEXT_COLOR = pygame.Color(255, 0, 0)


class MainGame():
    window = None
    my_tank = None

    def __init__(self):
        pass

    def startGmae(self):    # 开始游戏
        pygame.display.init()    # 加载主窗口和初始化主窗口
        MainGame.window = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT])    # 设置窗口的大小及显示
        MainGame.my_tank = Tank(350, 250)    # 初始化我方坦克
        pygame.display.set_caption('坦克大战')    # 设置窗口的标题
        while True:
            MainGame.window.fill(BG_COLOR)    # 给窗口设置填充色
            self.getEvent()    # 获取事件
            MainGame.window.blit(self.getTextSuface('敌方坦克剩余数量{0}'.format(6)), (10, 10))    # 绘制文字
            MainGame.my_tank = Tank(350, 250)    # 调用坦克显示的方法
            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 = pygame.font.SysFont('kaiti', 18)    # 获取字体Font对象
        textSuface = font.render(text, True, TEXT_COLOR)    # 绘制文字信息
        return textSuface

    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():
    def __init__(self, left, top):    # 添加距离左边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'    # 方向
        self.image = self.images[self.direction]    # 根据当前图片的方向获取图片 suface
        self.rect = self.image.get_rect()    # 根据图片获取区域
        self.rect.left = left    # 设置区域的left和top
        self.rect.top = top
        self.speed = 10    # 速度  决定移动的快慢

    # 移动
    def move(self):
        # 判断坦克的方向进行移动
        if self.direction == 'L':
            self.rect.left -= self.speed
        elif self.direction == 'U':
            self.rect.top -= self.speed
        elif self.direction == 'D':
            self.rect.top += self.speed
        elif self.direction == 'R':
            self.rect.left += self.speed

    # 射击
    def shot(self):
        pass

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


# 我方坦克
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().startGmae()
    MainGame().getTextSuface()

运行结果:

微信截图_20191115172341.png


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

untitled folder.zip

老师请问一下怎么在一个module里面修改另一个module里面的全局变量, 在同一个module里面可以修改,但是如果从另个一个module修改就不行.这是为什么..

Python 全系列/第二阶段:Python 深入与提高/模块 35347楼
Python 全系列/第二阶段:Python 深入与提高/文件处理 35350楼
Python 全系列/第二阶段:Python 深入与提高/游戏开发-坦克大战 35351楼
JAVA 全系列/(旧的隐藏)第十五阶段:百战商城项目(Spring Cloud最新架构)/百战商城项目 35353楼

from urllib.request import Request,build_opener,HTTPCookieProcessor
from urllib.parse import urlencode  #转换用的
from fake_useragent import UserAgent
from http.cookiejar import MozillaCookieJar#保存cookie得文件需要引进的模块

def get_cookie():
    login_url='http://learn.open.com.cn/Account/Login'#登录网站的url
    from_data={
        "user": "jxt17703612482",
        "password": "JXTjxt00"
    }
    headers={"UserAgent":UserAgent().random}
    rep=Request(login_url, headers=headers, data=urlencode(from_data).encode())

    cookie_jar=MozillaCookieJar()#保存cookie
    handler=HTTPCookieProcessor(cookie_jar)#参数cookie
    opener=build_opener(handler)
    resp=opener.open(rep)
    cookie_jar.save('cookie.txt',ignore_discard=True,ignore_expires=True)#【!】保存cookie,在cookie.txt文件夹里

def use_cookie():
    info_url='http://learn.open.com.cn/StudentCenter/MyCourse/MyCourseDetail?CourseID=69249&CourseIndex=0'#登录个人中心的url
    headers = {"UserAgent": UserAgent().random}
    rea=Request(info_url,headers=headers)
    cookie_jar=MozillaCookieJar()
    cookie_jar.load('cookie.txt',ignore_discard=True,ignore_expires=True)#加载用cookie_jar.load
    handler=HTTPCookieProcessor(cookie_jar)
    opener=build_opener(handler)
    resp=opener.open(rea)
    print(resp.read().decode())


if __name__ == '__main__':
    get_cookie()
    # use_cookie()

老师,我这显示以下错误,上面是我得代码。我搞了一个多小时了,也没整明白,你帮我看看。

D:\pythonDownloads\python.exe E:/demo1/test12/pdemo/15cookie的使用3.py

Traceback (most recent call last):

  File "E:/demo1/test12/pdemo/15cookie的使用3.py", line 34, in <module>

    get_cookie()

  File "E:/demo1/test12/pdemo/15cookie的使用3.py", line 18, in get_cookie

    resp=opener.open(rep)

  File "D:\pythonDownloads\lib\urllib\request.py", line 531, in open

    response = meth(req, response)

  File "D:\pythonDownloads\lib\urllib\request.py", line 641, in http_response

    'http', request, response, code, msg, hdrs)

  File "D:\pythonDownloads\lib\urllib\request.py", line 569, in error

    return self._call_chain(*args)

  File "D:\pythonDownloads\lib\urllib\request.py", line 503, in _call_chain

    result = func(*args)

  File "D:\pythonDownloads\lib\urllib\request.py", line 649, in http_error_default

    raise HTTPError(req.full_url, code, msg, hdrs, fp)

urllib.error.HTTPError: HTTP Error 403: Forbidden


Process finished with exit code 1


Python 全系列/第十五阶段:Python 爬虫开发/scrapy框架使用(旧) 35354楼

老师好,请看一下,

异常名称:Exception in thread "main" java.net.SocketException: Connection reset

想要知道怎么避免,怎么操作,请演示一下

已通过防火墙

image.png

客户端:

package cn.sxt.entity;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Scanner;

public class Client2 {
	public static void main(String[] args) throws IOException {
		//1创建socket对象,用于连接服务器
		Socket client = new Socket("localhost", 9999);
		//2获取输出流(对象流)
		ObjectOutputStream oos = new ObjectOutputStream(client.getOutputStream());
		//3创建user对象
					//获取user对象的方法
		User2 user = getUser();//new User2("sxt", "sxt");
		//4user对象发送到服务器
		oos.writeObject(user);//发生了向上转型
		//5获取输入流(数据流)
		DataInputStream dis = new DataInputStream(client.getInputStream());
		System.out.println(dis.readUTF());
		//6关闭流
		if (dis!=null) {
			dis.close();
		}
		if (oos!=null) {
			oos.close();
		}
		if (client!=null) {
			client.close();
		}
	}
	public static User2 getUser() {//获取对象的方法
		Scanner sc = new Scanner(System.in);
		System.out.println("请输入账户名");
		String userName = sc.next();
		System.out.println("请输入密码");
		String passWord = sc.next();
		return new User2(userName, passWord);
	}
}

服务器端:

package cn.sxt.server;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;


import cn.sxt.entity.User2;

public class Server2 {
	public static void main(String[] args) throws IOException, ClassNotFoundException {
		System.out.println("----------服务器端已启动---------");
		//1.创建ServerSocket对象
		ServerSocket server = new ServerSocket(9999);
		Socket client = server.accept();
		//2.创建输入流--->ObjectInputStream
		ObjectInputStream ois = new ObjectInputStream(client.getInputStream());
		User2 user = (User2)ois.readObject();//向下转型
		System.out.println(client.getInetAddress().getHostAddress()+"请求登录:用户名:"+user.getUserName()+"\t密码:"+user.getPassWord());
		//3.对用户名和密码进行验证
		String str = "";
		if ("sxt".equals(user.getUserName())&&"sxt".equals(user.getPassWord())) {
			str = "登录成功";
		}else {
			str = "对不起,用户名或密码错误";
		}
		//4.获取输出流(数据流)
		DataOutputStream dos = new DataOutputStream(client.getOutputStream());
		dos.writeUTF(str);
		//5.关闭流
		if (dos!=null) {
			dos.close();
		}
		if (ois!=null) {
			ois.close();
		}
		if (client!=null) {
			client.close();
		}
	}
}

运行效果:

image.png

JAVA 全系列/第二阶段:JAVA 基础深化和提高/网络编程(旧) 35355楼

课程分类

百战程序员微信公众号

百战程序员微信小程序

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