導航:首頁 > 編程語言 > Nodesjava

Nodesjava

發布時間:2022-08-28 10:32:10

java中.html文件和.java文件的用途及運行環境

您好,這樣的:
解析HTML文檔的Java程序
下面是一個解析HTML字元串,網路上下載的HTML文件,以及本地文件系統中的HTML文件的完整的Java程序。你可以使用Eclipse IDE或者別的IDE甚至命令來運行這個程序。在Eclipse裡面則很簡單,拷貝這份代碼,新建一個Java工程,在src包上右鍵並粘貼進去就可以了。Eclipse會去創建正確的包及同名的Java源文件的,因此工作量最小。如果你已經有一個Java示例工程了,那麼僅需一步就可以了。下面的這個Java程序展示了解析及遍歷HTML文件的三個不同例子。第一個例子中,我們直接解析了一個內容為HTML的字元串,第二個例子中我們解析了一個從URL中下載的HTML文件,第三個中我們從本地文件系統中載入了一個HTML文檔並進行解析。第一和第三個例子中都用到了parse方法來獲取一個Document對象,你可以查詢它來提取出任何的標簽值或者屬性值。第二個例子中,我們用到了Jsoup.connect方法,它會去創建URL的連接,下載HTML並進行解析。這個方法也會返回Document,它可以用於後續的查詢及獲取標簽或者屬性的值。
import java.io.IOException;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

/**
[*] Java Program to parse/read HTML documents from File using Jsoup library.
[*] Jsoup is an open source library which allows Java developer to parse HTML
[*] files and extract elements, manipulate data, change style using DOM, CSS and
[*] JQuery like method.
[*]
[*] @author Javin Paul
[*]/
public class HTMLParser{

public static void main(String args[]) {

// Parse HTML String using JSoup library
String HTMLSTring = "<!DOCTYPE html>"
+ "<html>"
+ "<head>"
+ "<title>JSoup Example</title>"
+ "</head>"
+ "<body>"
+ "|[b]HelloWorld[/b]"
+ ""
+ "</body>"
+ "</html>";

Document html = Jsoup.parse(HTMLSTring);
String title = html.title();
String h1 = html.body().getElementsByTag("h1").text();

System.out.println("Input HTML String to JSoup :" + HTMLSTring);
System.out.println("After parsing, Title : " + title);
System.out.println("Afte parsing, Heading : " + h1);

// JSoup Example 2 - Reading HTML page from URL
Document doc;
try {
doc = Jsoup.connect("http://google.com/").get();
title = doc.title();
} catch (IOException e) {
e.printStackTrace();
}

System.out.println("Jsoup Can read HTML page from URL, title : " + title);

// JSoup Example 3 - Parsing an HTML file in Java
//Document htmlFile = Jsoup.parse("login.html", "ISO-8859-1"); // wrong
Document htmlFile = null;
try {
htmlFile = Jsoup.parse(new File("login.html"), "ISO-8859-1");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // right
title = htmlFile.title();
Element div = htmlFile.getElementById("login");
String cssClass = div.className(); // getting class form HTML element

System.out.println("Jsoup can also parse HTML file directly");
System.out.println("title : " + title);
System.out.println("class of div tag : " + cssClass);
}

}

輸出:

Input HTML String to JSoup :<!DOCTYPE html><html><head><title>JSoup Example</title></head><body><table><tr><td><h1>HelloWorld</h1></tr></table></body></html>

After parsing, Title : JSoup Example
Afte parsing, Heading : HelloWorld
Jsoup Can read HTML page from URL, title : Google
Jsoup can also parse HTML file directly title : Login Page
class of div tag : simple

Jsoup的好處就是它的健壯性很強。Jsoup HTML解析器會對你提供的HTML進行盡量干凈的解析,而不去考慮這個HTML是否是格式良好的。它可以處理如下這些錯誤:未閉合的標簽(比如,Java <p>Scala to <p>JavaScala),隱式標簽(比如,一個裸的|Java is Great被封裝到了|裡面),它總能創建出一個文檔結構(包含head及body的HTML,並且head里只會包含正確的元素)。這就是在Java中如何進行HTML的解析。Jsoup是一個優秀的健壯的開源庫,它使得讀取HTML文檔,body片段,HTML字元串,以及直接從WEB中解析HTML內容都變得相當簡單。在這篇文章中,我們學習了如何在Java中獲取一個特定的HTML標簽,正如第一個例子中我們將title及H1標簽的值提取成了文本,而第三個例子中我們學習到了如何通過提取CSS屬性來從HTML標簽中獲取屬性值。除了強大的jQuery風格的html.body().getElementsByTag("h1").text()方法,你還可以提取任意的HTML標簽,它還提供了像Document.title()和Element.className()這樣便捷的方法,你可以快速獲取到標題及CSS類。希望JSoup能讓你玩得愉快,很快我們將會看到關於這個API的更多的一些例子。

㈡ 想用nodesjs做後台獲取 java後台介面參數,這樣可行嗎

用nodesjs做後台獲取 java後台介面參數,這是可以的。把java所以數據操作做成介面,讓nodejs調用!

㈢ Java一個組織樹里邊增加一個節點,然後把另一個節點下面的數據放在新創建的這個節點里。如何實現

</script>
<!--表格樹js-->
<script>
$(function(){

varsetting={

view:{showLine:true,showIcon:false},//有沒有連線和顯不示顯示圖標
//下面語句可以讓pid相同的分層
data:{
simpleData:{
enable:true//自動成聖樹結構
}
},
callback:{
onClick:zTreeOnClick//回調點擊函數
}

};

//動態獲取數據自動生成樹
$.ajax({
type:"post",
url:"../tools/admin_ajax.ashx?action=GetCallContent&time="+Math.random(),//鏈接地址
dataType:"html",
success:function(data){
//轉換一下json
varmyNodes=JSON.parse(data);
varzNodes=[];

//alert(myNodes);
for(vari=0;i<myNodes.length;i++){//判斷
if(myNodes[i].open!=null){
if(myNodes[i].checked!=null&&myNodes[i].checked)
zNodes[i]={id:myNodes[i].id,pId:myNodes[i].pId,name:myNodes[i].name,answer:myNodes[i].answer,open:true,checked:true};
else
zNodes[i]={id:myNodes[i].id,pId:myNodes[i].pId,name:myNodes[i].name,answer:myNodes[i].answer,open:true};
}
else{
if(myNodes[i].checked!=null&&myNodes[i].checked)
zNodes[i]={id:myNodes[i].id,pId:myNodes[i].pId,name:myNodes[i].name,answer:myNodes[i].answer,checked:true};
else
zNodes[i]={id:myNodes[i].id,pId:myNodes[i].pId,name:myNodes[i].name,answer:myNodes[i].answer,};

}
}
$.fn.zTree.init($("#demoZtree"),setting,zNodes);//初始化樹
$.fn.zTree.getZTreeObj("#demoZtree");//把得到的樹賦給div
}


});

//動態生成樹的ztree子節點點擊事件
functionzTreeOnClick(event,treeId,treeNode){
//alert(treeNode.tId+","+treeNode.name);
$("#eventProblemDesc1").html(treeNode.name);//把標題賦值給div

//插入節點到右邊的框內$("#tab_content_ztree_explain").html(treeNode.name+':');
$.ajax({
type:"get",
url:"../tools/admin_ajax.ashx?action=GetCallContent&time="+Math.random(),
dataType:"html",
success:function(data){
//轉換一下
varmyNodes=JSON.parse(data);
varzNodes=[];
//利用Selected獲取zTree當前被選中的節點數據集合
vartreeObj=$.fn.zTree.getZTreeObj("demoZtree");
varnodes=treeObj.getSelectedNodes();

//console.log(nodes);
for(vari=0;i<myNodes.length;i++){
varitem=myNodes[i];
if(item.id==nodes[0].id){//<spanstyle="font-family:Arial,Helvetica,sans-serif;">判斷樹節點與點擊的節點對應的id是否相等</span>

//alert(item);
varcont='';
cont+=item.answer;
$('#tab_content_ztree_explain').html(cont);//賦值給div


//$('treeNode.name').html(answ);

}
}
}


});
};


});

</script>

㈣ 請問這個樹狀圖在Java中應該怎麼做

打個比方

可以寫一個Tree的類
public class Tree extends BaseDomain {

private String id;

private String key;

private String icon;

private String title;

private String value;

private String text;

private String code;


private String mtype;

private String type;

/**
* 部門的特殊個別欄位
* 1.部門 / 2.崗位 的編碼
*/
private String number;

private Double order;
private Double sort;

private String href;

private String component;

private List<Tree<T>> children;

private String parentId;

private boolean hasParent = false;

private boolean hasChildren = false;

private Date createTime;

private Date modifyTime;

public void initChildren(){
this.children = new ArrayList<>();
}

}
在寫一個工具類
public class TreeUtil {

protected TreeUtil() {

}

private final static String TOP_NODE_ID = "0";

/**
* 用於構建菜單
*
* @param nodes nodes
* @param <T> <T>
* @return <T> Tree<T>
*/
public static <T> Tree<T> build(List<Tree<T>> nodes) {
if (nodes == null) {
return null;
}
List<Tree<T>> topNodes = new ArrayList<>();
nodes.forEach(node -> {
String pid = node.getParentId();
if (pid == null || TOP_NODE_ID.equals(pid)) {
topNodes.add(node);
return;
}
for (Tree<T> n : nodes) {
String id = n.getId();
if (id != null && id.equals(pid)) {
if (n.getChildren() == null)
n.initChildren();
n.getChildren().add(node);
node.setHasParent(true);
n.setHasChildren(true);
n.setHasParent(true);
return;
}
}
if (topNodes.isEmpty())
topNodes.add(node);
});


Tree<T> root = new Tree<>();
root.setId("0");
root.setParentId("");
root.setHasParent(false);
root.setHasChildren(true);
root.setChildren(topNodes);
root.setText("root");
return root;
}

}
寫完了這兩個在寫業務層
一個構建書的方法
private void buildTrees(List> trees, List menus, List ids) {
menus.forEach(menu -> {
ids.add(menu.getId().toString());
Tree tree = new Tree<>();
tree.setId(menu.getId().toString());
tree.setKey(tree.getId());
tree.setParentId(menu.getParentId().toString());
tree.setText(menu.getName());
tree.setTitle(tree.getText());
tree.setIcon(menu.getIcon());
tree.setComponent(menu.getComponent());
tree.setCreateTime(menu.getCreateTime());
tree.setCreateTime(menu.getCreateTime());
tree.setHref(menu.getHref());
tree.setSort(menu.getSort());
tree.setCode(menu.getCode());
tree.setMtype(menu.getMtype());
trees.add(tree);
});
}

Map<String, Object> result = new HashMap<>();
List<Dept> depts = findDepts(dept, request);
List<Tree<Dept>> trees = new ArrayList<>();
buildTrees(trees, depts);
Tree<Dept> deptTree = TreeUtil.build(trees);

result.put("rows", deptTree);
result.put("total", depts.size());

㈤ 請問誰能看明白這段代碼 java的

這個方法的作用是檢查由所有Nodes構成的圖是否存在環。m_nNodes定義了結點數,m_bits應該是定義了結點間的連接關系。
三個for循環,第一個是遍歷所有結點,第二個是根據當前遍歷的結點,遍歷所有其他結點,找出兩個結點間的關系。第三個是判斷是否存在環。
但是我感覺代碼似乎有邏輯問題。

㈥ java 什麼是單向鏈表 和 雙向鏈表

鏈表是類似一種數據結構的東西,就是分別存放有地址以及數據單項鏈表一般是上一個存放地址的地方存放下一個節點的地址,而雙向的就是有兩個存放地址的地方,分別存上一個以及下一個的地址。大概是這樣子

㈦ JAVA point類和鏈表的問題

練習了一下,我機子上的JRE 是特別的。。。所以可能有些問題。。。共同進步啊。。。有優化的也提出來。。。
兩個類

Node.java===========================================

package nodeLink;

public class Node {

public int x = 0 ;
public int y = 0;
public Node next = null;

public int getDistance()
{
int distance = 0;
distance = (int)java.lang.Math.sqrt(this.x * this.x + this.y * this.y);
return distance;
}

public Node()
{
//
}

public Node( int x , int y)
{
this.x = x;
this.y = y;
}

}

NodeLink.java==============================================
package nodeLink;

import java.util.Random;

public class NodeLink {

Node nodes[] = null;

public NodeLink(Node[] nodes)
{
this.nodes = nodes;
}

public NodeLink()
{

}

public Node[] Reverse()
{
Node nodesRev[] = null;

nodesRev = new Node[this.nodes.length];

for(int i=0;i<this.nodes.length ; i++)
{
nodesRev[this.nodes.length -i -1 ]= this.nodes[i];
if(i>=1)
nodesRev[this.nodes.length -i-1 ].next = this.nodes[i-1];
}

return nodesRev;
}

public Node[] Sort()
{
Node nodesSort[] = null;
Node nodeTemp = null;

//init nodesSort
nodesSort = new Node[this.nodes.length];

for(int i = 0;i<this.nodes.length ;i++)
nodesSort[i]= this.nodes[i];

for(int i=0;i<nodesSort.length-1;i++)
{
for (int j=i+1;j<nodesSort.length;j++)
{
if(nodesSort[i].getDistance() > nodesSort[j].getDistance())
{
nodeTemp = nodesSort[i];
nodesSort[i]=nodesSort[j];
nodesSort[j]=nodeTemp;
}
}
}

for(int i = 0;i<nodesSort.length;i++)
{

if (i < nodesSort.length -1)
nodesSort[i].next = nodesSort[i+1];
}

return nodesSort;
}

public void print()
{
for(int i = 0;i<this.nodes.length;i++)
{

System.out.println( Integer.toString(i) + " "
+ this.nodes[i].x + " "
+ this.nodes[i].y + " "
+ this.nodes[i].getDistance());
}
}

public static void printLink( Node[] nodes)
{
for(int i = 0;i< nodes.length;i++)
{

System.out.println( Integer.toString(i) + " "
+ nodes[i].x + " "
+ nodes[i].y + " "
+ nodes[i].getDistance());
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("test NodeLink");

//利用隨機函數定義10對(x,y)值,由此創建的Point類實例存入一個數組中
Node nodeArray[] = new Node[10];
Node nodeTemp = null;
Random r = new Random();
int x = 0;
int y = 0;

for(int i=0;i<nodeArray.length;i++)
{
x = r.nextInt(100);
if( x < 50) x = x + 50;

y = r.nextInt(100);
if( y < 50) y = y + 50;

nodeArray[i]= new Node(x , y);

}

System.out.println("Original List");
NodeLink.printLink(nodeArray);

Node nodesRev[] = null;
Node nodesSort[] = null;

NodeLink nodeLink = new NodeLink(nodeArray);

//按與原點(0,0)的距離由小到大的順序輸出所有的點及到原點的距離
System.out.println("Sort it");
nodesSort = nodeLink.Sort();
NodeLink.printLink(nodesSort);

//編程實現根據一個已存在的鏈表創建一個倒序鏈表。

System.out.println("Reverse it");
nodesRev = nodeLink.Reverse();
NodeLink.printLink(nodesRev);

}

}

㈧ 簡單的JAVA多叉樹問題實現

TreeNode.java
/*
*CopyrightWalkerStudio
*AllRightsReserved.
*
*文件名稱:TreeNode.java
*摘要:
*作者:Walker
*創建時間:2013-03-19
*/
packagecom.walker.commons.data.model;

/**
*樹節點
*
*@authorWalker
*@version1.0.0.0
*/
publicclassTreeNode
{
/**節點Id*/
privateStringnodeId;
/**父節點Id*/
privateStringparentId;
/**文本內容*/
privateStringtext;

/**
*構造函數
*
*@paramnodeId節點Id
*/
publicTreeNode(StringnodeId)
{
this.nodeId=nodeId;
}

/**
*構造函數
*
*@paramnodeId節點Id
*@paramparentId父節點Id
*/
publicTreeNode(StringnodeId,StringparentId)
{
this.nodeId=nodeId;
this.parentId=parentId;
}

publicStringgetNodeId(){
returnnodeId;
}

publicvoidsetNodeId(StringnodeId){
this.nodeId=nodeId;
}

publicStringgetParentId(){
returnparentId;
}

publicvoidsetParentId(StringparentId){
this.parentId=parentId;
}

publicStringgetText(){
returntext;
}

publicvoidsetText(Stringtext){
this.text=text;
}

}


ManyTreeNode.java

/*
*CopyrightWalkerStudio
*AllRightsReserved.
*
*文件名稱:ManyTreeNode.java
*摘要:
*作者:Walker
*創建時間:2013-03-19
*/
packagecom.walker.commons.data.model;

importjava.util.ArrayList;
importjava.util.List;

/**
*多叉樹節點
*
*@authorWalker
*@verion1.0.0.0
*/
publicclassManyTreeNode
{
/**樹節點*/
privateTreeNodedata;
/**子樹集合*/
privateList<ManyTreeNode>childList;

/**
*構造函數
*
*@paramdata樹節點
*/
publicManyTreeNode(TreeNodedata)
{
this.data=data;
this.childList=newArrayList<ManyTreeNode>();
}

/**
*構造函數
*
*@paramdata樹節點
*@paramchildList子樹集合
*/
publicManyTreeNode(TreeNodedata,List<ManyTreeNode>childList)
{
this.data=data;
this.childList=childList;
}

publicTreeNodegetData(){
returndata;
}

publicvoidsetData(TreeNodedata){
this.data=data;
}

publicList<ManyTreeNode>getChildList(){
returnchildList;
}

publicvoidsetChildList(List<ManyTreeNode>childList){
this.childList=childList;
}

}


ManyNodeTree.java

/*
*CopyrightWalkerStudio
*AllRightsReserved.
*
*文件名稱:ManyNodeTree.java
*摘要:
*作者:Walker
*創建時間:2013-03-19
*/
packagecom.walker.commons.data.model;

importjava.util.ArrayList;
importjava.util.List;

/**
*多叉樹生成、遍歷工具
*
*@authorWalker
*@version1.0.0.0
*/
publicclassManyNodeTree
{
/**樹根*/
privateManyTreeNoderoot;

/**
*構造函數
*/
publicManyNodeTree()
{
root=newManyTreeNode(newTreeNode("root"));
}

/**
*生成一顆多叉樹,根節點為root
*
*@paramtreeNodes生成多叉樹的節點集合
*@returnManyNodeTree
*/
publicManyNodeTreecreateTree(List<TreeNode>treeNodes)
{
if(treeNodes==null||treeNodes.size()<0)
returnnull;

ManyNodeTreemanyNodeTree=newManyNodeTree();

//將所有節點添加到多叉樹中
for(TreeNodetreeNode:treeNodes)
{
if(treeNode.getParentId().equals("root"))
{
//向根添加一個節點
manyNodeTree.getRoot().getChildList().add(newManyTreeNode(treeNode));
}
else
{
addChild(manyNodeTree.getRoot(),treeNode);
}
}

returnmanyNodeTree;
}

/**
*向指定多叉樹節點添加子節點
*
*@parammanyTreeNode多叉樹節點
*@paramchild節點
*/
publicvoidaddChild(ManyTreeNodemanyTreeNode,TreeNodechild)
{
for(ManyTreeNodeitem:manyTreeNode.getChildList())
{
if(item.getData().getNodeId().equals(child.getParentId()))
{
//找到對應的父親
item.getChildList().add(newManyTreeNode(child));
break;
}
else
{
if(item.getChildList()!=null&&item.getChildList().size()>0)
{
addChild(item,child);
}
}
}
}

/**
*遍歷多叉樹
*
*@parammanyTreeNode多叉樹節點
*@return
*/
publicStringiteratorTree(ManyTreeNodemanyTreeNode)
{
StringBuilderbuffer=newStringBuilder();
buffer.append(" ");

if(manyTreeNode!=null)
{
for(ManyTreeNodeindex:manyTreeNode.getChildList())
{
buffer.append(index.getData().getNodeId()+",");

if(index.getChildList()!=null&&index.getChildList().size()>0)
{
buffer.append(iteratorTree(index));
}
}
}

buffer.append(" ");

returnbuffer.toString();
}

publicManyTreeNodegetRoot(){
returnroot;
}

publicvoidsetRoot(ManyTreeNoderoot){
this.root=root;
}

publicstaticvoidmain(String[]args)
{
List<TreeNode>treeNodes=newArrayList<TreeNode>();
treeNodes.add(newTreeNode("系統許可權管理","root"));
treeNodes.add(newTreeNode("用戶管理","系統許可權管理"));
treeNodes.add(newTreeNode("角色管理","系統許可權管理"));
treeNodes.add(newTreeNode("組管理","系統許可權管理"));
treeNodes.add(newTreeNode("用戶菜單管理","系統許可權管理"));
treeNodes.add(newTreeNode("角色菜單管理","系統許可權管理"));
treeNodes.add(newTreeNode("用戶許可權管理","系統許可權管理"));
treeNodes.add(newTreeNode("站內信","root"));
treeNodes.add(newTreeNode("寫信","站內信"));
treeNodes.add(newTreeNode("收信","站內信"));
treeNodes.add(newTreeNode("草稿","站內信"));

ManyNodeTreetree=newManyNodeTree();

System.out.println(tree.iteratorTree(tree.createTree(treeNodes).getRoot()));
}

}

㈨ java貪吃蛇代碼注釋求解

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
public class InterFace extends JFrame {
/**
* WIDTH:寬
* HEIGHT:高
* SLEEPTIME:可以看作蛇運動的速度
* L = 1,R = 2, U = 3, D = 4 左右上下代碼
*/
public static final int WIDTH = 800, HEIGHT = 600, SLEEPTIME = 200, L = 1,R = 2, U = 3, D = 4;
BufferedImage offersetImage= new BufferedImage(WIDTH, HEIGHT,BufferedImage.TYPE_3BYTE_BGR);;
Rectangle rect = new Rectangle(20, 40, 15 * 50, 15 * 35);
Snake snake;
Node node;
public InterFace() {
//創建"蛇"對象
snake = new Snake(this);
//創建"食物"對象
createNode();
this.setBounds(100, 100, WIDTH, HEIGHT);
//添加鍵盤監聽器
this.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent arg0) {
System.out.println(arg0.getKeyCode());
switch (arg0.getKeyCode()) {
//映射上下左右4個鍵位
case KeyEvent.VK_LEFT:
snake.dir = L;
break;
case KeyEvent.VK_RIGHT:
snake.dir = R;
break;
case KeyEvent.VK_UP:
snake.dir = U;
break;
case KeyEvent.VK_DOWN:
snake.dir = D;
}
}
});
this.setTitle("貪吃蛇 0.1 By : Easy");
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setVisible(true);
//啟動線程,開始執行
new Thread(new ThreadUpadte()).start();
}
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D) offersetImage.getGraphics();
g2d.setColor(Color.white);
g2d.fillRect(0, 0, WIDTH, HEIGHT);
g2d.setColor(Color.black);
g2d.drawRect(rect.x, rect.y, rect.width, rect.height);
//如果蛇碰撞(吃)到食物,則創建新食物
if (snake.hit(node)) {
createNode();
}
snake.draw(g2d);
node.draw(g2d);
g.drawImage(offersetImage, 0, 0, null);
}
class ThreadUpadte implements Runnable {
public void run() {
//無限重繪畫面
while (true) {
try {
Thread.sleep(SLEEPTIME);
repaint(); //
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
/**
* 創建食物
*/
public void createNode() {
//隨機食物的出現位置
int x = (int) (Math.random() * 650) + 50,y = (int) (Math.random() * 500) + 50;
Color color = Color.blue;
node = new Node(x, y, color);
}
public static void main(String args[]) {
new InterFace();
}
}
/**
* 節點類(包括食物和蛇的身軀組成節點)
*/
class Node {
int x, y, width = 15, height = 15;
Color color;
public Node(int x, int y, Color color) {
this(x, y);
this.color = color;
}
public Node(int x, int y) {
this.x = x;
this.y = y;
this.color = color.black;
}
public void draw(Graphics2D g2d) {
g2d.setColor(color);
g2d.drawRect(x, y, width, height);
}
public Rectangle getRect() {
return new Rectangle(x, y, width, height);
}
}
/**
* 蛇
*/
class Snake {
public List<Node> nodes = new ArrayList<Node>();
InterFace interFace;
int dir=InterFace.R;
public Snake(InterFace interFace) {
this.interFace = interFace;
nodes.add(new Node(20 + 150, 40 + 150));
addNode();
}
/**
* 是否碰撞到食物
* @return true 是 false 否
*/
public boolean hit(Node node) {
//遍歷整個蛇體是否與食物碰撞
for (int i = 0; i < nodes.size(); i++) {
if (nodes.get(i).getRect().intersects(node.getRect())) {
addNode();
return true;
}
}
return false;
}
public void draw(Graphics2D g2d) {
for (int i = 0; i < nodes.size(); i++) {
nodes.get(i).draw(g2d);
}
move();
}
public void move() {
nodes.remove((nodes.size() - 1));
addNode();
}
public synchronized void addNode() {
Node nodeTempNode = nodes.get(0);
//如果方向
switch (dir) {
case InterFace.L:
//判斷是否會撞牆
if (nodeTempNode.x <= 20) {
nodeTempNode = new Node(20 + 15 * 50, nodeTempNode.y);
}
nodes.add(0, new Node(nodeTempNode.x - nodeTempNode.width,
nodeTempNode.y));
break;
case InterFace.R:
//判斷是否會撞牆
if (nodeTempNode.x >= 20 + 15 * 50 - nodeTempNode.width) {
nodeTempNode = new Node(20 - nodeTempNode.width, nodeTempNode.y);
}
nodes.add(0, new Node(nodeTempNode.x + nodeTempNode.width,
nodeTempNode.y));
break;
case InterFace.U:
//判斷是否會撞牆
if (nodeTempNode.y <= 40) {
nodeTempNode = new Node(nodeTempNode.x, 40 + 15 * 35);
}
nodes.add(0, new Node(nodeTempNode.x, nodeTempNode.y - nodeTempNode.height));
break;
case InterFace.D:
//判斷是否會撞牆
if (nodeTempNode.y >= 40 + 15 * 35 - nodeTempNode.height) {
nodeTempNode = new Node(nodeTempNode.x,40 - nodeTempNode.height);
}
nodes.add(0, new Node(nodeTempNode.x, nodeTempNode.y + nodeTempNode.height));
break;
}
}
}

閱讀全文

與Nodesjava相關的資料

熱點內容
脈脈app干什麼用的 瀏覽:357
拽姐是哪個app 瀏覽:858
雲伺服器刪除了還有嗎 瀏覽:232
macbook可以用單片機嘛 瀏覽:307
南陽php招聘 瀏覽:814
去哪裡找按摩師很漂亮的app 瀏覽:818
86x99用簡便演算法計算 瀏覽:830
php截圖flash 瀏覽:273
卸載聯想app哪個好 瀏覽:720
php文字轉圖片 瀏覽:331
豆客後台怎麼加密碼 瀏覽:574
jpg轉換pdf破解版 瀏覽:978
php基礎書籍推薦 瀏覽:778
伺服器與外網不通如何驗證 瀏覽:352
電子版是不是就是文件夾 瀏覽:51
游戲屬性文件加密 瀏覽:464
如何讓安卓手機桌面圖標下移 瀏覽:530
ubuntuphp5環境搭建 瀏覽:101
賭癮解壓視頻 瀏覽:919
晉城移動dns伺服器地址 瀏覽:296