会员可以在此提问,百战程序员老师有问必答
对大家有帮助的问答会被标记为“推荐”
看完课程过来浏览一下别人提的问题,会帮你学得更全面
截止目前,同学们一共提了 132499个问题
Python 全系列/第四阶段:函数式编程和核心特性/正则表达式 23491楼
JAVA 全系列/第三阶段:数据库编程/MySQL数据库的使用 23493楼

package com.bjsxt.array;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Date;

public class Test {
	public static void main(String[] args) {
		byte [] buf=write();//调用写对象的方法
		//调用读对象的方法
		read(buf);
	}
	public static byte[] write(){
		//创建字节数组流对象
		ByteArrayOutputStream baos=null;
		ObjectOutputStream oos=null;
		
		try {
			baos=new ByteArrayOutputStream();//创建字节数组流对象,目的地是字节数组,底层创建一个长度数为32的字节数组
			oos=new ObjectOutputStream(baos);
			oos.writeInt(98);
			oos.writeDouble(98.5);
			oos.writeChar('a');
			oos.writeBoolean(false);
			oos.writeObject(new Date(1000));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			//关闭流
			if (oos!=null) {
				try {
					oos.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		
		return baos.toByteArray();
	}
	public static void read(byte [] buf){
		ByteArrayInputStream bais=null;
		ObjectInputStream ois=null;
		//创建对象
		try {
			bais=new ByteArrayInputStream(buf); //数据源是byte类型的数组
			ois=new ObjectInputStream(bais);
			
			//读数据
			System.out.println(ois.readInt());
			System.out.println(ois.readDouble());
			System.out.println(ois.readChar());
			System.out.println(ois.readBoolean());
			System.out.println(ois.readObject());
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
		
			//关闭流
			if(ois!=null){
				try {
					ois.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
}

这里主函数去调用写出方法时是这样调用的

byte [] buf=write();//调用写对象的方法

有什么说法吗   第一次见这种写法

JAVA 全系列/第二阶段:JAVA 基础深化和提高/IO 流技术(旧) 23494楼
Python 全系列/第二阶段:Python 深入与提高/游戏开发-坦克大战 23495楼

敌方子弹打中我方坦克时画面就卡住了是什么原因?

image.png

import pygame
import time,random
SCREEN_WIDTH=700
SCREEN_HEIGHT=500
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):
        pygame.sprite.Sprite.__init__(self)
class MainGame():
    window=None
    my_tank=None
    #存储敌方坦克列表
    enemyTankList=[]
    #定义敌方坦克数量
    enemyTankCount=5
    #存储我方子弹的列表
    myBulletList=[]
    #存储敌方子弹的列表
    enemyBulletList=[]
    # 存储爆炸效果
    explodeList=[]
    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)
        #初始化敌方坦克,并将敌方坦克添加到列表中
        self.createEnemyTank()
        #设置窗口标题
        pygame.display.set_caption('坦克大战1.03')
        while True:
            #使坦克移动速度慢些
            time.sleep(0.02)
            #给窗口设置填充色
            MainGame.window.fill(BG_COLOR)
            #获取事件
            self.getEvent()
            #绘制文字
            MainGame.window.blit(self.getTextSuface('敌方坦克剩余数量%d'%len(MainGame.enemyTankList)),(10,10))
            #调用坦克显示的方法
            #判断我方坦克是否存活
            if MainGame.my_tank and MainGame.my_tank.live:
                MainGame.my_tank.displayTank()
            else:
                #删除我方坦克
                del MainGame.my_tank
                MainGame.my_tank=None
            #循环遍历敌方坦克列表,展示敌方坦克
            self.blitEnemyTank()
            #循环遍历显示我方坦克的子弹
            self.blitMyBullet()
            #循环遍历敌方子弹列表,展示敌方子弹
            self.blitEnemyBullet()
            #循环遍历爆炸列表,展示爆炸效果
            self.blitExplode()
            #调用移动方法
            #如果坦克的开关开启才可以移动
            if MainGame.my_tank and MainGame.my_tank.live:
                if not MainGame.my_tank.stop:
                    MainGame.my_tank.move()
                pygame.display.update()
    # 初始化敌方坦克,并将敌方坦克添加到列表中
    def createEnemyTank(self):
        top=10
        #循环生成敌方坦克
        for i in range(MainGame.enemyTankCount):
            left=random.randint(0,600)
            speed=random.randint(1,4)
            enemy=EnemyTank(left,top,speed)
            MainGame.enemyTankList.append(enemy)
    #循环展示爆炸效果
    def blitExplode(self):
        for explode in MainGame.explodeList:
            #判断是否活着
            if explode.live:
                #展示
                explode.displayExplode()
            else:
                #在爆炸列表中移除
                MainGame.explodeList.remove(explode)


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

    #循环遍历我方子弹存储列表
    def blitMyBullet(self):
        for myBullet in MainGame.myBulletList:
            #判断当前的子弹是否是活着状态,如果是则进行显示及移动,否则在列表中删除
            if myBullet.live:
                myBullet.displayBullet()
            #调用子弹的移动方法
                myBullet.move()
                #调用检测我方子弹是否与敌方坦克发生碰撞
                myBullet.myBullet_hit_enemyTank()
            else:
                MainGame.myBulletList.remove(myBullet)
    #循环遍历敌方子弹列表,展示敌方子弹
    def blitEnemyBullet(self):
        for enemyBullet in MainGame.enemyBulletList:
            if enemyBullet.live:
                enemyBullet.displayBullet()
                enemyBullet.move()
                #调用敌方子弹与我方坦克碰撞的方法
                enemyBullet.hit_myTank()
            else:
                MainGame.enemyBulletList.remove(enemyBullet)

    #结束游戏
    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 MainGame.my_tank and MainGame.my_tank.live:
                    #判断按下的是上、下、左、右
                    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('发射子弹')
                        #如果当前我方子弹列表的大小小于等于三时才能创建
                        if len(MainGame.myBulletList)<3:
                        # 创建我方坦克发射的子弹
                            myBullet=Bullet(MainGame.my_tank)
                            MainGame.myBulletList.append(myBullet)
            # 松开方向键,坦克停止移动,修改坦克的开关状态
            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.my_tank and MainGame.my_tank.live:
                        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='U'
        #根据当前图片的方向获取图片 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 == '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
        elif self.direction == 'R':
            if self.rect.left+self.rect.height<SCREEN_WIDTH:
                self.rect.left += self.speed
    #射击
    def shot(self):
        return Bullet(self)
    #展示坦克的方法
    def displayTank(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.randDirection()
        #根据方向获取图片
        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=60

    #随机生成敌方坦克的方向
    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
    #重写shot()
    def shot(self):
        #随机生成100以内的数
        num=random.randint(1,100)
        if num<3:
            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.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.width / 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.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_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
    #展示子弹的方法
    def displayBullet(self):
        #将图片surface加载到窗口
        MainGame.window.blit(self.image,self.rect)
    #我方子弹与敌方坦克的碰撞
    def myBullet_hit_enemyTank(self):
        #循环遍历敌方坦克列表,判断是否发生碰撞
        for enemyTank in MainGame.enemyTankList:
            if pygame.sprite.collide_rect(enemyTank,self):
                #修改敌方坦克和我方子弹的状态
                enemyTank.live=False
                self.live=False
                #创建爆炸对象
                explode=Explode(enemyTank)
                #将爆炸添加到爆炸列表中
                MainGame.explodeList.append(explode)
    #敌方子弹与我方坦克的碰撞
    def hit_myTank(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.explodeList.append(explode)
                #修改敌方子弹与我的坦克的状态
                self.live=False
                MainGame.my_tank.live=False

class Wall():
    def __init__(self):
        pass
    #展示墙壁的方法
    def displayWall(self):
        pass

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 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 Music():
    def __init__(self):
        pass
    #播放音乐的方法
    def play(self):
        pass

if __name__=='__main__':
    MainGame().startGame()


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

老师,我是照着你的代码的逻辑写的,为什么你的运行没出问题,我的运行出问题了,麻烦帮忙看下,谢谢!

class Array():
    def __init__(self,size=4):
        self.__size = size # 记录容器大小
        self.__item = [None]*size #分配空间
        self.__length = 0

    def __setitem__(self,key,value):
        self.__item[key] = value
        self.__length += 1

    def __getitem__(self,key):
        return self.__item[key]
    
    def __len__(self):
        return self.__length
    
    def __iter__(self):
        for value in self.__item:
            yield value


class Slot():
    def __init__(self,key=None,value=None,next=None):
        self.key = key
        self.value = value
        self.next = next
    
    def __str__(self):
        return 'key:{},value:{}'.format(self.key,self.value)
    
class HashTable():
    def __init__(self,size=4):
        self.size = size
        self.item = Array(self.size)
    
    def get_index(self,key):
        return hash(key) % self.size
    
    def push(self,key,value): # 存放数据
        s = Slot(key,value)
        index = self.get_index(key)  # # 获取默认的索引位置
        if self.item[index] == None: # 索引位置是空的
            self.item[index] = s
        else: # 索引位置是非空的
            if self.item[index].key == key: # 所占空间的数据的key 与 传入数据 key 相同
                self.item[index].value = value 
            else: # 所占空间的数据的key 与 传入数据 key 不相同
                temp_next = self.item[index].next # 记录下一个节点
                while temp_next is not None:
                    if temp_next.key == key:
                        temp_next.value = value # 更新原来节点的数据
                        return
                    temp_next = temp_next.next # 继续往下移动一个节点
                temp_next = s
    
    def get(self,key): # 获取数据
        index = self.get_index(key) # 获取key对应的索引
        if self.item[index]: # 索引位置不为空
            if self.item[index].key == key:  # 索引位置的key 与 传入数据 key 相同
                return self.item[index].value # 获取索引位置的key对应的value
            else:
                temp_next = self.item[index].next # 记录下一个节点
                while temp_next is not None: # 下一个节点不为空
                    if temp_next.key == key:
                        return temp_next.value # 找到则获取
                    temp_next = temp_next.next  # 未找到则继续往下移动一个节点
                return None
        return None

if __name__ == "__main__":
    h = HashTable()
    h.push('name','吕布')
    h.push('sex1','男')
    h.push('sex2','女')
    h.push('sex3','保密')

    print(h.get('name'))
    print(h.get('sex3'))
    print(h.get('sex2'))
    print(h.get('sex1'))
    # print(h.get('age'))

运行截图:

image.png



Python 全系列/第十六阶段:数据结构与算法/算法与数据结构(旧) 23500楼

已经导入jaxen包了,为啥还是会出现找不包的异常,用的是IDEA

package com.zheng.TestXML;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import java.io.File;

public class TextXpath {
    public static void main(String[] args) throws DocumentException {
        //1) 创建 SAXReader 对象
        SAXReader reader = new SAXReader();
        //2) 调用 read 方法
        Document doc = reader.read(new File("books.xml"));
        //3)
        Node node = doc.selectSingleNode("//name");
        System.out.println("节点的名称:"+node.getName()+"节点的值"+node.getText());
    }
}

"E:\学习软件大集合\IDEA\IntelliJ IDEA 2019.3.2\jbr\bin\java.exe" "-javaagent:E:\学习软件大集合\IDEA\IntelliJ IDEA 2019.3.2\lib\idea_rt.jar=49244:E:\学习软件大集合\IDEA\IntelliJ IDEA 2019.3.2\bin" -Dfile.encoding=UTF-8 -classpath C:\Users\zheng\Desktop\mycode\Process\out\production\XML;C:\Users\zheng\Desktop\mycode\Process\lib\jdom.jar;C:\Users\zheng\Desktop\mycode\Process\lib\dom4j-1.6.1.jar com.zheng.TestXML.TextXpath
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.dom4j.io.SAXContentHandler (file:/C:/Users/zheng/Desktop/mycode/Process/lib/dom4j-1.6.1.jar) to method com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser$LocatorProxy.getEncoding()
WARNING: Please consider reporting this to the maintainers of org.dom4j.io.SAXContentHandler
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
Exception in thread "main" java.lang.NoClassDefFoundError: org/jaxen/JaxenException
	at org.dom4j.DocumentFactory.createXPath(DocumentFactory.java:230)
	at org.dom4j.tree.AbstractNode.createXPath(AbstractNode.java:207)
	at org.dom4j.tree.AbstractNode.selectSingleNode(AbstractNode.java:183)
	at com.zheng.TestXML.TextXpath.main(TextXpath.java:22)
Caused by: java.lang.ClassNotFoundException: org.jaxen.JaxenException
	at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:581)
	at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
	at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
	... 4 more


JAVA 全系列/第二阶段:JAVA 基础深化和提高/XML 技术(旧) 23501楼
WEB前端全系列/第十二阶段:前端工程化(旧)/Webpack 23505楼

课程分类

百战程序员微信公众号

百战程序员微信小程序

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