file_id
int64
1
66.7k
content
stringlengths
14
343k
repo
stringlengths
6
92
path
stringlengths
5
169
66,192
package 剑指Offer.type07_递归和循环; /** * * @author loveincode * @data Dec 12, 2017 5:06:01 PM */ public class Q03_变态跳台阶 { /** * type : 递归和循环 * 一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。 * * 求该青蛙跳上一个n级的台阶总共有多少种跳法。 * */ public int JumpFloorII(int target) { if(target <= 0){ return 0; } if(target == 1){ return 1; } else{ int sum = 1; for(int i = 1; i < target ; i ++){ sum += JumpFloorII(i); } return sum; } //2 return 1<<--target; } }
loveincode/nowcoder
src/java/剑指Offer/type07_递归和循环/Q03_变态跳台阶.java
66,193
// 71. 变态跳台阶 // f(1)=1 f(2)=2 f(3)=4 f(4)=8 // f(n)=2的n-1次方 public class Solution { public int JumpFloorII(int target) { int res = 1; for (int i = 1; i < target; i++) { res *= 2; } return res; } }
linwt/nowcoder-leetcode
剑指Offer_Java_新版/JZ71.java
66,194
/** * [10-III] 变态跳台阶 * * 题目: 一只青蛙一次可以跳上 1 级台阶, 也可以跳上 2 级 ... 它也可以跳上 n 级. 求该青蛙跳上一个 n 级的台阶总共有多少种跳法. * * 思路: 动态规划, f(n) 表示 n 个台阶总共有多少种跳法; * 状态转移方程: f(n) = f(n - 1) + f(n - 2) + ... + f(0) * ==> f(n) = 2 * f(n - 1) * f(n - 1) = f(n - 2) + f(n - 3) + ... + f(0) * */ public class Solution { public int JumpFloorII(int n) { int dp = 1; for (int i = 2; i <= n; i++) { // state transition equation: f(n) = 2 * f(n - 1). dp = 2 * dp; } return dp; } }
A11Might/codingInterview
code/offer103.java
66,195
package web; /** * @program LeetNiu * @description: 变态跳台阶 * @author: mf * @create: 2020/01/09 13:34 */ /** * 一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。求该青蛙跳上一个n级的台阶总共有多少种跳法。 */ public class T9 { public int JumpFloorII(int target) { return 1 << (target - 1); } }
OAmbre/Java-Interview
SwordOffer/src/web/T9.java
66,197
package offer; /** * @author JohnnyJYWu */ public class T09_JumpFloorII { //变态跳台阶 public int JumpFloorII(int target) { if (target == 0 || target == 1) { return 1; } if (target == 2) { return 2; } int sum = 0; for (int i = 0; i < target; i++) {//本次跳0次到跳target-1次 sum += JumpFloorII(i);//对于本次的跳跃又有多少种跳法?递归获取结果 } return sum; } }
JohnnyJYWu/offer-Java
src/offer/T09_JumpFloorII.java
66,198
package com.haibin.calendarviewproject.custom; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.text.TextUtils; import com.haibin.calendarview.Calendar; import com.haibin.calendarview.MonthView; /** * 演示一个变态需求的月视图 * Created by huanghaibin on 2018/2/9. */ public class CustomMonthView extends MonthView { private int mRadius; /** * 自定义魅族标记的文本画笔 */ private Paint mTextPaint = new Paint(); /** * 24节气画笔 */ private Paint mSolarTermTextPaint = new Paint(); /** * 背景圆点 */ private Paint mPointPaint = new Paint(); /** * 今天的背景色 */ private Paint mCurrentDayPaint = new Paint(); /** * 圆点半径 */ private float mPointRadius; private int mPadding; private float mCircleRadius; /** * 自定义魅族标记的圆形背景 */ private Paint mSchemeBasicPaint = new Paint(); private float mSchemeBaseLine; public CustomMonthView(Context context) { super(context); mTextPaint.setTextSize(dipToPx(context, 8)); mTextPaint.setColor(0xffffffff); mTextPaint.setAntiAlias(true); mTextPaint.setFakeBoldText(true); mSolarTermTextPaint.setColor(0xff489dff); mSolarTermTextPaint.setAntiAlias(true); mSolarTermTextPaint.setTextAlign(Paint.Align.CENTER); mSchemeBasicPaint.setAntiAlias(true); mSchemeBasicPaint.setStyle(Paint.Style.FILL); mSchemeBasicPaint.setTextAlign(Paint.Align.CENTER); mSchemeBasicPaint.setFakeBoldText(true); mSchemeBasicPaint.setColor(Color.WHITE); mCurrentDayPaint.setAntiAlias(true); mCurrentDayPaint.setStyle(Paint.Style.FILL); mCurrentDayPaint.setColor(0xFFeaeaea); mPointPaint.setAntiAlias(true); mPointPaint.setStyle(Paint.Style.FILL); mPointPaint.setTextAlign(Paint.Align.CENTER); mPointPaint.setColor(Color.RED); mCircleRadius = dipToPx(getContext(), 7); mPadding = dipToPx(getContext(), 3); mPointRadius = dipToPx(context, 2); Paint.FontMetrics metrics = mSchemeBasicPaint.getFontMetrics(); mSchemeBaseLine = mCircleRadius - metrics.descent + (metrics.bottom - metrics.top) / 2 + dipToPx(getContext(), 1); } @Override protected void onPreviewHook() { mSolarTermTextPaint.setTextSize(mCurMonthLunarTextPaint.getTextSize()); mRadius = Math.min(mItemWidth, mItemHeight) / 11 * 5; } @Override protected boolean onDrawSelected(Canvas canvas, Calendar calendar, int x, int y, boolean hasScheme) { int cx = x + mItemWidth / 2; int cy = y + mItemHeight / 2; canvas.drawCircle(cx, cy, mRadius, mSelectedPaint); return true; } @Override protected void onDrawScheme(Canvas canvas, Calendar calendar, int x, int y) { boolean isSelected = isSelected(calendar); if (isSelected) { mPointPaint.setColor(Color.WHITE); } else { mPointPaint.setColor(Color.GRAY); } canvas.drawCircle(x + mItemWidth / 2, y + mItemHeight - 3 * mPadding, mPointRadius, mPointPaint); } @SuppressWarnings("IntegerDivisionInFloatingPointContext") @Override protected void onDrawText(Canvas canvas, Calendar calendar, int x, int y, boolean hasScheme, boolean isSelected) { int cx = x + mItemWidth / 2; int cy = y + mItemHeight / 2; int top = y - mItemHeight / 6; if (calendar.isCurrentDay() && !isSelected) { canvas.drawCircle(cx, cy, mRadius, mCurrentDayPaint); } if (hasScheme) { canvas.drawCircle(x + mItemWidth - mPadding - mCircleRadius / 2, y + mPadding + mCircleRadius, mCircleRadius, mSchemeBasicPaint); mTextPaint.setColor(calendar.getSchemeColor()); canvas.drawText(calendar.getScheme(), x + mItemWidth - mPadding - mCircleRadius, y + mPadding + mSchemeBaseLine, mTextPaint); } //当然可以换成其它对应的画笔就不麻烦, if (calendar.isWeekend() && calendar.isCurrentMonth()) { mCurMonthTextPaint.setColor(0xFF489dff); mCurMonthLunarTextPaint.setColor(0xFF489dff); mSchemeTextPaint.setColor(0xFF489dff); mSchemeLunarTextPaint.setColor(0xFF489dff); mOtherMonthLunarTextPaint.setColor(0xFF489dff); mOtherMonthTextPaint.setColor(0xFF489dff); } else { mCurMonthTextPaint.setColor(0xff333333); mCurMonthLunarTextPaint.setColor(0xffCFCFCF); mSchemeTextPaint.setColor(0xff333333); mSchemeLunarTextPaint.setColor(0xffCFCFCF); mOtherMonthTextPaint.setColor(0xFFe1e1e1); mOtherMonthLunarTextPaint.setColor(0xFFe1e1e1); } if (isSelected) { canvas.drawText(String.valueOf(calendar.getDay()), cx, mTextBaseLine + top, mSelectTextPaint); canvas.drawText(calendar.getLunar(), cx, mTextBaseLine + y + mItemHeight / 10, mSelectedLunarTextPaint); } else if (hasScheme) { canvas.drawText(String.valueOf(calendar.getDay()), cx, mTextBaseLine + top, calendar.isCurrentMonth() ? mSchemeTextPaint : mOtherMonthTextPaint); canvas.drawText(calendar.getLunar(), cx, mTextBaseLine + y + mItemHeight / 10, !TextUtils.isEmpty(calendar.getSolarTerm()) ? mSolarTermTextPaint : mSchemeLunarTextPaint); } else { canvas.drawText(String.valueOf(calendar.getDay()), cx, mTextBaseLine + top, calendar.isCurrentDay() ? mCurDayTextPaint : calendar.isCurrentMonth() ? mCurMonthTextPaint : mOtherMonthTextPaint); canvas.drawText(calendar.getLunar(), cx, mTextBaseLine + y + mItemHeight / 10, calendar.isCurrentDay() ? mCurDayLunarTextPaint : calendar.isCurrentMonth() ? !TextUtils.isEmpty(calendar.getSolarTerm()) ? mSolarTermTextPaint : mCurMonthLunarTextPaint : mOtherMonthLunarTextPaint); } } /** * dp转px * * @param context context * @param dpValue dp * @return px */ private static int dipToPx(Context context, float dpValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (dpValue * scale + 0.5f); } }
huanghaibin-dev/CalendarView
app/src/main/java/com/haibin/calendarviewproject/custom/CustomMonthView.java
66,199
/** * @Author: WuFan * @Date: 2019/2/26 16:01 */ package offer; import java.util.Arrays; /* * 1. 青蛙跳台阶 * 一只青蛙一次可以跳上 1 级台阶,也可以跳上 2 级。求该青蛙跳上一个 n 级的台阶 总共有多少种跳法。 2. 变态跳台阶 一只青蛙一次可以跳上 1 级台阶,也可以跳上 2 级... 它也可以跳上 n 级。求该青 蛙跳上一个 n 级的台阶总共有多少种跳法。 */ public class Solution10_2 { public int JumpFloor(int n){ if(n <=2){ return n; } int fist = 1, last = 2; for(int i =2;i <= n;i++){ last = fist + last; fist = last - fist; } return last; // // if (n <= 2) // return n; // int pre2 = 1, pre1 = 2; // int result = 1; // for (int i = 2; i < n; i++) { // result = pre2 + pre1; // pre2 = pre1; // pre1 = result; // } // return result; } public int JumpFloorII(int target){ // if(target <=2){ // return target; // } // int number[] = new int[target]; // number[0] = 1; // number[1] = 2; // int number_sum = 3; // for(int i = 2; i<= target-1;i++){ // number[i] = number_sum + 1; // number_sum = number_sum*2 + 1; // } // return number[target-1]; int[] dp = new int[target]; Arrays.fill(dp, 1); for (int i = 1; i < target; i++) for (int j = 0; j < i; j++) dp[i] += dp[j]; return dp[target - 1]; } }
wufans/EverydayAlgorithms
Java/Offer/Solution10_2.java
66,200
/** * JumpFloorII * * 变态跳 * 青蛙可以跳1,2到n层台阶,求上n层有多少种方法 * @author lirongqian * @since 2018/02/14 */ public class JumpFloorII { public int JumpFloorII(int target) { if (target <= 2) { return target; } int[] arr = new int[target + 1]; arr[0] = 1; arr[1] = 1; for (int i = 2; i <= target; i++) { arr[i] = 2 * arr[i - 1]; } return arr[target]; } }
stalary/swordoffer
src/JumpFloorII.java
66,201
package JianZhiOffer_09_变态跳台阶; /** * @Author: sunnyandgood * @Date: 2019/6/17 13:21 * 9、变态跳台阶 * 题目描述: * 一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。求该青蛙跳上一个n级的台阶总共有多少种跳法。 * 解题思路: * 还是类似于斐波那契数列 * f(n) = 2^(n-1) * 0 1 2 4 8 16 32 64 128 256 512 1024 */ public class JumpFloorII { public int JumpFloorII(int target) { if (target < 0){ return -1; } if (target <= 2){ return target; } int res = 0; int pre = 1; int cur = 2; for (int i=3;i<=target;i++){ res = pre + pre + cur; pre = cur; cur = res; } return res; } public static void main(String[] args) { JumpFloorII floor = new JumpFloorII(); for (int i=0;i<=10;i++){ System.out.println(floor.JumpFloorII(i)); } } }
sunnyandgood/StoreRoom
剑指Offer/JianZhiOffer/src/JianZhiOffer_09_变态跳台阶/JumpFloorII.java
66,202
package offer; /** * 变态跳台阶 * * @author lu * */ public class Solution9 { public static void main(String[] args) { // TODO Auto-generated method stub System.out.println(new Solution9().JumpFloorII(4)); } public int JumpFloorII(int target) { int sum = 0; if(target==1){ return 1; } for(int i=1; i<=target-1; i++) { sum += JumpFloorII(i); } return sum+1; } }
lsj9383/public-note
datastructure_algorithm/demo/offer/Solution9.java
66,203
package didi; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Scanner; import java.util.stream.Collectors; public class DD2020011 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in, StandardCharsets.UTF_8); String line = scanner.nextLine(); System.out.println(solve(line)); } private static String solve(String line) { String[] lines = line.split(","); int n = lines.length; int[] nums = new int[n]; for (int i = 0; i < n; i++) { nums[i] = Integer.parseInt(lines[i]); } Arrays.sort(nums); return Arrays.stream(nums).mapToObj(String::valueOf).collect(Collectors.joining("\t")); } } /* DD-2020011. 冒泡排序 https://leetcode.cn/problems/tpjs10/ 给定一个数组,使用冒泡实现排序。 格式: 输入: - 一个数组,元素以逗号分隔。 输出: - 冒泡排序后的结果。 示例: 输入:71,44,21,76,24,1,3,6 输出:1 3 6 21 24 44 71 76 答案的分隔符为 '\t' 多少有点变态。。 */
gdut-yy/leetcode-hub-java
leetcode/leetcode-extends/src/main/java/didi/DD2020011.java
66,204
package ToOfferNew; /* 斐波那契数列 */ public class Title9 { public static void main(String[] args) { System.out.println(Fibonacci(2)); } //非递归 public static int Fibonacci(int n){ int[] result = {0,1}; if(n<2){ return result[n]; } int one = 1; int two = 0; int fibN = 0; for (int i = 2; i <= n; i++) { fibN = one + two; two = one; one = fibN; } return fibN; } //递归,效率不够高,存在很多重复计算 public static int fib(int n){ if(n<=0){ return 0; } if(n==1){ return 1; } return fib(n-1)+fib(n-2); } //青蛙跳台阶,每次跳一个或两个,和斐波那契函数一样的道理。 //递归 public static int JumpFloor(int n){ if(n==1){ return 1; } if(n==2){ return 2; } return JumpFloor(n-1)+JumpFloor(n-2); } //非递归 public static int JumpFloor2(int n){ if(n==1){ return 1; } if(n==2){ return 2; } int x = 1; int y = 2; int z = 0; for (int i = 3; i <= n; i++) { z = x+y; x = y; y = z; } return z; } //变态青蛙跳台阶 //递归 public static int JumpFloorBT(int n){ if(n<1){ return 0; } if(n==1){ return 1; } return 2*JumpFloorBT(n-1); } //非递归 public static int JumpFloorBT2(int n){ if(n<1){ return 0; } if(n==1){ return 1; } int temp = 1; int x = 1; for (int i = 2; i <= n; i++) { temp = 2*x; x = temp; } return temp; } }
zhenshiyiyang/Algorithm
src/ToOfferNew/Title9.java
66,205
/* * Copyright (C) 2019 xuexiangjys([email protected]) * * 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.xuexiang.xuidemo.widget.calendar; import android.content.Context; import android.graphics.BlurMaskFilter; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.text.TextUtils; import android.view.View; import com.haibin.calendarview.Calendar; import com.haibin.calendarview.MonthView; /** * 演示一个变态需求的月视图 * Created by huanghaibin on 2018/2/9. */ public class CustomMonthView extends MonthView { private int mRadius; /** * 自定义魅族标记的文本画笔 */ private Paint mTextPaint = new Paint(); /** * 24节气画笔 */ private Paint mSolarTermTextPaint = new Paint(); /** * 背景圆点 */ private Paint mPointPaint = new Paint(); /** * 今天的背景色 */ private Paint mCurrentDayPaint = new Paint(); /** * 圆点半径 */ private float mPointRadius; private int mPadding; private float mCircleRadius; /** * 自定义魅族标记的圆形背景 */ private Paint mSchemeBasicPaint = new Paint(); private float mSchemeBaseLine; public CustomMonthView(Context context) { super(context); mTextPaint.setTextSize(dipToPx(context, 8)); mTextPaint.setColor(0xffffffff); mTextPaint.setAntiAlias(true); mTextPaint.setFakeBoldText(true); mSolarTermTextPaint.setColor(0xff489dff); mSolarTermTextPaint.setAntiAlias(true); mSolarTermTextPaint.setTextAlign(Paint.Align.CENTER); mSchemeBasicPaint.setAntiAlias(true); mSchemeBasicPaint.setStyle(Paint.Style.FILL); mSchemeBasicPaint.setTextAlign(Paint.Align.CENTER); mSchemeBasicPaint.setFakeBoldText(true); mSchemeBasicPaint.setColor(Color.WHITE); mCurrentDayPaint.setAntiAlias(true); mCurrentDayPaint.setStyle(Paint.Style.FILL); mCurrentDayPaint.setColor(0xFFeaeaea); mPointPaint.setAntiAlias(true); mPointPaint.setStyle(Paint.Style.FILL); mPointPaint.setTextAlign(Paint.Align.CENTER); mPointPaint.setColor(Color.RED); mCircleRadius = dipToPx(getContext(), 7); mPadding = dipToPx(getContext(), 3); mPointRadius = dipToPx(context, 2); Paint.FontMetrics metrics = mSchemeBasicPaint.getFontMetrics(); mSchemeBaseLine = mCircleRadius - metrics.descent + (metrics.bottom - metrics.top) / 2 + dipToPx(getContext(), 1); //兼容硬件加速无效的代码 setLayerType(View.LAYER_TYPE_SOFTWARE, mSelectedPaint); //4.0以上硬件加速会导致无效 mSelectedPaint.setMaskFilter(new BlurMaskFilter(28, BlurMaskFilter.Blur.SOLID)); setLayerType(View.LAYER_TYPE_SOFTWARE, mSchemeBasicPaint); mSchemeBasicPaint.setMaskFilter(new BlurMaskFilter(28, BlurMaskFilter.Blur.SOLID)); } @Override protected void onPreviewHook() { mSolarTermTextPaint.setTextSize(mCurMonthLunarTextPaint.getTextSize()); mRadius = Math.min(mItemWidth, mItemHeight) / 11 * 5; } @Override protected boolean onDrawSelected(Canvas canvas, Calendar calendar, int x, int y, boolean hasScheme) { int cx = x + mItemWidth / 2; int cy = y + mItemHeight / 2; canvas.drawCircle(cx, cy, mRadius, mSelectedPaint); return true; } @Override protected void onDrawScheme(Canvas canvas, Calendar calendar, int x, int y) { boolean isSelected = isSelected(calendar); if (isSelected) { mPointPaint.setColor(Color.WHITE); } else { mPointPaint.setColor(Color.GRAY); } canvas.drawCircle(x + mItemWidth / 2F, y + mItemHeight - 3 * mPadding, mPointRadius, mPointPaint); } @Override protected void onDrawText(Canvas canvas, Calendar calendar, int x, int y, boolean hasScheme, boolean isSelected) { int cx = x + mItemWidth / 2; int cy = y + mItemHeight / 2; int top = y - mItemHeight / 6; if (calendar.isCurrentDay() && !isSelected) { canvas.drawCircle(cx, cy, mRadius, mCurrentDayPaint); } if (hasScheme) { canvas.drawCircle(x + mItemWidth - mPadding - mCircleRadius / 2, y + mPadding + mCircleRadius, mCircleRadius, mSchemeBasicPaint); mTextPaint.setColor(calendar.getSchemeColor()); canvas.drawText(calendar.getScheme(), x + mItemWidth - mPadding - mCircleRadius, y + mPadding + mSchemeBaseLine, mTextPaint); } //当然可以换成其它对应的画笔就不麻烦, if (calendar.isWeekend() && calendar.isCurrentMonth()) { mCurMonthTextPaint.setColor(0xFF489dff); mCurMonthLunarTextPaint.setColor(0xFF489dff); mSchemeTextPaint.setColor(0xFF489dff); mSchemeLunarTextPaint.setColor(0xFF489dff); mOtherMonthLunarTextPaint.setColor(0xFF489dff); mOtherMonthTextPaint.setColor(0xFF489dff); } else { mCurMonthTextPaint.setColor(0xff333333); mCurMonthLunarTextPaint.setColor(0xffCFCFCF); mSchemeTextPaint.setColor(0xff333333); mSchemeLunarTextPaint.setColor(0xffCFCFCF); mOtherMonthTextPaint.setColor(0xFFe1e1e1); mOtherMonthLunarTextPaint.setColor(0xFFe1e1e1); } if (isSelected) { canvas.drawText(String.valueOf(calendar.getDay()), cx, mTextBaseLine + top, mSelectTextPaint); canvas.drawText(calendar.getLunar(), cx, mTextBaseLine + y + mItemHeight / 10F, mSelectedLunarTextPaint); } else if (hasScheme) { canvas.drawText(String.valueOf(calendar.getDay()), cx, mTextBaseLine + top, calendar.isCurrentMonth() ? mSchemeTextPaint : mOtherMonthTextPaint); canvas.drawText(calendar.getLunar(), cx, mTextBaseLine + y + mItemHeight / 10F, !TextUtils.isEmpty(calendar.getSolarTerm()) ? mSolarTermTextPaint : mSchemeLunarTextPaint); } else { canvas.drawText(String.valueOf(calendar.getDay()), cx, mTextBaseLine + top, calendar.isCurrentDay() ? mCurDayTextPaint : calendar.isCurrentMonth() ? mCurMonthTextPaint : mOtherMonthTextPaint); canvas.drawText(calendar.getLunar(), cx, mTextBaseLine + y + mItemHeight / 10F, calendar.isCurrentDay() ? mCurDayLunarTextPaint : calendar.isCurrentMonth() ? !TextUtils.isEmpty(calendar.getSolarTerm()) ? mSolarTermTextPaint : mCurMonthLunarTextPaint : mOtherMonthLunarTextPaint); } } /** * dp转px * * @param context context * @param dpValue dp * @return px */ private static int dipToPx(Context context, float dpValue) { final float scale = context.getResources().getDisplayMetrics().density; return (int) (dpValue * scale + 0.5f); } }
xuexiangjys/XUI
app/src/main/java/com/xuexiang/xuidemo/widget/calendar/CustomMonthView.java
66,206
/* * 剑指offer第9题 变态跳台阶 * 一只青蛙一次可以跳上1级台阶,也可以跳上2级……它也可以跳上n级。 * 求该青蛙跳上一个n级的台阶总共有多少种跳法。 * * 其实,这可能是跳台阶的最简单的一道题了 * 设f(n)为青蛙跳上n级台阶的跳法 * 青蛙可以从0跳n级,1跳n-1级,2跳n-2级,...,n-1跳一级 * 那么,f(n)=f(n-1) + f(n-2) + ..... + f(1) + 1 * 其中的1为直接跳n级,这个递推式可以看出,f(n) = 2 * f(n-1) * 其中f(1)=1, f(2)=2,所以,从n=2的时候就可以应用递推式了 */ public class Solution { public int JumpFloorII(int target) { // 边界 if (target == 0) { return 0; } if (target == 1) { return 1; } int t = 1; int i = 2; for(; i <=target; i++) { t = 2 * t; } return t; } }
jsycdut/leetcode
practice/for-the-offer/09-frog-and-stairs-2.java
66,207
package com.richie.expandable.activity; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.ExpandableListView; import android.widget.SimpleExpandableListAdapter; import android.widget.Toast; import com.richie.expandable.Constant; import com.richie.expandable.R; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 使用 SimpleExpandableListAdapter 实现适配器,虽然参数很变态,但为了学习还是拼了 %>_<% */ public class SimpleExpandActivity extends AppCompatActivity { private static final String TAG = "SimpleExpandActivity"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_expand); ExpandableListView listView = (ExpandableListView) findViewById(R.id.expandable_list); SimpleExpandableListAdapter adapter = new SimpleExpandableListAdapter(this, initGroupData(), R.layout.item_expand_group_normal, new String[]{Constant.BOOK_NAME}, new int[]{R.id.label_group_normal}, initChildData(), R.layout.item_expand_child, new String[]{Constant.FIGURE_NAME}, new int[]{R.id.label_expand_child}); listView.setAdapter(adapter); // 设置分组项的点击监听事件 listView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() { @Override public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) { Log.d(TAG, "onGroupClick: groupPosition:" + groupPosition + ", id:" + id); // 请务必返回 false,否则分组不会展开 return false; } }); // 设置子选项点击监听事件 listView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() { @Override public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) { Toast.makeText(SimpleExpandActivity.this, Constant.FIGURES[groupPosition][childPosition], Toast.LENGTH_SHORT).show(); return true; } }); } // 构建分组项显示的数据 private List<Map<String, String>> initGroupData() { List<Map<String, String>> list = new ArrayList<>(); Map<String, String> map; for (int i = 0; i < Constant.BOOKS.length; i++) { map = new HashMap<>(); map.put(Constant.BOOK_NAME, Constant.BOOKS[i]); list.add(map); } return list; } // 构建子选项显示的数据 private List<List<Map<String, String>>> initChildData() { List<List<Map<String, String>>> list = new ArrayList<>(); List<Map<String, String>> child; Map<String, String> map; int row = Constant.FIGURES.length; int column = Constant.FIGURES[0].length; for (int i = 0; i < row; i++) { child = new ArrayList<>(); for (int j = 0; j < column; j++) { map = new HashMap<>(); map.put(Constant.FIGURE_NAME, Constant.FIGURES[i][j]); child.add(map); } list.add(child); } return list; } }
isuperqiang/ExpandableListViewDemo
app/src/main/java/com/richie/expandable/activity/SimpleExpandActivity.java
66,211
package com.micmiu.es.tutorial; import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchType; import org.elasticsearch.client.Client; import org.elasticsearch.client.Requests; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.indices.IndexAlreadyExistsException; import org.elasticsearch.search.SearchHit; import java.util.Iterator; import java.util.Map; /** * Created * User: <a href="http://micmiu.com">micmiu</a> * Date: 6/5/2015 * Time: 17:33 */ public class IndexTest { private Client client = null; public static void startup(){ } /** * * @throws Exception */ public void createIndex() throws Exception { try { try { // 预定义一个索引 client.admin().indices().prepareCreate("app").execute().actionGet(); // 定义索引字段属性 XContentBuilder mapping = XContentFactory.jsonBuilder().startObject(); mapping = mapping.startObject("title") // 创建索引时使用paoding解析 .field("indexAnalyzer", "paoding") // 搜索时使用paoding解析 .field("searchAnalyzer", "paoding") .field("store", "yes") .endObject(); mapping = mapping.endObject(); PutMappingRequest mappingRequest = Requests.putMappingRequest("app").type("article").source(mapping); client.admin().indices().putMapping(mappingRequest).actionGet(); } catch (IndexAlreadyExistsException e) { System.out.println("索引库已存在"); } // 生成文档 XContentBuilder doc = XContentFactory.jsonBuilder().startObject(); doc = doc.field("title", "java附魔大师"); doc = doc.endObject(); // 创建索引 IndexResponse response = client.prepareIndex("app", "article", "1").setSource(doc).execute().actionGet(); System.out.println(response.getId() + "====" + response.getIndex() + "====" + response.getType()); } catch (Exception e) { e.printStackTrace(); } finally { client.close(); } } public void search() throws Exception { try { QueryBuilder qb = QueryBuilders.termQuery("title", "大师"); SearchResponse scrollResp = client.prepareSearch("app").setSearchType(SearchType.SCAN).setScroll( new TimeValue(60000)).setQuery(qb).setSize(100).execute().actionGet(); while (true) { scrollResp = client.prepareSearchScroll(scrollResp.getScrollId()).setScroll(new TimeValue(600000)).execute().actionGet(); for (SearchHit hit : scrollResp.getHits()) { Map<String, Object> source = hit.getSource(); if (!source.isEmpty()) { for (Iterator<Map.Entry<String, Object>> it = source.entrySet().iterator(); it.hasNext();) { Map.Entry<String, Object> entry = it.next(); System.out.println(entry.getKey() + "=======" + entry.getValue()); } } } if (scrollResp.getHits().getTotalHits() == 0) { break; } } } catch (Exception e) { e.printStackTrace(); } finally { client.close(); } } }
micmiu/bigdata-tutorial
es-tutorial/src/main/java/com/micmiu/es/tutorial/IndexTest.java
66,212
package cn.zhikaizhang.activity; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.preference.PreferenceManager; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnTouchListener; import android.view.Window; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import java.util.List; import cn.zhikaizhang.game.Algorithm; import cn.zhikaizhang.bean.Move; import cn.zhikaizhang.game.Rule; import cn.zhikaizhang.bean.Statistic; import cn.zhikaizhang.reversi.R; import cn.zhikaizhang.game.Constant; import cn.zhikaizhang.widget.MessageDialog; import cn.zhikaizhang.widget.NewGameDialog; import cn.zhikaizhang.game.ReversiView; public class GameActivity extends Activity { private static final byte NULL = Constant.NULL; private static final byte BLACK = Constant.BLACK; private static final byte WHITE = Constant.WHITE; private static final int STATE_PLAYER_MOVE = 0; private static final int STATE_AI_MOVE = 1; private static final int STATE_GAME_OVER = 2; private ReversiView reversiView = null; private LinearLayout playerLayout; private LinearLayout aiLayout; private TextView playerChesses; private TextView aiChesses; private ImageView playerImage; private ImageView aiImage; private TextView nameOfAI; private Button newGame; private Button tip; private byte playerColor; private byte aiColor; private int difficulty; private static final int M = 8; private static final int depth[] = new int[] { 0, 1, 2, 3, 7, 3, 5, 2, 4 }; private byte[][] chessBoard = new byte[M][M]; private int gameState; private static final String MULTIPLY = " × "; private static final String NAME_OF_AI[] = new String[]{"菜鸟", "新手", "入门", "棋手", "棋士", "大师", "宗师", "棋圣"}; private NewGameDialog dialog; private MessageDialog msgDialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.game); reversiView = (ReversiView) findViewById(R.id.reversiView); playerLayout = (LinearLayout) findViewById(R.id.player); aiLayout = (LinearLayout) findViewById(R.id.ai); playerChesses = (TextView) findViewById(R.id.player_chesses); aiChesses = (TextView) findViewById(R.id.aiChesses); playerImage = (ImageView) findViewById(R.id.player_image); aiImage = (ImageView) findViewById(R.id.aiImage); nameOfAI = (TextView) findViewById(R.id.name_of_ai); newGame = (Button) findViewById(R.id.new_game); tip = (Button) findViewById(R.id.tip); Bundle bundle = getIntent().getExtras(); playerColor = bundle.getByte("playerColor"); aiColor = (byte) -playerColor; difficulty = bundle.getInt("difficulty"); nameOfAI.setText(NAME_OF_AI[difficulty - 1]); initialChessboard(); reversiView.setOnTouchListener(new OnTouchListener() { boolean down = false; int downRow; int downCol; @Override public boolean onTouch(View v, MotionEvent event) { if (gameState != STATE_PLAYER_MOVE) { return false; } float x = event.getX(); float y = event.getY(); if (!reversiView.inChessBoard(x, y)) { return false; } int row = reversiView.getRow(y); int col = reversiView.getCol(x); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: down = true; downRow = row; downCol = col; break; case MotionEvent.ACTION_UP: if (down && downRow == row && downCol == col) { down = false; if (!Rule.isLegalMove(chessBoard, new Move(row, col), playerColor)) { return true; } /** * 玩家走步 */ Move move = new Move(row, col); List<Move> moves = Rule.move(chessBoard, move, playerColor); reversiView.move(chessBoard, moves, move, playerColor); aiTurn(); } break; case MotionEvent.ACTION_CANCEL: down = false; break; } return true; } }); newGame.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); byte _playerColor = (byte)preferences.getInt("playerColor", Constant.BLACK); int _difficulty = preferences.getInt("difficulty", 1); dialog = new NewGameDialog(GameActivity.this, _playerColor, _difficulty); dialog.setOnStartNewGameListener(new OnClickListener() { @Override public void onClick(View v) { playerColor = dialog.getPlayerColor(); aiColor = (byte) -playerColor; difficulty = dialog.getDifficulty(); SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); preferences.edit().putInt("playerColor", playerColor).commit(); preferences.edit().putInt("difficulty", difficulty).commit(); nameOfAI.setText(NAME_OF_AI[difficulty - 1]); initialChessboard(); if(playerColor == BLACK){ playerImage.setImageResource(R.drawable.black1); aiImage.setImageResource(R.drawable.white1); playerTurn(); }else{ playerImage.setImageResource(R.drawable.white1); aiImage.setImageResource(R.drawable.black1); aiTurn(); } reversiView.initialChessBoard(); dialog.dismiss(); } }); dialog.show(); } }); tip.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if(gameState != STATE_PLAYER_MOVE){ return; } new ThinkingThread(playerColor).start(); } }); if(playerColor == BLACK){ playerImage.setImageResource(R.drawable.black1); aiImage.setImageResource(R.drawable.white1); playerTurn(); }else{ playerImage.setImageResource(R.drawable.white1); aiImage.setImageResource(R.drawable.black1); aiTurn(); } } private void initialChessboard(){ for (int i = 0; i < M; i++) { for (int j = 0; j < M; j++) { chessBoard[i][j] = NULL; } } chessBoard[3][3] = WHITE; chessBoard[3][4] = BLACK; chessBoard[4][3] = BLACK; chessBoard[4][4] = WHITE; } class ThinkingThread extends Thread { private byte thinkingColor; public ThinkingThread(byte thinkingColor) { this.thinkingColor = thinkingColor; } public void run() { try { sleep(20 * 100); } catch (InterruptedException e) { e.printStackTrace(); } int legalMoves = Rule.getLegalMoves(chessBoard, thinkingColor).size(); if (legalMoves > 0) { Move move = Algorithm.getGoodMove(chessBoard, depth[difficulty], thinkingColor, difficulty); List<Move> moves = Rule.move(chessBoard, move, thinkingColor); reversiView.move(chessBoard, moves, move, thinkingColor); } updateUI.handle(0, legalMoves, thinkingColor); } } private UpdateUIHandler updateUI = new UpdateUIHandler(); class UpdateUIHandler extends Handler { @Override public void handleMessage(Message msg) { /** * 更新游戏状态 */ int legalMoves = msg.what; int thinkingColor = msg.arg1; int legalMovesOfAI, legalMovesOfPlayer; if(thinkingColor == aiColor){ legalMovesOfAI = legalMoves; legalMovesOfPlayer = Rule.getLegalMoves(chessBoard, playerColor).size(); Statistic statistic = Rule.analyse(chessBoard, playerColor); if (legalMovesOfAI > 0 && legalMovesOfPlayer > 0) { playerTurn(); } else if (legalMovesOfAI == 0 && legalMovesOfPlayer > 0) { playerTurn(); } else if (legalMovesOfAI == 0 && legalMovesOfPlayer == 0) { gameState = STATE_GAME_OVER; gameOver(statistic.PLAYER - statistic.AI); } else if (legalMovesOfAI > 0 && legalMovesOfPlayer == 0) { aiTurn(); return; } }else{ legalMovesOfPlayer = legalMoves; legalMovesOfAI = Rule.getLegalMoves(chessBoard, aiColor).size(); Statistic statistic = Rule.analyse(chessBoard, playerColor); if (legalMovesOfPlayer > 0 && legalMovesOfAI > 0) { aiTurn(); }else if(legalMovesOfPlayer == 0 && legalMovesOfAI > 0){ aiTurn(); }else if(legalMovesOfPlayer == 0 && legalMovesOfAI == 0){ gameState = STATE_GAME_OVER; gameOver(statistic.PLAYER - statistic.AI); }else if (legalMovesOfPlayer > 0 && legalMovesOfAI == 0) { playerTurn(); } } } public void handle(long delayMillis, int legalMoves, int thinkingColor) { removeMessages(0); sendMessageDelayed(Message.obtain(updateUI, legalMoves, thinkingColor, 0), delayMillis); } }; private void playerTurn(){ Statistic statistic = Rule.analyse(chessBoard, playerColor); playerChesses.setText(MULTIPLY + statistic.PLAYER); aiChesses.setText(MULTIPLY + statistic.AI); playerLayout.setBackgroundResource(R.drawable.rect); aiLayout.setBackgroundResource(R.drawable.rect_normal); gameState = STATE_PLAYER_MOVE; } private void aiTurn(){ Statistic statistic = Rule.analyse(chessBoard, playerColor); playerChesses.setText(MULTIPLY + statistic.PLAYER); aiChesses.setText(MULTIPLY + statistic.AI); playerLayout.setBackgroundResource(R.drawable.rect_normal); aiLayout.setBackgroundResource(R.drawable.rect); gameState = STATE_AI_MOVE; new ThinkingThread(aiColor).start(); } private void gameOver(int winOrLoseOrDraw){ String msg = ""; if(winOrLoseOrDraw > 0){ msg = "你击败了" + NAME_OF_AI[difficulty - 1]; }else if(winOrLoseOrDraw == 0){ msg = "平局"; }else if(winOrLoseOrDraw < 0){ msg = "你被" + NAME_OF_AI[difficulty - 1] + "击败了"; } msgDialog = new MessageDialog(GameActivity.this, msg); msgDialog.show(); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { Intent intent = new Intent(GameActivity.this, MainActivity.class); setResult(RESULT_CANCELED, intent); GameActivity.this.finish(); overridePendingTransition(android.R.anim.fade_in,android.R.anim.fade_out); return true; } return super.onKeyDown(keyCode, event); } }
laserwave/reversi
app/src/main/java/cn/zhikaizhang/activity/GameActivity.java
66,213
package com.fivechess.view; import java.awt.Image; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; import org.apache.log4j.Logger; /** * 人机对战界面 * 初级:电脑水平低级(随机算法) * 中级:电脑水平中级(简单算法) * 高级:电脑水平高级(复杂算法) * 大师:电脑水平大师级(机器学习或深度学习) * @author admin * */ public class ChooseLevel extends JFrame implements MouseListener{ public static final int PRIMARY=1; //初级 public static final int MEDIUM=2; //中级 public static final int SENIOR=3; //高级 public static final int SUPER=4; //大师 public ChooseLevel() { setVisible(true); setLayout(null); //取消原来布局 setBounds(580,185,290,420); setResizable(false); paintBg(); //页面 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); addMouseListener(this); } /** * 添加背景图片 */ private void paintBg() { // TODO Auto-generated method stub ImageIcon image = new ImageIcon("images/level.jpg"); image.setImage(image.getImage().getScaledInstance(290, 420, Image.SCALE_DEFAULT)); JLabel la = new JLabel(image); la.setBounds(0, 0, this.getWidth(), this.getHeight());//添加图片,设置图片大小为窗口的大小。 this.getLayeredPane().add(la, new Integer(Integer.MAX_VALUE)); //将JLabel加入到面板容器的最上层 } /** * 点击页面触发事件 * @param e */ @Override public void mouseClicked(MouseEvent e) { // TODO Auto-generated method stub Logger logger = Logger.getLogger("人机对战菜单"); //获取点击坐标 int x=e.getX(); int y=e.getY(); System.out.println(x+" "+y); if(x>=68 && x<=227 && y>=130 && y<=160) { // 加载初级难度界面 dispose(); logger.info("用户选择电脑水平为初级"); new PCMainBoard(PRIMARY); } else if(x>=68 && x<=227 && y>=185 && y<=226) { //加载中级难度页面 dispose(); logger.info("用户选择电脑水平为中级"); new PCMainBoard(MEDIUM); } else if(x>=68 && x<=227 && y>=250 && y<=293) { //加载高级难度界面 dispose(); logger.info("用户选择电脑水平为高级"); new PCMainBoard(SENIOR); } else if(x>=68 && x<=227 && y>=411 && y<=430) { //加载更高难度界面 dispose(); logger.info("用户选择电脑水平为大师级"); new PCMainBoard(SUPER); } else if(x>=7 && x<=40 && y>=83&& y<=107) { //返回 dispose(); logger.info("用户选择返回主菜单"); new SelectMenu(); } } @Override public void mousePressed(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseReleased(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseEntered(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseExited(MouseEvent e) { // TODO Auto-generated method stub } }
kingdomrushing/FiveChess
src/com/fivechess/view/ChooseLevel.java
66,214
package com.longluo.studyplan.meituan.day2.copypaste; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Scanner; /** * meituan-004. 小团的复制粘贴 * <p> * 小团是一个莫得感情的 CtrlCV 大师,他有一个下标从 1 开始的序列 A 和一个初始全部为 -1 序列 B ,两个序列的长度都是 n 。 * 他会进行若干次操作,每一次操作,他都会选择 A 序列中一段连续区间,将其粘贴到 B 序列中的某一个连续的位置, * 在这个过程中他也会查询 B 序列中某一个位置上的值。 * <p> * 我们用如下的方式表示他的粘贴操作和查询操作: * 粘贴操作:1 k x y,表示把 A 序列中从下标 x 位置开始的连续 k 个元素粘贴到 B 序列中从下标 y 开始的连续 k 个位置上。 * 原始序列中的元素被覆盖。(数据保证不会出现粘贴后 k 个元素超出 B 序列原有长度的情况) * 查询操作:2 x,表示询问B序列下标 x 处的值是多少。 * <p> * 格式: * <p> * 输入: * - 输入第一行包含一个正整数 n ,表示序列 A 和序列 B 的长度。 * - 输入第二行包含 n 个正整数,表示序列 A 中的 n 个元素,第 i 个数字表示下标为 i 的位置上的元素,每一个元素保证在 10^9 以内。 * - 输入第三行是一个操作数 m ,表示进行的操作数量。 * - 接下来 m 行,每行第一个数字为 1 或 2 ,具体操作细节详见题面。 * 输出: * - 对于每一个操作 2 输出一行,每行仅包含一个正整数,表示针对某一个询问的答案。 * <p> * 示例 1: * 输入: * 5 * 1 2 3 4 5 * 5 * 2 1 * 2 5 * 1 2 3 4 * 2 3 * 2 5 * 输出: * -1 * -1 * -1 * 4 * <p> * 示例 2: * 输入: * 5 * 1 2 3 4 5 * 9 * 1 2 3 4 * 2 3 * 2 5 * 1 2 2 3 * 2 1 * 2 2 * 2 3 * 2 4 * 2 5 * 输出: * -1 * 4 * -1 * -1 * 2 * 3 * 4 * <p> * 提示: * 1 <= n <= 2000 * 1 <= m <= 2000 * <p> * https://leetcode-cn.com/problems/TOVGD1/ */ public class Solution { public static void main(String[] args) throws IOException { BufferedReader sc = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(sc.readLine()); int[] arrayA = new int[n]; int[] arrayB = new int[n]; Arrays.fill(arrayA, -1); Arrays.fill(arrayB, -1); String[] nums = sc.readLine().split("\\s+"); for (int i = 0; i < n; i++) { arrayA[i] = Integer.parseInt(nums[i]); } int count = Integer.parseInt(sc.readLine()); List<int[]> operList = new ArrayList<>(); for (int i = 0; i < count; i++) { String[] opts = sc.readLine().split("\\s+"); if (opts[0].equals("1")) { int k = Integer.parseInt(opts[1]); int x = Integer.parseInt(opts[2]); int y = Integer.parseInt(opts[3]); operList.add(new int[]{k, x - 1, y - 1}); } else if (opts[0].equals("2")) { int queryIdx = Integer.parseInt(opts[1]); queryIdx--; for (int j = operList.size() - 1; j >= 0; j--) { int[] op = operList.get(j); if (queryIdx >= op[2] && queryIdx <= op[0] + op[2] - 1) { int offset = queryIdx - op[2]; arrayB[queryIdx] = arrayA[op[1] + offset]; break; } } System.out.println(arrayB[queryIdx]); } } sc.close(); } /* public static void main(String[] args) { sc sc = new sc(System.in); int n = Integer.parseInt(sc.readLine()); int[] arrayA = new int[2 * n]; int[] arrayB = new int[2 * n]; Arrays.fill(arrayB, -1); String numStr = sc.readLine(); String[] numArr = numStr.split("\\s+"); for (int i = 0; i < n; i++) { arrayA[i] = Integer.parseInt(numArr[i]); } int operationNum = Integer.parseInt(sc.readLine()); for (int i = 0; i < operationNum; i++) { String operStr = sc.readLine(); String[] operStrArr = operStr.split("\\s+"); int operation = Integer.parseInt(operStrArr[0]); if (operation == 1) { int k = Integer.parseInt(operStrArr[1]); int x = Integer.parseInt(operStrArr[2]); int y = Integer.parseInt(operStrArr[3]); System.arraycopy(arrayA, x - 1, arrayB, y - 1, k); } else if (operation == 2) { int queryIdx = Integer.parseInt(operStrArr[1]); System.out.println(arrayB[queryIdx - 1]); } } } */ /* public static void main(String[] args) { sc sc = new sc(System.in); int n = Integer.parseInt(sc.readLine()); int[] arrayA = new int[n]; int[] arrayB = new int[n]; Arrays.fill(arrayB, -1); String numStr = sc.readLine(); String[] numArr = numStr.split("\\s+"); for (int i = 0; i < n; i++) { arrayA[i] = Integer.parseInt(numArr[i]); } int operationNum = Integer.parseInt(sc.readLine()); for (int i = 0; i < operationNum; i++) { String operStr = sc.readLine(); String[] operStrArr = operStr.split("\\s+"); int operation = Integer.parseInt(operStrArr[0]); if (operation == 1) { int k = Integer.parseInt(operStrArr[1]); int x = Integer.parseInt(operStrArr[2]); int y = Integer.parseInt(operStrArr[3]); for (int j = 0; j < k; j++) { if (y - 1 + j < n) { arrayB[y - 1 + j] = arrayA[x - 1 + j]; } } } else if (operation == 2) { int queryIdx = Integer.parseInt(operStrArr[1]); System.out.println(arrayB[queryIdx - 1]); } } } */ }
longluo/leetcode
Java/src/com/longluo/studyplan/meituan/day2/copypaste/Solution.java
66,215
package luozhuanghehun; /** * 本命卦合婚 * * @author luozhuang 大师♂罗莊 * modified by liuziying */ public class Luozhuanghehun { enum sex { man, woman; } enum basicstring { 坎, 坤, 震, 巽, 乾, 兑, 艮, 离; } public String hehun(String man, String woman) { if (man.length() != 4 || woman.length() != 4) { return "输入不正确"; } return peihun(getnumber(man, sex.man), getnumber(woman, sex.woman)); } public String peihun(String man, String woman) { return peihun(getnumber(man, sex.man), getnumber(woman, sex.woman)); } private String peihun(int man, int woman) { basicstring mang = basicsnumber(man, sex.man); basicstring womang = basicsnumber(woman, sex.woman); // 乾命男配艮命女 ,艮命男配乾命女; if (mang == basicstring.乾 && womang == basicstring.艮) { return "延年婚"; } if (womang == basicstring.乾 && mang == basicstring.艮) { return "延年婚"; } // 震命男配坎命女,坎命男配震命女; if (mang == basicstring.震 && womang == basicstring.坎) { return "延年婚"; } if (womang == basicstring.震 && mang == basicstring.坎) { return "延年婚"; } // 兑命男配坤命女,坤命男配兑命女; if (mang == basicstring.兑 && womang == basicstring.坤) { return "延年婚"; } if (womang == basicstring.兑 && mang == basicstring.坤) { return "延年婚"; } // 巽命男配离命女,离命男配巽命女; if (mang == basicstring.巽 && womang == basicstring.离) { return "延年婚"; } if (womang == basicstring.巽 && mang == basicstring.离) { return "延年婚"; } // 坎命男配巽命女,巽命男配坎命女; if (mang == basicstring.坎 && womang == basicstring.巽) { return "生气婚"; } if (womang == basicstring.坎 && mang == basicstring.巽) { return "生气婚"; } // 震命男配离命女,离命女配震命男; if (mang == basicstring.震 && womang == basicstring.离) { return "生气婚"; } if (womang == basicstring.震 && mang == basicstring.离) { return "生气婚"; } // 乾命男配兑命女,兑命男配乾命女; if (mang == basicstring.乾 && womang == basicstring.兑) { return "生气婚"; } if (womang == basicstring.乾 && mang == basicstring.兑) { return "生气婚"; } // 艮命男配坤命女,坤命男配艮命女。 if (mang == basicstring.艮 && womang == basicstring.坤) { return "生气婚"; } if (womang == basicstring.艮 && mang == basicstring.坤) { return "生气婚"; } // 坎命男配艮命女,艮命男配坎命女; if (mang == basicstring.艮 && womang == basicstring.坎) { return "天医婚"; } if (womang == basicstring.艮 && mang == basicstring.坎) { return "天医婚"; } // 坤命男配巽命女,巽命男配坤命女; if (mang == basicstring.坤 && womang == basicstring.巽) { return "天医婚"; } if (womang == basicstring.坤 && mang == basicstring.巽) { return "天医婚"; } // 震命男配乾命女,乾命男配震命女; if (mang == basicstring.震 && womang == basicstring.乾) { return "天医婚"; } if (womang == basicstring.震 && mang == basicstring.乾) { return "天医婚"; } // 兑命男配离命女,离命男配兑命女。 if (mang == basicstring.兑 && womang == basicstring.离) { return "天医婚"; } if (womang == basicstring.兑 && mang == basicstring.离) { return "天医婚"; } // 坎命男配乾命女,乾命男配坎命女; if (mang == basicstring.坎 && womang == basicstring.乾) { return "六煞婚"; } if (womang == basicstring.坎 && mang == basicstring.乾) { return "六煞婚"; } // 震命男配艮命女,艮命男配震命女; if (mang == basicstring.震 && womang == basicstring.艮) { return "六煞婚"; } if (womang == basicstring.震 && mang == basicstring.艮) { return "六煞婚"; } // 兑命男配巽命女,巽命男配兑命女; if (mang == basicstring.兑 && womang == basicstring.巽) { return "六煞婚"; } if (womang == basicstring.兑 && mang == basicstring.巽) { return "六煞婚"; } // 离命男配坤命女,坤命男配离命女。 if (mang == basicstring.离 && womang == basicstring.坤) { return "六煞婚"; } if (womang == basicstring.离 && mang == basicstring.坤) { return "六煞婚"; } // 坎命男配离命女,离命男配坎命女; if (mang == basicstring.坎 && womang == basicstring.离) { return "祸害婚"; } if (womang == basicstring.坎 && mang == basicstring.离) { return "祸害婚"; } // 巽命男配震命女,震命男配巽命女; if (mang == basicstring.巽 && womang == basicstring.震) { return "祸害婚"; } if (womang == basicstring.巽 && mang == basicstring.震) { return "祸害婚"; } // 乾命男配坤命女,坤命男配乾命女; if (mang == basicstring.乾 && womang == basicstring.坤) { return "祸害婚"; } if (womang == basicstring.乾 && mang == basicstring.坤) { return "祸害婚"; } // 兑命男配巽命女,巽命男配兑命女; if (mang == basicstring.兑 && womang == basicstring.巽) { return "祸害婚"; } if (womang == basicstring.兑 && mang == basicstring.巽) { return "祸害婚"; } // 坎命男配坎命女,乾命男配乾命女; // // 坤命男配坤命女,兑命男配兑命女; // // 震命男配震命女,艮命男配艮命女; // // 巽命男配巽命女,离命男配离命女。 if (mang == womang) { return "伏位婚"; } // 坎命男配兑命女,兑命男配坎命女; if (mang == basicstring.坎 && womang == basicstring.兑) { return "五鬼婚"; } if (womang == basicstring.坎 && mang == basicstring.兑) { return "五鬼婚"; } // 震命男配坤命女,坤命男配震命女; if (mang == basicstring.震 && womang == basicstring.坤) { return "五鬼婚"; } if (womang == basicstring.震 && mang == basicstring.坤) { return "五鬼婚"; } // 离命男配艮命女,艮命男配离命女; if (mang == basicstring.离 && womang == basicstring.艮) { return "五鬼婚"; } if (womang == basicstring.离 && mang == basicstring.艮) { return "五鬼婚"; } // 乾命男配巽命女,巽命男配乾命女。; if (mang == basicstring.乾 && womang == basicstring.巽) { return "五鬼婚"; } if (womang == basicstring.乾 && mang == basicstring.巽) { return "五鬼婚"; } // 坎命男配坤命女,坤命男配坎命女; if (mang == basicstring.坎 && womang == basicstring.坤) { return "绝命婚"; } if (womang == basicstring.坎 && mang == basicstring.坤) { return "绝命婚"; } // 震命男配兑命女,兑命男配震命女; if (mang == basicstring.震 && womang == basicstring.兑) { return "绝命婚"; } if (womang == basicstring.震 && mang == basicstring.兑) { return "绝命婚"; } // 巽命男配艮命女,艮命男配巽命女; if (mang == basicstring.巽 && womang == basicstring.艮) { return "绝命婚"; } if (womang == basicstring.巽 && mang == basicstring.艮) { return "绝命婚"; } // 乾命男配离命女,离命男配乾命女。 if (mang == basicstring.乾 && womang == basicstring.离) { return "绝命婚"; } if (womang == basicstring.乾 && mang == basicstring.离) { return "绝命婚"; } return "输入不正确"; } private String parseHun(String result){ StringBuffer sb = new StringBuffer(); if(result=="延年婚"){ sb.append("延年婚主长寿有福,男女和谐,积德积庆,终生安康,上吉之配。"); }else if(result=="生气婚"){ sb.append("生气婚主多子多福,儿孙满堂,子孝孙贤,有福有禄,上吉之配。"); }else if(result=="天医婚"){ sb.append("天医婚主无灾无病,一生平安,儿女和睦,无奸无盗,上吉之配。"); }else if(result=="六煞婚"){ sb.append("六煞婚主化险为夷,夫妻和顺,虽富不达,丰衣足食。寻常之配。"); }else if(result=="祸害婚"){ sb.append("祸害婚主遇难可解,逢凶化吉,坎坷劳碌,可保小康,寻常之配。"); }else if(result=="伏位婚"){ sb.append("伏位婚主一生平淡,有子有女,团圆和气,无惊无险,寻常之配。"); }else if(result=="五鬼婚"){ sb.append("五鬼婚主口舌是非,生活不宁,邻里不和,时有官司,次凶之配。"); }else if(result=="绝命婚"){ sb.append("绝命婚主平生坎坷,生世艰辛,东离西走,家遭凶祸,大凶之配。"); } return sb.toString(); } /** * 数字选宫挂 * * @param number 数字 * @param isman 男人么 * @return 属于宫挂 */ public Luozhuanghehun.basicstring basicsnumber(int number, sex isman) { switch (number) { case 1: return basicstring.坎; case 2: return basicstring.坤; case 3: return basicstring.震; case 4: return basicstring.巽; case 5: if (isman == sex.man) { return basicstring.坤; } else { return basicstring.艮; } case 6: return basicstring.乾; case 7: return basicstring.兑; case 8: return basicstring.艮; case 9: return basicstring.离; } return null; } /** * 男性:11-出生年横加(也为流年玄空飞星入中宫计算公式) 女性:4+出生年横加 * 1989年出生的男性:11-(1+9+8+9)=11-(27)=11-(2+7)=2,即本命卦为坤卦 * * @param year 输入年份字符 * @return 重载getnumber */ public int getnumber(String year, sex isman) throws NumberFormatException { int yearnumber = Short.parseShort(year); return getnumber(yearnumber, isman); } /** * 男性:11-出生年横加(也为流年玄空飞星入中宫计算公式) 女性:4+出生年横加 * 1989年出生的男性:11-(1+9+8+9)=11-(27)=11-(2+7)=2,即本命卦为坤卦 * * @param year 输入年份数字 * @return 返回结果 */ public int getnumber(int year, sex isman) { int m = ((int) (year / 1000) % 10); int h = ((int) (year / 100) % 10); int s = ((int) (year / 10) % 10); int g = year % 10; int sum = m + h + g + s; int result; if (isman == sex.man) { result = 11 - ((int) (sum / 10) % 10) - (sum % 10); } else { result = 4 + ((int) (sum / 10) % 10) + (sum % 10); } if (result > 10) { result = result - 9;// 如果超过10,原文没有写怎么做,我自己推的 } return result; } /** * @param args the command line arguments */ public static void main2(String[] args) { Luozhuanghehun my = new Luozhuanghehun(); String result = my.hehun("1980", "1981"); System.out.println(my.getnumber("1980", sex.man)); System.out.println(my.basicsnumber(my.getnumber("1980", sex.man), sex.man)); System.out.println(my.getnumber("1981", sex.woman)); System.out.println(my.basicsnumber(my.getnumber("1981", sex.woman), sex.woman)); System.out.println(result); System.out.println(my.parseHun(result)); } }
lusing/bazi
src/luozhuanghehun/Luozhuanghehun.java
66,216
package com.lahm.library; import android.app.ActivityManager; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.net.LocalServerSocket; import android.text.TextUtils; import android.util.Log; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.BindException; import java.net.ConnectException; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.Random; /** * Project Name:checkMultiApk * Package Name:com.lahm.library * Created by lahm on 2018/5/14 下午4:11 */ public class VirtualApkCheckUtil { private String TAG = "test"; private static volatile VirtualApkCheckUtil singleInstance; private VirtualApkCheckUtil() { } public static VirtualApkCheckUtil getSingleInstance() { if (singleInstance == null) { synchronized (VirtualApkCheckUtil.class) { if (singleInstance == null) { singleInstance = new VirtualApkCheckUtil(); } } } return singleInstance; } /** * 维护一份市面多开应用的包名列表 */ private String[] virtualPkgs = { "com.bly.dkplat",//多开分身本身的包名 // "dkplugin.pke.nnp",//多开分身克隆应用的包名会随机变换 "com.by.chaos",//chaos引擎 "com.lbe.parallel",//平行空间 "com.excelliance.dualaid",//双开助手 "com.lody.virtual",//VirtualXposed,VirtualApp "com.qihoo.magic"//360分身大师 }; /** * 通过检测app私有目录,多开后的应用路径会包含多开软件的包名 * * @param context * @param callback * @return */ public boolean checkByPrivateFilePath(Context context, VirtualCheckCallback callback) { String path = context.getFilesDir().getPath(); for (String virtualPkg : virtualPkgs) { if (path.contains(virtualPkg)) { if (callback != null) callback.findSuspect(); return true; } } return false; } /** * 检测原始的包名,多开应用会hook处理getPackageName方法 * 顺着这个思路,如果在应用列表里出现了同样的包,那么认为该应用被多开了 * * @param context * @param callback * @return */ public boolean checkByOriginApkPackageName(Context context, VirtualCheckCallback callback) { try { if (context == null) throw new IllegalArgumentException("you have to set context first"); int count = 0; String packageName = context.getPackageName(); PackageManager pm = context.getPackageManager(); List<PackageInfo> pkgs = pm.getInstalledPackages(0); for (PackageInfo info : pkgs) { if (packageName.equals(info.packageName)) { count++; } } if (count > 1 && callback != null) callback.findSuspect(); return count > 1; } catch (Exception ignore) { } return false; } /** * 运行被克隆的应用,该应用会加载多开应用的so库 * 检测已经加载的so里是否包含这些应用的包名 * * @param callback * @return */ public boolean checkByMultiApkPackageName(VirtualCheckCallback callback) { BufferedReader bufr = null; try { bufr = new BufferedReader(new FileReader("/proc/self/maps")); String line; while ((line = bufr.readLine()) != null) { for (String pkg : virtualPkgs) { if (line.contains(pkg)) { if (callback != null) callback.findSuspect(); return true; } } } } catch (Exception ignore) { } finally { if (bufr != null) { try { bufr.close(); } catch (IOException e) { } } } return false; } /** * Android系统一个app一个uid * 如果同一uid下有两个进程对应的包名,在"/data/data"下有两个私有目录,则该应用被多开了 * * @param callback * @return */ public boolean checkByHasSameUid(VirtualCheckCallback callback) { String filter = getUidStrFormat(); if (TextUtils.isEmpty(filter)) return false; String result = CommandUtil.getSingleInstance().exec("ps"); if (TextUtils.isEmpty(result)) return false; String[] lines = result.split("\n"); if (lines == null || lines.length <= 0) return false; int exitDirCount = 0; for (int i = 0; i < lines.length; i++) { if (lines[i].contains(filter)) { int pkgStartIndex = lines[i].lastIndexOf(" "); String processName = lines[i].substring(pkgStartIndex <= 0 ? 0 : pkgStartIndex + 1, lines[i].length()); File dataFile = new File(String.format("/data/data/%s", processName, Locale.CHINA)); if (dataFile.exists()) { exitDirCount++; } } } if (exitDirCount > 1 && callback != null) callback.findSuspect(); return exitDirCount > 1; } private String getUidStrFormat() { String filter = CommandUtil.getSingleInstance().exec("cat /proc/self/cgroup"); if (filter == null || filter.length() == 0) { return null; } int uidStartIndex = filter.lastIndexOf("uid"); int uidEndIndex = filter.lastIndexOf("/pid"); if (uidStartIndex < 0) { return null; } if (uidEndIndex <= 0) { uidEndIndex = filter.length(); } filter = filter.substring(uidStartIndex + 4, uidEndIndex); try { String strUid = filter.replaceAll("\n", ""); if (isNumber(strUid)) { int uid = Integer.valueOf(strUid); filter = String.format("u0_a%d", uid - 10000); return filter; } return null; } catch (Exception e) { e.printStackTrace(); return null; } } private boolean isNumber(String str) { if (str == null || str.length() == 0) { return false; } for (int i = 0; i < str.length(); i++) { if (!Character.isDigit(str.charAt(i))) { return false; } } return true; } /** * 端口监听,先扫一遍已开启的端口并连接, * 如果发现能通信且通信信息一致, * 则认为之前有一个相同的自己打开了(也就是被多开了) * 如果没有,则开启监听 * 这个方法没有 checkByCreateLocalServerSocket 方法简单,不推荐使用 * * @param secret * @param callback */ @Deprecated public void checkByPortListening(String secret, VirtualCheckCallback callback) { startClient(secret); new ServerThread(secret, callback).start(); } //此时app作为secret的接收方,也就是server角色 private class ServerThread extends Thread { String secret; VirtualCheckCallback callback; private ServerThread(String secret, VirtualCheckCallback callback) { this.secret = secret; this.callback = callback; } @Override public void run() { super.run(); startServer(secret, callback); } } //找一个没被占用的端口开启监听 //如果监听到有连接,开启读线程 private void startServer(String secret, VirtualCheckCallback callback) { Random random = new Random(); ServerSocket serverSocket = null; try { serverSocket = new ServerSocket(); serverSocket.bind(new InetSocketAddress("127.0.0.1", random.nextInt(55534) + 10000)); while (true) { Socket socket = serverSocket.accept(); ReadThread readThread = new ReadThread(secret, socket, callback); readThread.start(); // serverSocket.close(); } } catch (BindException e) { startServer(secret, callback);//may be loop forever } catch (IOException e) { e.printStackTrace(); } } //读线程读流信息,如果包含secret则认为被广义多开 private class ReadThread extends Thread { private ReadThread(String secret, Socket socket, VirtualCheckCallback callback) { InputStream inputStream = null; try { inputStream = socket.getInputStream(); byte buffer[] = new byte[1024 * 4]; int temp = 0; while ((temp = inputStream.read(buffer)) != -1) { String result = new String(buffer, 0, temp); if (result.contains(secret) && callback != null) callback.findSuspect(); } inputStream.close(); socket.close(); } catch (IOException e) { e.printStackTrace(); } } } //读文件扫描已开启的端口,放入端口列表,每个端口都尝试连接一次 private void startClient(String secret) { String tcp6 = CommandUtil.getSingleInstance().exec("cat /proc/net/tcp6"); if (TextUtils.isEmpty(tcp6)) return; String[] lines = tcp6.split("\n"); ArrayList<Integer> portList = new ArrayList<>(); for (int i = 0, len = lines.length; i < len; i++) { int localHost = lines[i].indexOf("0100007F:");//127.0.0.1: if (localHost < 0) continue; String singlePort = lines[i].substring(localHost + 9, localHost + 13); Integer port = Integer.parseInt(singlePort, 16); portList.add(port); } if (portList.isEmpty()) return; for (int port : portList) { new ClientThread(secret, port).start(); } } //app此时作为secret的发送方(也就是client角色),发送完毕就结束 private class ClientThread extends Thread { String secret; int port; private ClientThread(String secret, int port) { this.secret = secret; this.port = port; } @Override public void run() { super.run(); try { Socket socket = new Socket("127.0.0.1", port); socket.setSoTimeout(2000); OutputStream outputStream = socket.getOutputStream(); outputStream.write((secret + "\n").getBytes("utf-8")); outputStream.flush(); socket.shutdownOutput(); InputStream inputStream = socket.getInputStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); String info = null; while ((info = bufferedReader.readLine()) != null) { Log.i(TAG, "ClientThread: " + info); } bufferedReader.close(); inputStream.close(); socket.close(); } catch (ConnectException e) { Log.i(TAG, port + "port refused"); } catch (SocketException e) { e.printStackTrace(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } /** * 如issue25讨论 * https://github.com/lamster2018/EasyProtector/issues/25 * 感谢https://github.com/wangkunlin提供 * * @param uniqueMsg * @param callback * @return */ private volatile LocalServerSocket localServerSocket; /** * @param uniqueMsg 不要使用固定值,多个马甲包或多进程时会误报。 * 如果是单进程使用,推荐使用context.getPackageName(); * 如果是多进程,推荐使用进程名{@link SecurityCheckUtil#getCurrentProcessName()} * @param callback * @return */ public boolean checkByCreateLocalServerSocket(String uniqueMsg, VirtualCheckCallback callback) { if (localServerSocket != null) return false; try { localServerSocket = new LocalServerSocket(uniqueMsg); return false; } catch (IOException e) { if (callback != null) callback.findSuspect(); return true; } } /** * TopActivity的检查顶层task的思路 * https://github.com/109021017/android-TopActivity * TopActivity作为另一个进程(观察者的角度) * <p> * 能够正确识别多开软件的正确包名,类名 * 这也是为什么能知道使用多开分身app多开后的应用包名是随机的。 * 这里我只是提供调用方法,随时可能删掉。 */ public String checkByTopTask(Context context) { ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); List<ActivityManager.RunningTaskInfo> rtis = am.getRunningTasks(1); return rtis.get(0).topActivity.getPackageName(); } public String checkByTopActivity(Context context) { ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); List<ActivityManager.RunningTaskInfo> rtis = am.getRunningTasks(1); return rtis.get(0).topActivity.getClassName(); } }
lamster2018/EasyProtector
library/src/main/java/com/lahm/library/VirtualApkCheckUtil.java
66,217
package com.x.learning.createName; /** * Date : 2016-05-21 */ /**汉字五行笔画类 * * @author luozhuang 大师♂罗莊 */ public class MetaLibItem { private int bh;//笔画 private String findStr; private int wx_indx;//五行 /** * * @param bh 笔画 * @param wx_indx 五行顺序 * @param findStr //汉字列 */ public MetaLibItem(int bh, int wx_indx, String findStr) { this.bh = bh; this.wx_indx = wx_indx; this.findStr = findStr; } /** * * @return 获得笔画 */ public int getBh() { return this.bh; } /** * 获得汉字列 * * @return */ public String getFindStr() { return this.findStr; } /** * 获得汉字是否存在列表中 * * @return */ public Boolean IfStringexist(String findStr) { if (this.findStr.indexOf(findStr) == -1) { return false; } return true; } /** * 获得汉字是否存在列表中 * * @return */ public Boolean IfStringexist(char findStr) { if (this.findStr.indexOf(findStr) == -1) { return false; } return true; } /** * 获得五行顺序 * * @return */ public int getWx_indx() { return this.wx_indx; } }
blaire101/language
java/javaseBasic/src/main/java/com/x/learning/createName/MetaLibItem.java
66,218
package com.andbase.demo.activity; import java.util.ArrayList; import java.util.List; import android.os.Bundle; import android.widget.ExpandableListView; import com.ab.activity.AbActivity; import com.ab.task.thread.AbTaskPool; import com.ab.view.titlebar.AbTitleBar; import com.andbase.R; import com.andbase.demo.adapter.MyExpandableListAdapter; import com.andbase.global.Constant; import com.andbase.global.MyApplication; import com.andbase.util.download.DownFile; import com.andbase.util.download.DownFileDao; public class DownListActivity extends AbActivity{ private MyApplication application; private DownFileDao mDownFileDao = null; private ArrayList<DownFile> mDownFileList1 = null; private ArrayList<DownFile> mDownFileList2 = null; private ArrayList<ArrayList<DownFile>> mGroupDownFileList = null; private MyExpandableListAdapter mExpandableListAdapter = null; private AbTaskPool mAbTaskPool = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setAbContentView(R.layout.down_list); AbTitleBar mAbTitleBar = this.getTitleBar(); mAbTitleBar.setTitleText(R.string.down_list); mAbTitleBar.setLogo(R.drawable.button_selector_back); mAbTitleBar.setTitleBarBackground(R.drawable.top_bg); mAbTitleBar.setTitleTextMargin(10, 0, 0, 0); mAbTitleBar.setLogoLine(R.drawable.line); application = (MyApplication)abApplication; mDownFileDao = DownFileDao.getInstance(this); mDownFileList1 = new ArrayList<DownFile>(); mDownFileList2 = new ArrayList<DownFile>(); mGroupDownFileList = new ArrayList<ArrayList<DownFile>>(); mGroupDownFileList.add(mDownFileList1); mGroupDownFileList.add(mDownFileList2); mAbTaskPool = AbTaskPool.getInstance(); String[] mDownFileGroupTitle = new String[]{this.getResources().getString(R.string.download_complete_title),this.getResources().getString(R.string.undownLoad_title)}; //创建一个BaseExpandableListAdapter对象 mExpandableListAdapter = new MyExpandableListAdapter(this,mGroupDownFileList,mDownFileGroupTitle); ExpandableListView mExpandListView = (ExpandableListView)findViewById(R.id.mExpandableListView); mExpandListView.setAdapter(mExpandableListAdapter); //Indicator靠右 int width = getWindowManager().getDefaultDisplay().getWidth(); mExpandListView.setIndicatorBounds(width-40, width-25); mExpandListView.setChildIndicatorBounds(5, 53); initDownFileList(); } /** * 初始化所有文件 */ private void initDownFileList() { List<DownFile> mDownFileList = new ArrayList<DownFile>(); DownFile mDownFile1 = new DownFile(); mDownFile1.setName("愤怒的小鸟"); mDownFile1.setDescription("以星球大战电影前传为背景"); mDownFile1.setPakageName(""); mDownFile1.setState(Constant.undownLoad); mDownFile1.setIcon(String.valueOf(R.drawable.default_pic)); mDownFile1.setDownUrl("http://down.apk.hiapk.com/down?aid=1832508&em=13"); mDownFile1.setSuffix(".apk"); mDownFileList.add(mDownFile1); DownFile mDownFile2 = new DownFile(); mDownFile2.setName("节奏大师"); mDownFile2.setPakageName(""); mDownFile2.setDescription("一款老少皆宜的绿色音乐游戏"); mDownFile2.setState(Constant.undownLoad); mDownFile2.setIcon(String.valueOf(R.drawable.default_pic)); mDownFile2.setDownUrl("http://down.mumayi.com/292416/mbaidu"); mDownFile2.setSuffix(".apk"); mDownFileList.add(mDownFile2); DownFile mDownFile3 = new DownFile(); mDownFile3.setName("天天酷跑"); mDownFile3.setPakageName(""); mDownFile3.setDescription("腾讯移动游戏平台首批产品"); mDownFile3.setState(Constant.undownLoad); mDownFile3.setIcon(String.valueOf(R.drawable.default_pic)); mDownFile3.setDownUrl("http://down.mumayi.com/407098/mbaidu"); mDownFile3.setSuffix(".apk"); mDownFileList.add(mDownFile3); //测试 //mDownFileDao.delete("http://down.apk.hiapk.com/down?aid=1832508&em=13"); //mDownFileDao.delete("http://down.mumayi.com/292416/mbaidu"); //mDownFileDao.delete("http://down.mumayi.com/407098/mbaidu"); //初始化文件已经下载的长度,计算已下载的进度 for(DownFile mDownFile:mDownFileList){ //本地数据 DownFile mDownFileT = mDownFileDao.getDownFile(mDownFile.getDownUrl()); if(mDownFileT != null){ mDownFile = mDownFileT; if(mDownFile.getDownLength() == mDownFile.getTotalLength() && mDownFile.getTotalLength()!=0){ mDownFile.setState(Constant.downloadComplete); mDownFileList1.add(mDownFile); mExpandableListAdapter.notifyDataSetChanged(); }else{ //显示为暂停状态 mDownFile.setState(Constant.downLoadPause); mDownFileList2.add(mDownFile); mExpandableListAdapter.notifyDataSetChanged(); } }else{ mDownFile.setState(Constant.undownLoad); mDownFileList2.add(mDownFile); mExpandableListAdapter.notifyDataSetChanged(); } } } @Override public void finish() { super.finish(); //释放所有的下载线程 mExpandableListAdapter.releaseThread(); } }
ym6745476/andbase
AndBaseDemo/src/com/andbase/demo/activity/DownListActivity.java
66,219
package com.king.applib.util; //CHECKSTYLE:OFF import java.util.regex.Matcher; import java.util.regex.Pattern; /** * 校验身份证 * @since 2013年11月14日 下午1:58:18 */ public class UserUtil { private static final int[] weight = new int[]{7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1}; // 校验码 private static final int[] checkDigit = new int[]{1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2}; /** * 检查注册用户名是否符合要求 */ public static boolean checkUserStr(String s) { String str = "[A-Za-z0-9_|\u4e00-\u9fa5]*"; Pattern pattern = Pattern.compile(str); Matcher matcher = pattern.matcher(s); if (!matcher.matches()) { return false; } str = "\\$|\\(|\\)|\\*|\\+|\\-|\\.|\\[|]|\\?|\\|\\^|\\{|\\||}|~|`|!|@|#|%|&|=|<|>|/|,|'| | |\\:|林美眉|林MM|林美湄|大鳄浮头|500158|今夜很冷|余超群|小赌怡情|专家团|大赢家|盈彩畅联|辉煌|dyj|小鹰|无双|大师|投资团|法[  ]*轮[  ]*功"; pattern = Pattern.compile(str); matcher = pattern.matcher(s); return !matcher.matches(); } /** * 验证身份证是否符合格式 */ public static boolean verifyIDCard(String idcard) { if (StringUtil.isNullOrEmpty(idcard) || (idcard.length() != 15 && idcard.length() != 18)) { return false; } if (idcard.length() == 15) { //15 位的身份证不能带X等字母 Pattern pattern = Pattern.compile("[0-9]{1,}"); if (pattern.matcher(idcard).matches()) { idcard = update2eighteen(idcard); } else { return false; } } if (!NumberUtil.isInteger(idcard.substring(0, 17))) { return false; } // 获取输入身份证上的最后一位,它是校验码 // 比较获取的校验码与本方法生成的校验码是否相等 return idcard.substring(17, 18).equalsIgnoreCase(getCheckDigit(idcard)); } /** * 计算18位身份证的校验码 * @param eighteenCardID 18位身份证 */ private static String getCheckDigit(String eighteenCardID) { int remaining = 0; if (eighteenCardID.length() == 18) { eighteenCardID = eighteenCardID.substring(0, 17); } if (eighteenCardID.length() == 17) { int sum = 0; int[] a = new int[17]; // 先对前17位数字的权求和 for (int i = 0; i < 17; i++) { String k = eighteenCardID.substring(i, i + 1); a[i] = Integer.parseInt(k); } for (int i = 0; i < 17; i++) { sum = sum + weight[i] * a[i]; } // 再与11取模 remaining = sum % 11; } return remaining == 2 ? "X" : String.valueOf(checkDigit[remaining]); } /** * 将15位身份证升级成18位身份证号码 */ private static String update2eighteen(String fifteenCardID) { // 15位身份证上的生日中的年份没有19,要加上 String eighteenCardID = fifteenCardID.substring(0, 6) + "19" + fifteenCardID.substring(6, 15); return eighteenCardID + getCheckDigit(eighteenCardID); } } //CHECKSTYLE:ON
hubme/WorkHelperApp
applib/src/main/java/com/king/applib/util/UserUtil.java
66,220
package meituan; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; public class Meituan004 { private static final int N = 40010; public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in, StandardCharsets.UTF_8)); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(System.out, StandardCharsets.UTF_8)); // input String line0 = reader.readLine(); int n = Integer.parseInt(line0); int[] A = new int[N]; int[] B = new int[N]; String[] line1 = reader.readLine().split(" "); for (int i = 1; i <= n; i++) { A[i] = Integer.parseInt(line1[i - 1]); B[i] = -1; } String line2 = reader.readLine(); int m = Integer.parseInt(line2); String[] lines = new String[m]; for (int i = 0; i < m; i++) { lines[i] = reader.readLine(); } // solution int[] res = solution(A, B, lines); // output for (int re : res) { writer.write(String.valueOf(re)); writer.write(System.lineSeparator()); } writer.close(); reader.close(); } private static int[] solution(int[] A, int[] B, String[] lines) { List<Integer> resList = new ArrayList<>(); for (String line : lines) { String[] lineM = line.split(" "); int op = Integer.parseInt(lineM[0]); if (op == 1) { int k = Integer.parseInt(lineM[1]); int x = Integer.parseInt(lineM[2]); int y = Integer.parseInt(lineM[3]); for (int i = x, j = y; i < k + x; i++, j++) { B[j] = A[i]; } } else { int x = Integer.parseInt(lineM[1]); resList.add(B[x]); } } return resList.stream().mapToInt(i -> i).toArray(); } } /* meituan-004. 小团的复制粘贴 https://leetcode.cn/problems/TOVGD1/ 小团是一个莫得感情的 CtrlCV 大师,他有一个下标从 1 开始的序列 A 和一个初始全部为 -1 序列 B ,两个序列的长度都是 n 。 他会进行若干次操作,每一次操作,他都会选择 A 序列中一段连续区间,将其粘贴到 B 序列中的某一个连续的位置, 在这个过程中他也会查询 B 序列中某一个位置上的值。 我们用如下的方式表示他的粘贴操作和查询操作: 粘贴操作:1 k x y,表示把 A 序列中从下标 x 位置开始的连续 k 个元素粘贴到 B 序列中从下标 y 开始的连续 k 个位置上。 原始序列中的元素被覆盖。(注意:输入数据可能会出现粘贴后 k 个元素超出 B 序列原有长度的情况,超出部分可忽略) 查询操作:2 x,表示询问B序列下标 x 处的值是多少。 格式: 输入: - 输入第一行包含一个正整数 n ,表示序列 A 和序列 B 的长度。 - 输入第二行包含 n 个正整数,表示序列 A 中的 n 个元素,第 i 个数字表示下标为 i 的位置上的元素,每一个元素保证在 10^9 以内。 - 输入第三行是一个操作数 m ,表示进行的操作数量。 - 接下来 m 行,每行第一个数字为 1 或 2 ,具体操作细节详见题面。 输出: - 对于每一个操作 2 输出一行,每行仅包含一个正整数,表示针对某一个询问的答案。 示例 1: 输入: 5 1 2 3 4 5 5 2 1 2 5 1 2 3 4 2 3 2 5 输出: -1 -1 -1 4 示例 2: 输入: 5 1 2 3 4 5 9 1 2 3 4 2 3 2 5 1 2 2 3 2 1 2 2 2 3 2 4 2 5 输出: -1 4 -1 -1 2 3 4 提示: 1 <= n <= 20000 1 <= m <= 20000 */
gdut-yy/leetcode-hub-java
leetcode/leetcode-extends/src/main/java/meituan/Meituan004.java
66,221
public class Object01{ public static void main (String[]args) { String name1="黄冰棒"; String name2="黄文强"; int age1=28; int age2=23; String stydy1="不爱学习"; String study2="大师"; //单独变量解决 不利于数据管理,数组解决问题 String[]name3={"黄冰棒","28岁","不爱学习"}; man man1=new man(); man1.name="黄冰棒"; man1.age=28; man1.study="不爱学习"; man man2=new man(); man2.name="黄文强"; man2.age=20; man2.study="爱睡觉"; System.out.println("第一个人的信息"+man1.name+" "+man1.age+" "+man1.study); System.out.println("第二个人的信息"+man2.name+" "+man2.age+" "+man2.study); } }//实例化一个人 //定义1个类型 class man { String name; int age; String study; }
Achilles0622/Achilles
java/Object01.java
66,223
package gapp.season.sudoku; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 数独的一些例子(81个0-9的数字组成的字符串) * 带*表示非唯一解 */ public class Sudokus { private static Sudokus instance; private List<String> mSudokuTips; private List<String> mSudokuKeys; private Map<String, List<String>> mSudokusTipListMap; private Map<String, List<String>> mSudokusValueListMap; private Sudokus() { // 标准数独、X数独、%数独 mSudokuTips = new ArrayList<>(); mSudokuKeys = new ArrayList<>(); mSudokusTipListMap = new HashMap<>(); mSudokusValueListMap = new HashMap<>(); mSudokuTips.add("复制当前数独字符串"); mSudokuKeys.add("copy"); mSudokuTips.add("数独-粘贴板字符串"); mSudokuKeys.add("paste"); mSudokuTips.add("数独-输入字符串"); mSudokuKeys.add("input"); mSudokuTips.add("数独-随机生成数独"); mSudokuKeys.add("generate"); addSudokus_1(); addSudokus_2(); addSudokus_3(); addSudokus_4(); } private void addSudokus_1() { mSudokuTips.add("数独-入门"); String key = "standard_level_simple"; List<String> tipList = new ArrayList<>(); List<String> valueList = new ArrayList<>(); tipList.add("标准数独-入门-1"); valueList.add("369052478850674931714308265683927154597416820021835697138769042240583719905241306"); tipList.add("标准数独-入门-2"); valueList.add("571983460408627915962105387740219036086374529293850741629038154804502673357461208"); tipList.add("标准数独-入门-3"); valueList.add("069084753587019426230607891691470238752831049348962105405196307913728064876543010"); tipList.add("X数独-入门-1"); valueList.add("452379860638140507901806402806503279217904385593280140365020914104695703720431658"); tipList.add("%数独-入门-1"); valueList.add("302486597968507401574192680839200176720613948041879302203964015197350264456721830"); //额外列表 insertSudoku(tipList, valueList, "简单数独-1", "052006000160900004049803620400000800083201590001000002097305240200009056000100970"); insertSudoku(tipList, valueList, "简单数独-2", "052400100100002030000813025400007010683000597070500002890365000010700006006004970"); insertSudoku(tipList, valueList, "简单数独-3", "302000089068052734009000000400007000083201590000500002000000200214780350530000908"); insertSudoku(tipList, valueList, "简单数独-4", "402000007000080420050302006090030050503060708070010060900406030015070000200000809"); insertSudoku(tipList, valueList, "简单数独-5", "060091080109680405050040106600000200023904710004000003907020030305079602040150070"); insertSudoku(tipList, valueList, "简单数独-6", "060090380009080405050300106001008200020904010004200900907006030305070600046050070"); insertSudoku(tipList, valueList, "简单数独-7", "402000380109607400008300106090030004023964710800010060907006500005809602046000809"); insertSudoku(tipList, valueList, "简单数独-8", "400091000009007425058340190691000000003964700000000963087026530315800600000150009"); insertSudoku(tipList, valueList, "简单数独-9", "380001004002600070000487003000040239201000406495060000600854000070006800800700092"); insertSudoku(tipList, valueList, "简单数独-10", "007520060002009008006407000768005009031000450400300781000804300100200800050013600"); insertSudoku(tipList, valueList, "简单数独-11", "380000000540009078000407503000145209000908000405362000609804000170200045000000092"); insertSudoku(tipList, valueList, "简单数独-12", "007001000540609078900487000760100230230000056095002081000854007170206045000700600"); insertSudoku(tipList, valueList, "简单数独-13", "007021900502009078006407500000140039031908450490062000009804300170200805004710600"); insertSudoku(tipList, valueList, "简单数独-14", "086500204407008090350009000009080601010000080608090300000200076030800409105004820"); insertSudoku(tipList, valueList, "简单数独-15", "086507000007360100000000068249003050500000007070100342890000000002056400000904820"); insertSudoku(tipList, valueList, "简单数独-16", "000007230420368000050029768000080650000602000078090000894230070000856019065900000"); insertSudoku(tipList, valueList, "简单数独-17", "906000200400368190350400000209080051013040980670090302000001076032856009005000803"); insertSudoku(tipList, valueList, "简单数独-18", "095002000700804001810076500476000302000000000301000857003290075500307006000400130"); insertSudoku(tipList, valueList, "简单数独-19", "005002740002850901810000500070501302008723600301609050003000075509017200087400100"); insertSudoku(tipList, valueList, "简单数独-20", "605102740732004001000000020400501300008020600001609007060000000500300286087405109"); insertSudoku(tipList, valueList, "简单数独-21", "695102040700800000000970023076000090900020004020000850160098000000007006080405139"); insertSudoku(tipList, valueList, "简单数独-22", "090002748000004901800906500470500090008000600020009057003208005509300000287400030"); insertSudoku(tipList, valueList, "简单数独-23", "001009048089070030003106005390000500058602170007000094900708300030040860870300400"); insertSudoku(tipList, valueList, "简单数独-24", "600039708000004600000100025002017506408000103107850200910008000005900000806320009"); insertSudoku(tipList, valueList, "简单数独-25", "620500700500270631040100005302000086000090000160000204900008050235041007006005019"); insertSudoku(tipList, valueList, "简单数独-26", "080130002140902007273080000000070206007203900502040000000060318600308024400021050"); insertSudoku(tipList, valueList, "简单数独-27", "980100402046950000200684001010009086007000900590800070700465008000098720408001059"); insertSudoku(tipList, valueList, "简单数独-28", "085100400000950007073684001010070080067203940090040070700465310600098000008001650"); insertSudoku(tipList, valueList, "简单数独-29", "085100460146000807070004001300009080067000940090800003700400010601000724038001650"); insertSudoku(tipList, valueList, "简单数独-30", "085130462006000007270680090000009200060213040002800000020065018600000700438021650"); mSudokuKeys.add(key); mSudokusTipListMap.put(key, tipList); mSudokusValueListMap.put(key, valueList); } private void addSudokus_2() { mSudokuTips.add("数独-中等"); String key = "standard_level_medium"; List<String> tipList = new ArrayList<>(); List<String> valueList = new ArrayList<>(); tipList.add("标准数独-中等-1"); valueList.add("509004010600802005040300607004007900060920030900040070050010003090085020001200400"); tipList.add("标准数独-中等-2"); valueList.add("070016090000000000090730060032000007900420103000001009300800000805097001700000580"); tipList.add("标准数独-中等-3"); valueList.add("800400520005901600063007004300040200020300040700092006900510002040009080007080005"); tipList.add("标准数独-中等-4"); valueList.add("026100400507634102001005970000056219000001000000000703309000000000500000165240000"); tipList.add("标准数独-中等-5 *"); valueList.add("006850009002601500500074200300060000020310000840709600009007036000593070000080005"); tipList.add("标准数独-中等-6"); valueList.add("600000002040806030100000007091602700080190200502300000000004305005039020009508170"); tipList.add("标准数独-中等-7"); valueList.add("010500003095000270700001060600050080000009000830600105908005046000700000060030002"); tipList.add("标准数独-中等-8"); valueList.add("030040700690708034001090050300060517000000006060502090010903070900000000853020001"); tipList.add("标准数独-中等-9"); valueList.add("000000076680000054530000000059086000106003000000002409403200000000700503000630840"); tipList.add("标准数独-中等-10"); valueList.add("000000548500000002847000000000025009010089304050000800209000010005810060100790000"); tipList.add("标准数独-中等-11 *"); valueList.add("007000900200507006080104070040010030601000809090080060050809010010603002006000300"); tipList.add("标准数独-中等-12"); valueList.add("070103060050000070300050001500304008407000102900702004200070003030000040060509020"); tipList.add("标准数独-中等-13"); valueList.add("000013400080006950650000000960201000100070002000304016000000079025800040009760000"); tipList.add("标准数独-中等-14"); valueList.add("001090270009002050200003000300014002080000040100280005000900007010300900046070500"); tipList.add("标准数独-中等-15"); valueList.add("000409000080020700020507106300800060760000031010006002205908040009070010000605000"); tipList.add("标准数独-中等-16"); valueList.add("000000945006000000520103807090310000003080100000046020705208019000000300861000000"); tipList.add("标准数独-中等-17"); valueList.add("200700050000048006000002309900600240070020080025001003804900000600480000090003008"); tipList.add("标准数独-中等-18"); valueList.add("065000300200067900040300001006050004000402000700080100600004010008570006001000830"); tipList.add("标准数独-中等-19"); valueList.add("027900000050002084008000207070030006000817000300040020106000800240600010000005640"); tipList.add("标准数独-中等-20"); valueList.add("900278100001030249003000000030800000007000500000004030000000300578040900004516007"); tipList.add("标准数独-中等-21"); valueList.add("006007009800030100900605030003000018000901000210000600060703001009020004700800500"); tipList.add("标准数独-中等-22"); valueList.add("470108029000000000006927100090601030300000004040709080004875300000000000580403097"); tipList.add("标准数独-中等-23"); valueList.add("050801090730000054800030001008302100000000000006704500100050009380000012040608030"); tipList.add("标准数独-中等-24"); valueList.add("653000700000009000804050003900017300005030800007290005400070206000800000006000157"); tipList.add("X数独-中等-1 *"); valueList.add("005100300006803100010007050072030900000080000008040710020400030007300800004008600"); tipList.add("X数独-中等-2 *"); valueList.add("098020050006500008000800900001200760000167000057009100002003000700002500060050270"); tipList.add("X数独-中等-3 *"); valueList.add("057900000020074068000005007082000005040000030900000240200700000870210050000008720"); tipList.add("%数独-中等-1 *"); valueList.add("000895170005000900890043600008609001003578200600104500000950062009000800067381050"); tipList.add("%数独-中等-2"); valueList.add("561739000009080160000100009037600008804010206206008310600094000082050600000261834"); tipList.add("%数独-中等-3 *"); valueList.add("261000940000090730930604050500000010090348070070000009080407021052010000014000863"); //额外列表 insertSudoku(tipList, valueList, "普通数独-1", "916004072800620050500008930060000200000207000005000090097800003080076009450100687"); insertSudoku(tipList, valueList, "普通数独-2", "000900082063001409908000000000670300046050290007023000000000701704300620630007000"); insertSudoku(tipList, valueList, "普通数独-3", "035670000400829500080003060020005807800206005301700020040900070002487006000052490"); insertSudoku(tipList, valueList, "普通数独-4", "030070902470009000009003060024000837007000100351000620040900200000400056708050090"); insertSudoku(tipList, valueList, "普通数独-5", "084200000930840000057000000600401700400070002005602009000000980000028047000003210"); insertSudoku(tipList, valueList, "普通数独-6", "007861000008003000560090010100070085000345000630010007050020098000600500000537100"); insertSudoku(tipList, valueList, "普通数独-7", "040001003000050079560002804100270080082000960030018007306100098470080000800500040"); insertSudoku(tipList, valueList, "普通数独-8", "000500006000870302270300081000034900793050614008790000920003057506087000300005000"); insertSudoku(tipList, valueList, "普通数独-9", "000900067090000208460078000320094070700603002010780043000850016501000090670009000"); insertSudoku(tipList, valueList, "普通数独-10", "024000017000301000300000965201000650000637000093000708539000001000502000840000570"); insertSudoku(tipList, valueList, "普通数独-11", "200006143004000600607008029100800200003090800005003001830500902006000400942600005"); insertSudoku(tipList, valueList, "普通数独-12", "504002030900073008670000020000030780005709200047060000050000014100450009060300502"); insertSudoku(tipList, valueList, "普通数独-13", "580000637000000000603540000090104705010709040807205090000026304000000000468000072"); insertSudoku(tipList, valueList, "普通数独-14", "000010000900003408670500021000130780015000240047065000750006014102400009000090000"); insertSudoku(tipList, valueList, "普通数独-15", "780300050956000000002065001003400570600000003025008100200590800000000417030004025"); insertSudoku(tipList, valueList, "普通数独-16", "200367500500800060300450700090530400080000070003074050001026005030005007002783001"); insertSudoku(tipList, valueList, "普通数独-17", "801056200000002381900003000350470000008000100000068037000600002687100000004530806"); insertSudoku(tipList, valueList, "普通数独-18", "300004005841753060000010000003000087098107540750000100000070000030281796200300008"); insertSudoku(tipList, valueList, "普通数独-19", "000064810040050062009010300003040607008107500704030100006070200430080090017390000"); insertSudoku(tipList, valueList, "普通数独-20", "000040320000357080000600400357006040600705003080900675008009000090581000064070000"); insertSudoku(tipList, valueList, "普通数独-21", "905040026026050900030600050350000009009020800100000075010009030003080760560070108"); insertSudoku(tipList, valueList, "普通数独-22", "010403060030017400200000300070080004092354780500070030003000005008530040050906020"); insertSudoku(tipList, valueList, "普通数独-23", "605900100000100073071300005009010004046293510700040600200001730160002000008009401"); insertSudoku(tipList, valueList, "普通数独-24", "049060002800210490100040000000035084008102300630470000000080001084051006700020950"); insertSudoku(tipList, valueList, "普通数独-25", "067020300003700000920103000402035060300000002010240903000508039000009200008010750"); insertSudoku(tipList, valueList, "普通数独-26", "050842001004000900800050040600400019007506800430009002080090006001000400500681090"); insertSudoku(tipList, valueList, "普通数独-27", "000076189000002030009813000025000010083000590070000460000365200010700000536120000"); insertSudoku(tipList, valueList, "普通数独-28", "080000030400368000350409700000003650003000900078100000004201076000856009060000020"); insertSudoku(tipList, valueList, "普通数独-29", "000500748589000001700086900302010580000000000067050204004760002200000867876005000"); insertSudoku(tipList, valueList, "普通数独-30", "021009008000004031740100025000007086058000170160800000910008052230900000800300410"); mSudokuKeys.add(key); mSudokusTipListMap.put(key, tipList); mSudokusValueListMap.put(key, valueList); } private void addSudokus_3() { mSudokuTips.add("数独-大师"); String key = "standard_level_master"; List<String> tipList = new ArrayList<>(); List<String> valueList = new ArrayList<>(); tipList.add("标准数独-大师-1"); valueList.add("000100260700030000302080400000408001035000940200305000006050709000040008057009000"); tipList.add("标准数独-大师-2"); valueList.add("008090000070000280064100309000805900500000001009304000802007560097000010000060700"); tipList.add("标准数独-大师-3"); valueList.add("000702000100040007650000094470801062000000000580209013860000075900060008000908000"); tipList.add("标准数独-大师-4"); valueList.add("007238000060700050000400002900000867100000003648000005700003000020005030000174900"); tipList.add("标准数独-大师-5"); valueList.add("507000009080002170010060004090030000001709300000040060800050020076200090400000608"); tipList.add("标准数独-大师-6"); valueList.add("009700000500002709800010006001600405000040000706008200400090008602300004000007900"); tipList.add("标准数独-大师-7"); valueList.add("009000064400000000100360072004600009000903000200005400920057008000000005340000600"); tipList.add("标准数独-大师-8"); valueList.add("030008005005000807000040900000390400059070210002065000007050000501000700600900020"); tipList.add("标准数独-大师-9"); valueList.add("302700009008000045004001300000059000090030060000260000001400200260000100400002503"); tipList.add("标准数独-大师-10"); valueList.add("095008000002006700040000005050020007060050020400070080200000040006100300000300250"); tipList.add("标准数独-大师-11"); valueList.add("003000400007208500800030007200703004005000800700501009100040002006809700004000900"); tipList.add("标准数独-大师-12"); valueList.add("000009752090000000140800009009502006000308000700104500600003025000000010524600000"); tipList.add("X数独-大师-1 *"); valueList.add("806305000010070000300010400400000860000761000063000007001050009000080030000902604"); tipList.add("X数独-大师-2 *"); valueList.add("700010200005200300080075000400000080060487050070000003000320090008004600007060004"); tipList.add("X数独-大师-3 *"); valueList.add("200007030100025807000130040800000050000000000060000003090082000501370004030900005"); tipList.add("%数独-大师-1 *"); valueList.add("900570000000800003350010780010082000500637001000150030039060025200005000000021004"); tipList.add("%数独-大师-2 *"); valueList.add("300090006420000800005000700000300000070104050000005000004000200003000067100087009"); tipList.add("%数独-大师-3 *"); valueList.add("002700060000064000900003010001000709080307050307000100030800001000140000010000500"); //额外列表 insertSudoku(tipList, valueList, "复杂数独-1", "600300100071620000805001000500870901009000600407069008000200807000086410008003002"); insertSudoku(tipList, valueList, "复杂数独-2", "906013008058000090030000010060800920003409100049006030090000080010000670400960301"); insertSudoku(tipList, valueList, "复杂数独-3", "300060250000500103005210486000380500030000040002045000413052700807004000056070004"); insertSudoku(tipList, valueList, "复杂数独-4", "060001907100007230080000406018002004070040090900100780607000040051600009809300020"); insertSudoku(tipList, valueList, "复杂数独-5", "600300208400185000000000450000070835030508020958010000069000000000631002304009006"); insertSudoku(tipList, valueList, "复杂数独-6", "400030090200001600760800001500318000032000510000592008900003045001700006040020003"); insertSudoku(tipList, valueList, "复杂数独-7", "004090170900070002007204000043000050798406213060000890000709400600040001085030700"); insertSudoku(tipList, valueList, "复杂数独-8", "680001003007004000000820000870009204040302080203400096000036000000500400700200065"); insertSudoku(tipList, valueList, "复杂数独-9", "000002000103400005200050401340005090807000304090300017605030009400008702000100000"); insertSudoku(tipList, valueList, "复杂数独-10", "050702003073480005000050400040000200027090350006000010005030000400068730700109060"); insertSudoku(tipList, valueList, "复杂数独-11", "500080020007502801002900040024000308000324000306000470090006700703208900060090005"); insertSudoku(tipList, valueList, "复杂数独-12", "108090000200308096090000400406009030010205060080600201001000040360904007000060305"); insertSudoku(tipList, valueList, "复杂数独-13", "010008570607050009052170000001003706070000040803700900000017260100020407024300090"); insertSudoku(tipList, valueList, "复杂数独-14", "020439800080000001003001520050092703000000000309740080071300900600000030008924010"); insertSudoku(tipList, valueList, "复杂数独-15", "000500201800006005005207080017960804000000000908074610080405300700600009504009000"); insertSudoku(tipList, valueList, "复杂数独-16", "920000000500870000038091000052930160090000030073064980000410250000053001000000073"); insertSudoku(tipList, valueList, "复杂数独-17", "590006010001254709000001400003715008100000004200648100002500000708463900050100047"); insertSudoku(tipList, valueList, "复杂数独-18", "309870004000005008870400000104580003000706000700034105000009081900300000400057206"); insertSudoku(tipList, valueList, "复杂数独-19", "800200000910300706000007002084000009095104860100000230500600000609003071000005008"); insertSudoku(tipList, valueList, "复杂数独-20", "005037001000050627600002530020070000001968200000010090013700008486090000700840100"); insertSudoku(tipList, valueList, "复杂数独-21", "090350700000800029000402008710000000463508297000000051300204000940005000008037040"); insertSudoku(tipList, valueList, "复杂数独-22", "000005904080090605006000030030701450008040700074206090060000300801060070309800000"); insertSudoku(tipList, valueList, "复杂数独-23", "030004087948700500060800009010586720000000000087312050800003070003007865570200090"); insertSudoku(tipList, valueList, "复杂数独-24", "300687015000030082050000300400300000601050709000004003008000020210040000970521004"); insertSudoku(tipList, valueList, "复杂数独-25", "702000004030702010400093008000827090007030800080956000300570009020309080600000503"); insertSudoku(tipList, valueList, "复杂数独-26", "300040057400853060025700000000000430800406001034000000000005690090624003160080002"); insertSudoku(tipList, valueList, "复杂数独-27", "000260050000005900000380046020094018004000500950810070380021000005700000040058000"); insertSudoku(tipList, valueList, "复杂数独-28", "062080504008050090700320001000740620000203000027065000200036007040070100803090240"); insertSudoku(tipList, valueList, "复杂数独-29", "002001000068000003000086090900002086804000102520800009080140000100000920000700500"); insertSudoku(tipList, valueList, "复杂数独-30", "000030065460950200000086004003070006004090100500010300200140000007065028630020000"); mSudokuKeys.add(key); mSudokusTipListMap.put(key, tipList); mSudokusValueListMap.put(key, valueList); } private void addSudokus_4() { mSudokuTips.add("数独-经典"); String key = "standard_level_classics"; List<String> tipList = new ArrayList<>(); List<String> valueList = new ArrayList<>(); tipList.add("标准数独-经典-1"); valueList.add("100400800040030009009006050050300000000001600000070002004010900700800004020004080"); tipList.add("标准数独-经典-2"); valueList.add("080000001007004020600300700002009000100060008030400000001700600090008005000000040"); tipList.add("标准数独-经典-3"); valueList.add("100500400009030000070008005001000030800600500090007008004020010200800600000001002"); tipList.add("标准数独-经典-4"); valueList.add("000000070060010004003400200800003050002900700040080009020060007000100900700008060"); tipList.add("标准数独-经典-5"); valueList.add("100007090030020008009600500005300900010080002600004000300000010040000007007000300"); mSudokuKeys.add(key); mSudokusTipListMap.put(key, tipList); mSudokusValueListMap.put(key, valueList); } private void insertSudoku(List<String> tipList, List<String> valueList, String title, String value) { tipList.add(title); valueList.add(value); } public static Sudokus getInstance() { if (instance == null) { instance = new Sudokus(); } return instance; } public String[] getSudokuTipArray() { String[] ss = new String[mSudokuTips.size()]; for (int i = 0; i < mSudokuTips.size(); i++) { ss[i] = mSudokuTips.get(i); } return ss; } public List<String> getSudokuTips() { return mSudokuTips; } public List<String> getSudokuKeys() { return mSudokuKeys; } public String[] getSudokusTipArray(String key) { List<String> tipList = getSudokusTipList(key); String[] ss = new String[tipList.size()]; for (int i = 0; i < tipList.size(); i++) { ss[i] = tipList.get(i); } return ss; } public List<String> getSudokusTipList(String key) { return mSudokusTipListMap.get(key); } public List<String> getSudokusValueList(String key) { return mSudokusValueListMap.get(key); } }
guangGG/RoamCatX
sudoku/src/main/java/gapp/season/sudoku/Sudokus.java
66,224
package com.subao.common.e; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.text.TextUtils; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; /* compiled from: AccelGameMap */ public class c { /* access modifiers changed from: private */ public static final Locale a = Locale.US; @NonNull private final b b; @Nullable private HashMap<String, b> c; @Nullable private HashMap<String, b> d; /* compiled from: AccelGameMap */ public interface b { boolean a(@NonNull String str); boolean b(@NonNull String str); boolean c(@NonNull String str); } public c(@NonNull b bVar, @Nullable List<b> list) { this.b = bVar; a(list); } public c(@Nullable List<b> list) { this(new a(), list); } public void a(@Nullable List<b> list) { if (list == null || list.isEmpty()) { this.c = null; this.d = null; return; } this.c = new HashMap<>(list.size()); this.d = new HashMap<>(16); for (b next : list) { if (next.c()) { List<String> list2 = next.e; if (list2 != null) { for (String put : list2) { this.d.put(put, next); } } } else { this.c.put(next.a.toLowerCase(a), next); } } } @Nullable public b a(@NonNull String str, @NonNull String str2) { b bVar; if (TextUtils.isEmpty(str) || TextUtils.isEmpty(str2) || this.b.a(str2) || this.b.b(str)) { return null; } if (this.d == null || (bVar = this.d.get(str)) == null) { return a(str2); } return bVar; } private b a(@NonNull String str) { if (this.c == null) { return null; } String lowerCase = str.toLowerCase(a); b bVar = this.c.get(lowerCase); if (bVar != null) { return bVar; } if (lowerCase.length() <= 3) { return null; } for (Map.Entry next : this.c.entrySet()) { String str2 = (String) next.getKey(); if (str2.length() > 2) { b bVar2 = (b) next.getValue(); if (!bVar2.l && !bVar2.b() && lowerCase.contains(str2)) { if (this.b.c(lowerCase)) { return null; } return bVar2; } } } return null; } /* compiled from: AccelGameMap */ private static class a implements b { private static final String[] a = {"notification", "pps", "pptv", "theme", "wallpaper", "wifi", "安装", "八门神器", "百宝箱", "伴侣", "宝典", "备份", "必备", "壁纸", "变速", "表情", "补丁", "插件", "查询", "查询", "出招表", "春节神器", "答题", "大全", "大师", "单机", "动态", "翻图", "辅助", "辅助", "改名", "工具", "攻略", "喊话", "合成表", "合集", "盒子", "红包神器", "画报", "集市", "计算", "技巧", "計算", "加速", "脚本", "解说", "精选", "剧场", "快问", "礼包", "连招表", "论坛", "漫画", "秘籍", "模拟器", "魔盒", "配装器", "拼图", "启动器", "全集", "社区", "视频", "视讯", "手册", "刷开局", "刷魔", "锁屏", "台词", "特辑", "头条", "图集", "图鉴", "圖鑑", "外挂", "系列", "下载", "小说", "小智", "修改", "一键", "英雄帮", "英雄榜", "游戏盒", "游戏通", "掌游宝", "照相", "直播", "指南", "制作器", "主题", "助理", "助手", "抓包", "追剧", "桌面", "资料", "资讯", "資料", "作弊"}; private static final String[] b = {"掌上英雄联盟", "影之诗", "Shadowverse"}; private static final String[] c = {"com.kugou.android", "com.huluxia.mctool", "com.tencent.qt.sns", "com.cygames.Shadowverse", "jp.co.cygames.Shadowverse"}; private a() { } public boolean a(@NonNull String str) { for (String equals : b) { if (equals.equals(str)) { return true; } } return false; } public boolean b(@NonNull String str) { if (TextUtils.isEmpty(str)) { return false; } String lowerCase = str.toLowerCase(c.a); for (String equals : c) { if (equals.equals(lowerCase)) { return true; } } return false; } public boolean c(@NonNull String str) { for (String contains : a) { if (str.contains(contains)) { return true; } } return false; } } }
quyenlm/lq
app/src/main/java/com/subao/common/e/c.java
66,225
package com.mvvm.lux.burqa.model; import android.databinding.ObservableBoolean; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import com.mvvm.lux.burqa.base.SectionedRecyclerViewAdapter; import com.mvvm.lux.burqa.databinding.FragmentRecomBinding; import com.mvvm.lux.burqa.http.RetrofitHelper; import com.mvvm.lux.burqa.model.response.RecommendResponse; import com.mvvm.lux.burqa.ui.home.adapter.section.RecomBannerSection; import com.mvvm.lux.burqa.ui.home.adapter.section.RecomItemListSection; import com.mvvm.lux.burqa.ui.home.adapter.section.RecomItemSection; import com.mvvm.lux.burqa.ui.home.fragment.RecomFragment; import com.mvvm.lux.framework.base.BaseViewModel; import com.mvvm.lux.framework.http.RxHelper; import com.mvvm.lux.framework.http.RxSubscriber; import com.mvvm.lux.widget.emptyview.EmptyView; import java.util.List; /** * @Description * @Author luxiao418 * @Email [email protected] * @Date 2017/1/5 13:26 * @Version */ public class RecomViewModel extends BaseViewModel { private final RecomFragment mFragment; private final FragmentRecomBinding mDataBinding; public ObservableBoolean refreshing = new ObservableBoolean(false); public RecomViewModel(RecomFragment fragment, FragmentRecomBinding dataBinding) { super(fragment.getActivity()); mFragment = fragment; mDataBinding = dataBinding; refreshing.set(true); } public ObservableBoolean showEmpty = new ObservableBoolean(false); public SectionedRecyclerViewAdapter mAdapter; public EmptyView.ReloadOnClickListener mReloadOnClickListener = this::initData; // refreshing.set(true); 双向绑定之后,刷新之后就不用设置为true了 public SwipeRefreshLayout.OnRefreshListener onRefreshListener = this::initData; public RecyclerView.LayoutManager getLayoutManager() { GridLayoutManager layoutManager = new GridLayoutManager(mFragment.getActivity(), 6); layoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() { @Override public int getSpanSize(int position) { switch (mAdapter.getSectionItemViewType(position)) { case SectionedRecyclerViewAdapter.VIEW_TYPE_HEADER: case SectionedRecyclerViewAdapter.VIEW_TYPE_FOOTER: return 6; case SectionedRecyclerViewAdapter.VIEW_TYPE_ITEM_LOADED: return 2; default: return 6; } } }); return layoutManager; } public void initData() { RetrofitHelper.init() .getRecommend() .compose(RxHelper.handleErr()) .subscribe(new RxSubscriber<List<RecommendResponse>>() { @Override public void onNext(List<RecommendResponse> recommendResponse) { mAdapter = new SectionedRecyclerViewAdapter(); mAdapter.addSection(new RecomBannerSection(recommendResponse.get(0), mFragment.getActivity())); //大图推荐 mAdapter.addSection(new RecomItemSection(recommendResponse.get(1), mFragment.getActivity())); //近期必看 三个条目 mAdapter.addSection(new RecomItemListSection(recommendResponse.get(2), mFragment.getActivity())); //火热专题 两个条目 mAdapter.addSection(new RecomItemSection(recommendResponse.get(3), mFragment.getActivity())); //大师 mAdapter.addSection(new RecomItemSection(recommendResponse.get(4), mFragment.getActivity())); //国漫 mAdapter.addSection(new RecomItemListSection(recommendResponse.get(5), mFragment.getActivity())); //美漫 mAdapter.addSection(new RecomItemSection(recommendResponse.get(6), mFragment.getActivity())); //热门 mAdapter.addSection(new RecomItemListSection(recommendResponse.get(7), mFragment.getActivity())); //条漫 mAdapter.addSection(new RecomItemSection(recommendResponse.get(8), mFragment.getActivity())); //最新 // mAdapter.addSection(new RecomItemSection(recommendResponse.get(9), mFragment.getActivity())); mDataBinding.recyclerView.setAdapter(mAdapter); //加载完成之后要设置adapter,一定要记住 refreshing.set(false); showEmpty.set(false); } @Override public void onError(Throwable e) { super.onError(e); showEmpty.set(true); refreshing.set(false); } }); } }
luxiao0314/burqa
app/src/main/java/com/mvvm/lux/burqa/model/RecomViewModel.java
66,227
package cn.zhouchaoyuan.myanimation; import android.app.Fragment; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.DisplayMetrics; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.TextView; import android.widget.Toast; public class CardFlipActivity extends AppCompatActivity implements View.OnTouchListener{ //the width of the FrameLayout private int width; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_card_flip); if (savedInstanceState == null) { getFragmentManager() .beginTransaction() .add(R.id.flip_container, new FragmentCard()) .commit(); } FrameLayout frameLayout = (FrameLayout) findViewById(R.id.flip_container); frameLayout.setOnTouchListener(this); DisplayMetrics metrics = getResources().getDisplayMetrics(); width = metrics.widthPixels; } /** * judge flipCardForWard or flipCardBackWard * */ private float initx,offsetx; @Override public boolean onTouch(View v, MotionEvent event) { switch(event.getAction()){ case MotionEvent.ACTION_DOWN: initx = event.getX(); break; case MotionEvent.ACTION_UP: offsetx = event.getX() - initx; /*if(Math.abs(offsetx) < 5){//just click the view //click the view if(event.getX() > width/2){ flipCardForWard(); } else{ flipCardBackWard(); } } else*/ if(offsetx <= -5){// error of margin flipCardForWard(); } else if(offsetx >= 5){ flipCardBackWard(); } break; } return true; } /** * card flip forward * */ public void flipCardForWard() { getFragmentManager() .beginTransaction() .setCustomAnimations( R.animator.card_filp_right_in,R.animator.card_flip_right_out, R.animator.card_flip_left_in, R.animator.card_flip_left_out) .replace(R.id.flip_container, new FragmentCard()) .addToBackStack(null) .commit(); } /** * card flip backward * */ public void flipCardBackWard(){ if(getFragmentManager().getBackStackEntryCount() > 0){ getFragmentManager().popBackStack(); } else{ Toast.makeText(this,"First Page",Toast.LENGTH_SHORT).show(); } } /** * static inner class * */ public static class FragmentCard extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_flip_card, container, false); TextView textView = (TextView) view.findViewById(R.id.des_text); textView.setText(datas[index++ % datas.length]); return view; } } private static int index = 0; private final static String[] datas = { "明明可以靠脸吃饭,你却要靠才华,这就是你和明明的区别", "用“要么…要么…”造句,\n小明:冰棍五毛啊!要么…要么。", " 你认为最有影响力的物理学家是谁?\n我写的是“牛顿”。结果,全班只有我一个人没及格,原来,大家都把导师的名字写了上去……kao,什么世道!", "每天早上起床后我都要看一遍福布斯富翁排行榜,如果上面没有我的名字,我就去上班", "马云是首富啊,他有1500亿,咱中国13亿人,他给咱每人分1亿,咱们都是亿万富翁了,他还有1487亿,他依然是首富啊。我被这句话深深的感动了。", "在下姓聂,刚才到机场去接个客户,见面后客户非常热情的迎过来握手:聂总您好!您好!这时他的秘书用怪怪的目光在看我……你妹啊!你才孽种,你全家都孽种!", "有一朋友去找大师给他儿子取名。\n朋友:大师我给我儿子起名要有英文名字和中文名字,我姓陆。大师:叫陆由器,英文名Wi-Fi!", "早晨刚出小区门口,一个五六岁的小萝莉,一下抱住我的大腿哭着喊:叔叔,你娶了我吧!!! 我正凌乱中,忽然听背后一个声音说:你就是结婚了,今天也得给我上学去!" }; }
zhouchaoyuan/ThePlanForMe
M3-M4/W5/MyAnimation/app/src/main/java/cn/zhouchaoyuan/myanimation/CardFlipActivity.java
66,228
package com.liujh168.jqmq; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.os.Environment; import android.os.Handler; import android.util.AttributeSet; import android.util.Log; import android.view.GestureDetector; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.PopupMenu; import android.widget.Toast; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import static android.content.ContentValues.TAG; import static java.util.concurrent.locks.Lock.*; import com.liujh168.jqmq.Position; import javax.net.ssl.HttpsURLConnection; public class GameView extends View implements View.OnTouchListener { private GestureDetector mGestureDetector; public static float screen_height; //screen hight,从其它模块得到。不变的参数 public static float screen_width; //screen screen_width // 原始棋盘图参数,从属性得来 public static float board_width = 560f; //棋盘的大小 public static float board_height = 646f; public static float board_ox = 53.0f; //左上角棋子位置(相对于棋盘) public static float board_oy = 71.0f; private static float board_dd = 56f; //棋盘格大小 public static float xZoom = screen_width / board_width; //要充满屏幕的缩放比例 public static float yZoom = screen_height / board_height; public static float boardWidth = board_width * xZoom; //棋盘的大小 public static float boardHeight = board_height * yZoom; public static float boardOX = board_ox * xZoom; //左上角棋子位置(相对于棋盘) public static float boardOY = board_oy * yZoom; private static float SQUARE_SIZE = board_dd * xZoom; //棋盘格大小 public static float imgX = (screen_width - boardWidth * xZoom) / 2; //棋盘图像的起始坐标 public static float imgY = (screen_width - boardHeight * yZoom) / 2; int viewLeft = 0, viewTop = 0; //棋盘view的位置 public static int isvisible = 2; //控制棋盘棋子是否显示 public static boolean isnoPlaySound = true; //是否播放声音 public static boolean isBoardEdit = false; //是否棋盘编辑状态 public static final int RESP_CLICK = 0; public static final int RESP_ILLEGAL = 1; public static final int RESP_MOVE = 2; public static final int RESP_MOVE2 = 3; public static final int RESP_CAPTURE = 4; public static final int RESP_CAPTURE2 = 5; public static final int RESP_CHECK = 6; public static final int RESP_CHECK2 = 7; public static final int RESP_WIN = 8; public static final int RESP_DRAW = 9; public static final int RESP_LOSS = 10; public static final int RESP_BG = 11; //背景音乐 private String resultMessage = ""; private static final String[] PIECE_NAME = { null, null, null, null, null, null, null, null, "rk", "ra", "rb", "rn", "rr", "rc", "rp", null, "bk", "ba", "bb", "bn", "br", "bc", "bp", null, }; private static final String[] BOARD_NAME = { "wood", "green", "white", "sheet", "canvas", "drops", "qianhong" }; private static final String[] PIECES_NAME = { "wood", "delicate", "polish" }; private static final String[] SOUND_NAME = { "click", "illegal", "move", "move2", "capture", "capture2", "check", "check2", "win", "draw", "loss" }; private static final String[] MUSIC_NAME = { "express", "funny", "classic", "mozart1", "mozart4", "furelise", "lovdream", "waltz", "humour", "pal", "cmusic" }; static final int MUSIC_MUTE = MUSIC_NAME.length; static final String[] LEVEL_TEXT = { "入门", "业余", "专业", "大师", "特级大师" }; static int bFromWhich; //控制走法来源 static final int BMFROMCLOUD = 0; static final int BMFROMLOCAL = 1; Bitmap[] imgPieces = new Bitmap[PIECE_NAME.length]; Bitmap imgSelected, imgBoard, imgbrothers; JqmqActivity father; public static Position pos; public static Search search; private Paint paint; volatile boolean thinking; String currentFen; String retractFen; int sqSelected, mvLast; boolean flipped; int handicap, level, board, pieces, music; int mWidth, mHight; private Lock lock = new ReentrantLock(); public GameView(Context context) { super(context); this.father = (JqmqActivity) context; } public GameView(Context context, AttributeSet attrs) { super(context, attrs); this.father = (JqmqActivity) context; TypedArray boardattrs = context.obtainStyledAttributes(attrs, R.styleable.GameView); board_ox = boardattrs.getInteger(R.styleable.GameView_boardox, 53); //左上角棋子位置(相对于棋盘) board_oy = boardattrs.getInteger(R.styleable.GameView_boardoy, 71); board_width = boardattrs.getInteger(R.styleable.GameView_boardw, 560);//棋盘的大小 board_height = boardattrs.getInteger(R.styleable.GameView_boardh, 646); board_dd = boardattrs.getInteger(R.styleable.GameView_boarddd, 56); isvisible = boardattrs.getInteger(R.styleable.GameView_isVisible, 0); currentFen = boardattrs.getString(R.styleable.GameView_fen); int boardbg = boardattrs.getColor(R.styleable.GameView_boardbg, Color.RED); int boardline = boardattrs.getColor(R.styleable.GameView_boardline, Color.RED); boardattrs.recycle();//TypedArray对象回收 Log.d(TAG, "GameView: board_ox=" + board_ox); Log.d(TAG, "GameView: board_oy=" + board_oy); Log.d(TAG, "GameView: board_dd=" + board_dd); Log.d(TAG, "GameView: board_width=" + board_width); Log.d(TAG, "GameView: board_height=" + board_height); Log.d(TAG, "GameView: board_fen=" + currentFen); initChessViewFinal(); //更新相关绘图参数 this.paint = new Paint(); // this.paint.setColor(boardline); this.paint.setStrokeWidth(3); loadPieces(); loadBoard(); pos = new Position(); search = new Search(pos, 16); currentFen = Position.STARTUP_FEN[0]; retractFen = currentFen; flipped = false; thinking = false; bFromWhich = BMFROMLOCAL; bFromWhich = BMFROMCLOUD; int handicap = 0, level = 1, board = 0, pieces = 0, music = 8; mGestureDetector = new GestureDetector(new gestureListener()); //使用派生自OnGestureListener setOnTouchListener(this); setFocusable(true); setClickable(true); // setLongClickable(true); } public void restart() { currentFen=father.getString(R.string.txt_start_fen); retractFen = currentFen; pos.fromFen(currentFen); isvisible = 2; bFromWhich = BMFROMCLOUD; sqSelected = mvLast = 0; invalidate(); if (flipped && pos.sdPlayer == 0) { thinking(); } playSound(RESP_CLICK); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); int width = getMySize((int) imgX, widthMeasureSpec); int height = getMySize((int) imgY, heightMeasureSpec); height = (int) ((width / 9) * 10 + board_dd * 0.8f); setMeasuredDimension(width, height); viewLeft = getLeft(); viewTop = getTop(); Log.d("测量 GameView", "view_width: " + width + " view_height: " + height); Log.d("测量 GameView", "viewLeft=" + viewLeft + " viewTop=" + viewTop); } // @Override // public boolean onTouchEvent(MotionEvent e) { //// super(e); // float currentX = e.getX(); // float currentY = e.getY(); // int action = e.getAction(); // switch (action) { // case MotionEvent.ACTION_DOWN: // if (!thinking) { // currentX = e.getX() - (boardOX - SQUARE_SIZE / 2); // currentY = e.getY() - (boardOY - SQUARE_SIZE / 2); // int x = Util.MIN_MAX(0, (int) (currentX / SQUARE_SIZE), 8); // int y = Util.MIN_MAX(0, (int) (currentY / SQUARE_SIZE), 9); // int currsq = Position.COORD_XY(x + Position.FILE_LEFT, y + Position.RANK_TOP); //// Log.d("点击选择的棋盘格为:",Integer.toHexString(currsq)); // if (!isBoardEdit) { // clickSquare(currsq); // } else { // clickSquareOnBoardEdit(currsq); // } // } // // break; // case MotionEvent.ACTION_MOVE: // break; // case MotionEvent.ACTION_UP: // break; // } // return false; // } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); if (isvisible == 0) { return; //仅显示广告 } if (isvisible == 1) { canvas.drawBitmap(JqmqActivity.scaleToFit(imgBoard, xZoom), 0, 0, null); return; //仅显示棋盘,不显示棋子 } //以下正常显示棋盘棋子 canvas.drawBitmap(JqmqActivity.scaleToFit(imgBoard, xZoom), 0, 0, null); lock.lock(); //这里应该只锁pos数据更新,重画时间久 for (int x = Position.FILE_LEFT; x <= Position.FILE_RIGHT; x++) { for (int y = Position.RANK_TOP; y <= Position.RANK_BOTTOM; y++) { int sq = Position.COORD_XY(x, y); sq = (flipped ? Position.SQUARE_FLIP(sq) : sq); int pc = pos.squares[sq]; float xx = boardOX + (x - Position.FILE_LEFT) * SQUARE_SIZE; float yy = boardOY + (y - Position.RANK_TOP) * SQUARE_SIZE; if (pc > 0) { canvas.drawBitmap(JqmqActivity.scaleToFit(imgPieces[pc], xZoom * 1.15f), xx - SQUARE_SIZE / 2, yy - SQUARE_SIZE / 2, null); } if (sq == sqSelected || sq == Position.SRC(mvLast) || sq == Position.DST(mvLast)) { canvas.drawBitmap(JqmqActivity.scaleToFit(imgSelected, xZoom), xx - SQUARE_SIZE / 2, yy - SQUARE_SIZE / 2, null); } } } lock.unlock(); } private void loadBoard() { imgBoard = BitmapFactory.decodeResource(getResources(), R.drawable.board); imgbrothers = BitmapFactory.decodeResource(getResources(), R.drawable.brothers); } private void loadPieces() { imgSelected = BitmapFactory.decodeResource(getResources(), R.drawable.mm); imgPieces[8] = BitmapFactory.decodeResource(getResources(), R.drawable.rk); imgPieces[9] = BitmapFactory.decodeResource(getResources(), R.drawable.ra); imgPieces[10] = BitmapFactory.decodeResource(getResources(), R.drawable.rb); imgPieces[11] = BitmapFactory.decodeResource(getResources(), R.drawable.rn); imgPieces[12] = BitmapFactory.decodeResource(getResources(), R.drawable.rr); imgPieces[13] = BitmapFactory.decodeResource(getResources(), R.drawable.rc); imgPieces[14] = BitmapFactory.decodeResource(getResources(), R.drawable.rp); imgPieces[16] = BitmapFactory.decodeResource(getResources(), R.drawable.bk); imgPieces[17] = BitmapFactory.decodeResource(getResources(), R.drawable.ba); imgPieces[18] = BitmapFactory.decodeResource(getResources(), R.drawable.bb); imgPieces[19] = BitmapFactory.decodeResource(getResources(), R.drawable.bn); imgPieces[20] = BitmapFactory.decodeResource(getResources(), R.drawable.br); imgPieces[21] = BitmapFactory.decodeResource(getResources(), R.drawable.bc); imgPieces[22] = BitmapFactory.decodeResource(getResources(), R.drawable.bp); } void clickSquare(int sq_) { int sq = (flipped ? Position.SQUARE_FLIP(sq_) : sq_); int pc = pos.squares[sq]; if ((pc & Position.SIDE_TAG(pos.sdPlayer)) != 0) { if (mvLast > 0) { mvLast = 0; } sqSelected = sq; invalidate(); playSound(RESP_CLICK); } else if (sqSelected > 0) { int mv = Position.MOVE(sqSelected, sq); if (!pos.legalMove(mv)) { playSound(RESP_ILLEGAL); Toast.makeText(father, "不能这么走啊,亲", Toast.LENGTH_SHORT).show(); return; } if (!pos.makeMove(mv)) { playSound(RESP_ILLEGAL); Toast.makeText(father, "不能送将啊,亲", Toast.LENGTH_SHORT).show(); return; } int response = pos.inCheck() ? RESP_CHECK : pos.captured() ? RESP_CAPTURE : RESP_MOVE; if (pos.captured()) { pos.setIrrev(); } mvLast = mv; sqSelected = 0; invalidate(); playSound(response); if (!getResult()) { Toast.makeText(father, resultMessage, Toast.LENGTH_LONG); thinking(); } } } //摆棋状态的clicksquare.在退出摆棋状态时应该检查棋盘的正确性。 void clickSquareOnBoardEdit(int sq_) { final int sq = (flipped ? Position.SQUARE_FLIP(sq_) : sq_); int pc = pos.squares[sq]; if (pc != 0) { if (sqSelected == sq) { pos.squares[sq] = 0; sqSelected = 0; } else { sqSelected = sq; } playSound(RESP_CLICK); } else if (sqSelected > 0) { pos.squares[sq] = pos.squares[sqSelected]; pos.squares[sqSelected] = 0; sqSelected = 0; playSound(RESP_CLICK); } else { //以下弹出棋子列表菜单 PopupMenu popup = new PopupMenu(father, this); popup.getMenuInflater().inflate(R.menu.cmenu, popup.getMenu()); popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { case R.id.popmenurr: pos.squares[sq] = 8 + Position.PIECE_ROOK; Log.d(TAG, "onMenuItemClick: 红车"); break; case R.id.popmenurn: pos.squares[sq] = 8 + Position.PIECE_KNIGHT; Log.d(TAG, "onMenuItemClick: 红马"); break; case R.id.popmenurc: pos.squares[sq] = 8 + Position.PIECE_CANNON; Log.d(TAG, "onMenuItemClick: 红炮"); break; case R.id.popmenurp: pos.squares[sq] = 8 + Position.PIECE_PAWN; Log.d(TAG, "onMenuItemClick: 红兵"); break; case R.id.popmenurb: pos.squares[sq] = 8 + Position.PIECE_BISHOP; Log.d(TAG, "onMenuItemClick: 红相"); break; case R.id.popmenura: pos.squares[sq] = 8 + Position.PIECE_ADVISOR; Log.d(TAG, "onMenuItemClick: 红仕"); break; case R.id.popmenurk: pos.squares[sq] = 8 + Position.PIECE_KING; Log.d(TAG, "onMenuItemClick: 红帅"); break; case R.id.popmenubr: pos.squares[sq] = 16 + Position.PIECE_ROOK; break; case R.id.popmenubn: pos.squares[sq] = 16 + Position.PIECE_KNIGHT; break; case R.id.popmenubc: pos.squares[sq] = 16 + Position.PIECE_CANNON; break; case R.id.popmenubp: pos.squares[sq] = 16 + Position.PIECE_PAWN; break; case R.id.popmenubb: pos.squares[sq] = 16 + Position.PIECE_BISHOP; break; case R.id.popmenuba: pos.squares[sq] = 16 + Position.PIECE_ADVISOR; break; case R.id.popmenubk: pos.squares[sq] = 16 + Position.PIECE_KING; break; default: pos.squares[sq] = 0; break; } invalidate(); return true; } }); popup.show(); } invalidate(); } void thinking() { thinking = true; new Thread() { public void run() { int mv = mvLast; lock.lock(); mvLast = searchBestMove(); if (pos.legalMove(mvLast)) { pos.makeMove(mvLast); lock.unlock(); int response = pos.inCheck() ? RESP_CHECK2 : pos.captured() ? RESP_CAPTURE2 : RESP_MOVE2; if (pos.captured()) { pos.setIrrev(); } getResult(response); //此处更新棋盘,在UI线程提示消息 father.runOnUiThread(new Runnable() { @Override public void run() { //father.edtFen.setText(resultMessage); //Toast.makeText(father, resultMessage, Toast.LENGTH_LONG); invalidate(); } }); thinking = false; }else{ lock.unlock(); playSound(RESP_ILLEGAL); thinking = false; } } }.start(); } void playSound(int response) { father.playSound(response, 0); } /** * Player Move Result */ boolean getResult() { return getResult(-1); } /** * Computer Move Result */ boolean getResult(int response) { if (pos.isMate()) { resultMessage = response < 0 ? "祝贺你取得胜利!" : "你输啦,请再接再厉!"; playSound(response < 0 ? RESP_WIN : RESP_LOSS); return true; } int vlRep = pos.repStatus(3); if (vlRep > 0) { vlRep = (response < 0 ? pos.repValue(vlRep) : -pos.repValue(vlRep)); playSound(vlRep > Position.WIN_VALUE ? RESP_LOSS : vlRep < -Position.WIN_VALUE ? RESP_WIN : RESP_DRAW); resultMessage = vlRep > Position.WIN_VALUE ? "长打作负,请不要气馁!" : vlRep < -Position.WIN_VALUE ? "电脑长打作负,祝贺你取得胜利!" : "双方不变作和,辛苦了!"; return true; } if (pos.moveNum > 100) { playSound(RESP_DRAW); resultMessage = "超过自然限着作和,辛苦了!"; return true; } if (response >= 0) { playSound(response); retractFen = currentFen; currentFen = pos.toFen(); } return false; } public static void initChessViewFinal() { xZoom = screen_width / board_width; yZoom = screen_height / board_height; if (xZoom > yZoom) { xZoom = yZoom; } else { yZoom = xZoom; } imgX = (screen_width - board_width * xZoom) / 2; imgY = (screen_height - board_height * yZoom) / 2; boardOX = board_ox * xZoom; //左上角棋子位置(相对于棋盘) boardOY = board_oy * yZoom; boardWidth = board_width * xZoom; //棋盘的大小 boardHeight = board_height * xZoom; SQUARE_SIZE = board_dd * xZoom; //棋盘格大小 } private int getMySize(int defaultSize, int measureSpec) { int mySize = defaultSize; int mode = MeasureSpec.getMode(measureSpec); int size = MeasureSpec.getSize(measureSpec); switch (mode) { case MeasureSpec.UNSPECIFIED: {//如果没有指定大小,就设置为默认大小 mySize = defaultSize; break; } case MeasureSpec.AT_MOST: {//如果测量模式是最大取值为size //我们将大小取最大值,你也可以取其他值 mySize = size; break; } case MeasureSpec.EXACTLY: {//如果是固定的大小,那就不要去改变它 mySize = size; break; } } return mySize; } private void setimgsize(ImageView img) { //设置图片宽高 img.setLayoutParams(new ViewGroup.LayoutParams(mWidth, mHight)); img.setImageResource(R.drawable.ba); img.setScaleType(ImageView.ScaleType.FIT_CENTER); } private void getWidthHight() { this.post(new Runnable() { @Override public void run() { mWidth = getWidth(); mHight = mWidth; Log.d(TAG, "run: this.post.Runnable.run of getWidthHight"); } }); } //根据Position数据生成棋盘棋子图片(这个函数未使用,待调试) private void drawBoard() { Bitmap board = BitmapFactory.decodeResource(getResources(), R.drawable.board); // 得到图片的宽、高 int width_board = board.getWidth(); int height_board = board.getHeight(); // 创建一个你需要尺寸的Bitmap Bitmap mBitmap = Bitmap.createBitmap(width_board, height_board, Bitmap.Config.ARGB_8888); // 用这个Bitmap生成一个Canvas,然后canvas就会把内容绘制到上面这个bitmap中 Canvas mCanvas = new Canvas(mBitmap); // 绘制棋盘图片 mCanvas.drawBitmap(board, 0.0f, 0.0f, paint); // 绘制棋子图片 Bitmap piece = BitmapFactory.decodeResource(getResources(), R.drawable.bk); // 得到棋子的宽、高 int width_piece = piece.getWidth(); int height_piece = piece.getHeight(); // 绘制图片--保证其在水平方向居中 mCanvas.drawBitmap(piece, (width_board - width_piece) / 2, 0.0f, paint); // 绘制文字 paint.setColor(Color.WHITE);// 白色画笔 paint.setTextSize(80.0f);// 设置字体大小 // 绘制文字 paint.setColor(Color.RED);// 红色画笔 paint.setTextSize(120.0f);// 设置字体大小 String distanceTextString = "中国象棋盲棋训练系统:"; String distanceDataString = String.valueOf(888); String distanceScalString = "元"; float distanceTextString_width = paint.measureText( distanceTextString, 0, distanceTextString.length()); float distanceDataString_width = paint.measureText( distanceDataString, 0, distanceDataString.length()); float distanceScalString_width = paint.measureText( distanceScalString, 0, distanceScalString.length()); float x = (width_board - distanceTextString_width - distanceDataString_width - distanceScalString_width) / 2; mCanvas.drawText(distanceTextString, x, height_piece, paint);// 绘制文字 mCanvas.drawText(distanceDataString, x + distanceTextString_width, height_piece, paint);// 绘制文字 mCanvas.drawText(distanceScalString, x + distanceTextString_width + distanceDataString_width, height_piece, paint);// 绘制文字 // 保存绘图为本地图片 mCanvas.save(Canvas.ALL_SAVE_FLAG); mCanvas.restore(); File file = new File(Environment.getExternalStorageDirectory().getPath() + "/盲棋.png"); Log.i("CXC", Environment.getExternalStorageDirectory().getPath()); FileOutputStream fos = null; try { fos = new FileOutputStream(file); mBitmap.compress(Bitmap.CompressFormat.PNG, 50, fos); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { fos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // 在onTouch()方法中,我们调用GestureDetector的onTouchEvent()方法,将捕捉到的MotionEvent交给GestureDetector // 来分析是否有合适的callback函数来处理用户的手势 @Override public boolean onTouch(View v, MotionEvent event) { Log.i("GameView", "onTouch"); //Toast.makeText(father, "onTouch", Toast.LENGTH_LONG).show(); return mGestureDetector.onTouchEvent(event); } private class gestureListener implements GestureDetector.OnGestureListener { // 用户轻触触摸屏,由1个MotionEvent ACTION_DOWN触发 public boolean onDown(MotionEvent e) { Log.i("MyGesture", "onDownPress"); //Toast.makeText(father, "onDown", Toast.LENGTH_SHORT).show(); // super(e); float currentX = e.getX(); float currentY = e.getY(); int action = e.getAction(); switch (action) { case MotionEvent.ACTION_DOWN: if (!thinking) { currentX = e.getX() - (boardOX - SQUARE_SIZE / 2); currentY = e.getY() - (boardOY - SQUARE_SIZE / 2); int x = Util.MIN_MAX(0, (int) (currentX / SQUARE_SIZE), 8); int y = Util.MIN_MAX(0, (int) (currentY / SQUARE_SIZE), 9); int currsq = Position.COORD_XY(x + Position.FILE_LEFT, y + Position.RANK_TOP); // Log.d("点击选择的棋盘格为:",Integer.toHexString(currsq)); if (!isBoardEdit) { clickSquare(currsq); } else { clickSquareOnBoardEdit(currsq); } } break; case MotionEvent.ACTION_MOVE: break; case MotionEvent.ACTION_UP: break; } return false; //return false; } //用户轻触触摸屏,尚未松开或拖动,由一个1个MotionEvent ACTION_DOWN触发 //注意和onDown()的区别,强调的是没有松开或者拖动的状态 // 而onDown也是由一个MotionEventACTION_DOWN触发的,但是他没有任何限制, // 也就是说当用户点击的时候,首先MotionEventACTION_DOWN,onDown就会执行, // 如果在按下的瞬间没有松开或者是拖动的时候onShowPress就会执行,如果是按下的时间超过瞬间 // (这块我也不太清楚瞬间的时间差是多少,一般情况下都会执行onShowPress),拖动了,就不执行onShowPress。 public void onShowPress(MotionEvent e) { Log.i("MyGesture", "onShowPress"); //Toast.makeText(father, "onShowPress", Toast.LENGTH_SHORT).show(); } // 用户(轻触触摸屏后)松开,由一个1个MotionEvent ACTION_UP触发 ///轻击一下屏幕,立刻抬起来,才会有这个触发 //从名子也可以看出,一次单独的轻击抬起操作,当然,如果除了Down以外还有其它操作,那就不再算是Single操作了,所以这个事件 就不再响应 public boolean onSingleTapUp(MotionEvent e) { Log.i("MyGesture", "onSingleTapUp"); // Toast.makeText(father, "onSingleTapUp", Toast.LENGTH_SHORT).show(); return true; } // 用户按下触摸屏,并拖动,由1个MotionEvent ACTION_DOWN, 多个ACTION_MOVE触发 public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { Log.i("MyGesture22", "onScroll:" + (e2.getX() - e1.getX()) + " " + distanceX); //Toast.makeText(father, "onScroll", Toast.LENGTH_LONG).show(); return true; } // 用户长按触摸屏,由多个MotionEvent ACTION_DOWN触发 public void onLongPress(MotionEvent e) { Log.i("MyGesture", "onLongPress"); father.edtFen.setText("onLongPress"); //Toast.makeText(father, "onLongPress", Toast.LENGTH_LONG).show(); } // 用户按下触摸屏、快速移动后松开,由1个MotionEvent ACTION_DOWN, 多个ACTION_MOVE, 1个ACTION_UP触发 public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { Log.i("MyGesture", "onFling"); Toast.makeText(father, "onFling", Toast.LENGTH_LONG).show(); return true; } } //从云库获取走法,主要是用于解残局 int searchBestMove(){ int mv=0; HttpURLConnection connection=null; BufferedReader reader=null; switch(bFromWhich){ case BMFROMCLOUD: try { String strquery="http://api.chessdb.cn:81/chessdb.php?action=querybest&board="; String fenexample = "rnbakabnr/9/1c5c1/p1p1p1p1p/9/9/P1P1P1P1P/1C5C1/9/RNBAKABNR w"; fenexample = pos.toFen(); strquery = strquery+fenexample; Log.d(TAG, "searchBestMove: 云库查询"+strquery); //String strquery="http://www.baidu.com"; URL url = new URL(strquery); connection=(HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(8000); connection.setReadTimeout(8000); InputStream in = connection.getInputStream(); reader = new BufferedReader((new InputStreamReader(in))); StringBuilder response = new StringBuilder(); String line; while( ( line=reader.readLine() )!=null ){ response.append(line); } Log.d(TAG, "cloudBestMove: "+ response.toString()); ShowResponse(response.toString()); mv = iccs2Move(response.toString().substring(5,9)); Log.d(TAG, "cloudBestMove: " + Integer.toHexString(mv)); if(mv==0) { bFromWhich = BMFROMLOCAL; mv = search.searchMain(100 << (level << 1)); Log.d(TAG, "BestMove电脑切换本地引擎" + Integer.toHexString(mv)); } }catch (Exception e) { e.printStackTrace(); }finally { if(reader!=null){ try{ reader.close(); }catch (IOException e){ e.printStackTrace(); } } if(connection!=null){ connection.disconnect(); } } break; default: mv = search.searchMain(100 << (level << 1)); ShowResponse("localBestMove: " + Integer.toHexString(mv)); Log.d(TAG, "localBestMove: " + Integer.toHexString(mv)); break; } return mv; } private void ShowResponse(final String response){ father.runOnUiThread(new Runnable(){ @Override public void run(){ father.edtFen.setText(response); } }); } /** ICCS表示转换为内部着法表示 */ private int iccs2Move(String strIccs) { char[] cIccs = strIccs.toCharArray(); if (cIccs[0] < 'a' || cIccs[0] > 'i' || cIccs[1] < '0' || cIccs[1] > '9' || cIccs[2] < 'a' || cIccs[2] > 'i' || cIccs[3] < '0' || cIccs[3] > '9') { return 0; } int sqSrc = pos.COORD_XY(cIccs[0] - 'a' + pos.FILE_LEFT, '9' + pos.RANK_TOP - cIccs[1]); int sqDst = pos.COORD_XY(cIccs[2] - 'a' + pos.FILE_LEFT, '9' + pos.RANK_TOP - cIccs[3]); return pos.MOVE(sqSrc, sqDst); } }
liujh168/jqmq
app/src/main/java/com/liujh168/jqmq/GameView.java
66,229
package com.example.administrator.bazipaipan.chat.fragment; import android.content.Context; import android.os.Bundle; import android.support.v4.app.Fragment; import com.example.administrator.bazipaipan.augur.model.Augur; import com.example.administrator.bazipaipan.chat.ChatContainerActivity; import com.example.administrator.bazipaipan.login.model.MyUser; import com.example.administrator.bazipaipan.utils.BmobUtils; /** * Created by 王中阳 on 2016/1/7. */ public class ChatMainFragment extends Fragment { private ChatContainerActivity mycontext; private Augur augur; private MyUser myUser; /** * 1进入聊天室(游客围观) * 2点击排队(队列中) * 3正在测算 */ private String chatType; /** * 1有人排队 * 2到自己 */ private String hasline; /** * 命主测算状态 * 1在队列首位 轮到他 * 2测算中 * 3测算结束 */ private String clientChatType; /** * 大师测算状态 * 1测算中 * 2结束 */ private String augurChattype; /** * 在线状态 * 1在聊天室 * 2在app中 * 3离线状态 */ private String onlineType; /** * 系统消息 * 1开始测算 * 2结束测算 * 3为大师打赏 */ private String sysMsg; /** * 退出聊天室的方式 * 1点返回 back键及左上角返回按钮退出 * 2点结束 结束按钮只有大师和命主可见 */ private String quitType; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); String userType = BmobUtils.getCurrentUser(mycontext).getType(); enterRoom(userType); } private void enterRoom(String type) { //大师 非大师进入房间 chatType = "1"; switch (type) { case "1"://游客 /** * 1进入就是围观区 * 2点击排队之后才能进行聊天 * 3一对一测算是从聊天队列中获取的 */ switch (chatType) { case "1"://在围观 /** * 1发送信息到围观区,显示简键盘 * 2送礼物 * 3排队 * 4关注大师 */ //点击排队 chatType = "2"; break; case "2"://在排队 /** * 1在排队队列首位 * 2大师点击结束回话按钮 * 3填写自己的命盘 * 4取消排队 */ switch (hasline) { case "1"://有人排队 //取消排队 chatType = "2"; break; case "2"://没人排队 到自己 chatType = "3"; clientChatType = "1"; break; } break; case "3"://在测算 switch (clientChatType) { case "1"://队列到自己测算 轮到他 switch (onlineType) { case "1"://在聊天室 /** * 1弹窗提示,到“xxx”测算 * 2显示全键盘:语音 图片 表情 * 3显示发送内容到聊天区 */ sysMsg = "1"; break; case "2"://在app /** * 1弹窗提示到“xxx” * 2“确定”,进入到大师房间 * 3“取消”,从排队队列中清除,关闭弹窗 */ break; case "3"://离线 /** * 1通知栏提醒,点击通知栏进入聊天室 * 2短信提醒 ---是否需要不?? * 3 1分钟后不回复,从排队队列中清除?? */ break; } break; case "2"://测算中 switch (onlineType) { case "1"://在聊天室 /** * 1主动聊天 双方回话 * 2系统消息 */ break; case "2"://在app /** * 提示红点?? */ break; case "3"://离线 /** * 1通知栏提醒,点击通知栏进入聊天室 * 2短信提醒 ---是否需要不?? * 3 1分钟后不回复,从排队队列中清除?? */ break; } break; case "3"://测算结束 switch (quitType) { case "1"://back键 左上角退出 /** * 1弹窗是否退出 */ break; case "2"://结束按钮退出 /** * 1提示打赏 弹窗 * 2回到围观区 */ chatType = "2"; break; } break; } break; } break; case "2"://大师 switch (augurChattype) { case "1"://测算中 switch (onlineType) { case "1"://聊天室 break; case "2"://在app break; case "3"://离线 break; } break; case "2"://结束 switch (quitType) { case "1"://点返回 back键 /** * 1测算中:弹窗确定是否退出 * 2休息中:直接退出:队列中没有人排队 * 3添加一种 不测算,但是可以和围观区互动的情景 */ break; case "2"://点结束按钮 /** * 1弹窗确定 */ break; } break; } break; } } @Override public void onAttach(Context context) { super.onAttach(context); this.mycontext = (ChatContainerActivity) context; } }
jiangqqlmj/BaziXiansheng
app/src/main/java/com/example/administrator/bazipaipan/chat/fragment/ChatMainFragment.java
66,230
package com.ctz.destiny.resource.body; /** * Created by chentz on 2017/10/19. */ import java.text.ParseException; import java.util.Calendar; /** *排大运 * @author luozhuang 大师♂罗莊 */ public class Luozhuangpaipandayun { LuozhuangshenshaHehun myLuozhuangshenshaHehun = new LuozhuangshenshaHehun(); Luozhuanglvhehun myLuozhuanglvhehun = new Luozhuanglvhehun(); /** * * @param man 生日 yyyy-MM-dd HH * @return 返回乾造 * @throws ParseException */ public String paipan(String man, Sex isman) throws ParseException { Calendar mancal; try { mancal = myLuozhuangshenshaHehun.getCalendarfromString(man, "yyyy-MM-dd HH"); //原来的private 方法改了下 } catch (ParseException ex) { return "输入不正确" + ex.getMessage(); } return paipan(mancal, isman); } /**找数组中月柱起始位置 * * @param jiazhi * @param yuezhu * @return */ public int getyuezhuStart(String[] jiazhi, String yuezhu) { int start = -1; for (int i = 0; i < jiazhi.length; i++) { if (yuezhu.equals(jiazhi[i])) { start = i; break; } } return start; } //顺行排大运 private String[] shundayun(String yuezhu) { String[] DayunStringArray = new String[8];//取八个 String[] jiazhi = myLuozhuanglvhehun.jiazhi; int start = getyuezhuStart(jiazhi, yuezhu); if (start == -1) { return null; } else { start++; } for (int i = 0; i < 8; i++) { DayunStringArray[i] = jiazhi[(start + i) % jiazhi.length]; } return DayunStringArray; } //逆行排大运 private String[] nidayun(String yuezhu) { String[] DayunStringArray = new String[8];//取八个 String[] jiazhi = myLuozhuanglvhehun.jiazhi; int start = getyuezhuStart(jiazhi, yuezhu); if (start == -1) { return null; } else { start--; } for (int i = 0; i < 8; i++) { DayunStringArray[i] = jiazhi[(start - i) % jiazhi.length]; } return DayunStringArray; } //大运用月柱排 public String[] Dayun(String nianzhu,String yuezhu,Sex isman) { String[] DayunStringArray = null; if (yuezhu == null || yuezhu.length() != 2) { return null; } //甲、丙、戊、庚、壬之年为阳,乙、丁、己、辛、癸之年为阴 //阴年生男子(或阳年生女子),大运逆行否则顺行 if (nianzhu.startsWith("甲") || nianzhu.startsWith("丙") || nianzhu.startsWith("戊") || nianzhu.startsWith("庚") || nianzhu.startsWith("庚") || nianzhu.startsWith("壬")) { if (isman == Sex.MAN) {//顺行 DayunStringArray= shundayun(yuezhu); } else { DayunStringArray=nidayun(yuezhu); } } else { if (isman == Sex.MAN) { DayunStringArray= nidayun(yuezhu); } else { DayunStringArray=shundayun(yuezhu); } } return DayunStringArray; } private String paipan(Calendar cal, Sex isman) throws ParseException { BaZi lunar = new BaZi(cal); System.out.println("此人农历的日期【" + lunar.toString() + "】"); /** * 很多地方都是按照23:00-1:00为子时这是不对的。 * 子时24.00-2.00,丑时2.00-4.00,寅时4.00-6.00,卯时6.00-8.00, * 辰时8.00-10.00,巳时10.00-12.00,午时12.00-14.00,未时14.00-16.00 * 申时16.00-18.00,酉时18.00-20.00,戌时20.00-22.00,亥时22.00-24.00 * */ int time = cal.get(Calendar.HOUR_OF_DAY) / 2; System.out.println("此人八字【" + lunar.getYearGanZhi(time) + "】"); //获取生肖 System.out.println("此人的农历生肖【" + lunar.animalsYear() + "】"); String GanZhi = lunar.getYearGanZhi(time);//取八字 String[] tempchar = GanZhi.split(","); //我修改原来的,用,分割 String ganziyear = tempchar[0];//年柱 String ganzimonth = tempchar[1];//月柱 String ganziday = tempchar[2];//日柱 String ganzitime = tempchar[3];//时柱 //五行纳音 String soundyear = myLuozhuangshenshaHehun.getnumsix(ganziyear); String soundmonth = myLuozhuangshenshaHehun.getnumsix(ganzimonth); String soundday = myLuozhuangshenshaHehun.getnumsix(ganziday); String soundtime = myLuozhuangshenshaHehun.getnumsix(ganzitime); String[] DayunArray = Dayun(ganziyear,ganzimonth, isman); pringst(DayunArray); return null; } public static void pringst(String[] res) { for (int i = 0; i < res.length; i++) { System.out.print(res[i]); System.out.print(" "); } System.out.println(""); } /** * @param args the command line arguments */ public static void main(String[] args) throws ParseException { String[] test = new String[2]; test[0]="a"; test[1]="b"; System.out.print(String.format(":%s,:%s",test)); } }
yyctz/destiny
src/main/java/com/ctz/destiny/resource/body/Luozhuangpaipandayun.java
66,231
package ledong.wxapp.constant.enums; /** * 响应码 * * @author pengdengfu * */ public enum GradeCodeEnum { BRASS(1000, "青铜"), SILVER(1001, "白银"), GOLDEN(1002, "黄金"), DIAMOND(1003, "钻石"), MASTER(1004, "大师"), ONEPOINT(2001, "1.0"), ONEANDHALF(2002, "1.5"), TWOPOINT(2003, "2.0"), TWOANDHALF(2004, "2.5"), THREEPOINT(2005, "3.0"), THREEANDHALF(2006, "3.5"), FOURPOINT(2007, "4.0"), FOURANDHALF(2008, "4.5"), UNKOWN_ERROR(90001, "未知错误"); private Integer code; private String message; GradeCodeEnum(Integer code, String message) { this.code = code; this.message = message; } public Integer getCode() { return this.code; } public String getMessage() { return this.message; } public static String getMessage(String name) { for (GradeCodeEnum item : GradeCodeEnum.values()) { if (item.name().equals(name)) { return item.message; } } return name; } public static Integer getCode(String name) { for (GradeCodeEnum item : GradeCodeEnum.values()) { if (item.name().equals(name)) { return item.code; } } return null; } @Override public String toString() { return this.name(); } }
niyaou/ledong-tennis
wxapp/src/main/java/ledong/wxapp/constant/enums/GradeCodeEnum.java
66,232
package com.ctz.destiny.resource.body; /** * @(#)Lunar.java 2008-4-5 2:06:22 */ import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.List; import java.util.TimeZone; import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * 提供一些农历相关信息 * * @author 林志斌, 修改by 大师♂罗莊 */ public class Lunar { /** * 获得某天后个节气日期差 * * @return 日期数 */ public static List<JieQi> Alljieqi(int year) { List<JieQi> jieqi = new ArrayList<>(); jieqi.addAll(JieQiUtil.getYearJieQiList(year-1)); jieqi.addAll(JieQiUtil.getYearJieQiList(year)); jieqi.addAll(JieQiUtil.getYearJieQiList(year+1)); return jieqi; } /** * 获得某天前后两个节气序号 * * @return */ public static int[] getnearsolarTerm(int year, Date date) { List<JieQi> jieqi = Alljieqi(year); int[] returnValue = new int[2]; for (int i = 0; i < jieqi.size(); i++) { if (date.getTime() > jieqi.get(i).getJieQiDate().getTime()) { continue; } if (i % 2 == 0) {//只管气 returnValue[0] = i - 2; returnValue[1] = i; } else { returnValue[0] = i - 1; returnValue[1] = i + 1; } break; } return returnValue; } /** * 获得某年中所有节气Date * * @return */ public static Date[] jieqilist(int year) { Date[] returnvalue = new Date[solarTerm.length]; for (int i = 0; i < solarTerm.length; i++) { Date t = getSolarTermCalendar(year, i); returnvalue[i] = t; } return returnvalue; } private final static int[] lunarInfo = { 0x4bd8, 0x4ae0, 0xa570, 0x54d5, 0xd260, 0xd950, 0x5554, 0x56af, 0x9ad0, 0x55d2, 0x4ae0, 0xa5b6, 0xa4d0, 0xd250, 0xd295, 0xb54f, 0xd6a0, 0xada2, 0x95b0, 0x4977, 0x497f, 0xa4b0, 0xb4b5, 0x6a50, 0x6d40, 0xab54, 0x2b6f, 0x9570, 0x52f2, 0x4970, 0x6566, 0xd4a0, 0xea50, 0x6a95, 0x5adf, 0x2b60, 0x86e3, 0x92ef, 0xc8d7, 0xc95f, 0xd4a0, 0xd8a6, 0xb55f, 0x56a0, 0xa5b4, 0x25df, 0x92d0, 0xd2b2, 0xa950, 0xb557, 0x6ca0, 0xb550, 0x5355, 0x4daf, 0xa5b0, 0x4573, 0x52bf, 0xa9a8, 0xe950, 0x6aa0, 0xaea6, 0xab50, 0x4b60, 0xaae4, 0xa570, 0x5260, 0xf263, 0xd950, 0x5b57, 0x56a0, 0x96d0, 0x4dd5, 0x4ad0, 0xa4d0, 0xd4d4, 0xd250, 0xd558, 0xb540, 0xb6a0, 0x95a6, 0x95bf, 0x49b0, 0xa974, 0xa4b0, 0xb27a, 0x6a50, 0x6d40, 0xaf46, 0xab60, 0x9570, 0x4af5, 0x4970, 0x64b0, 0x74a3, 0xea50, 0x6b58, 0x5ac0, 0xab60, 0x96d5, 0x92e0, 0xc960, 0xd954, 0xd4a0, 0xda50, 0x7552, 0x56a0, 0xabb7, 0x25d0, 0x92d0, 0xcab5, 0xa950, 0xb4a0, 0xbaa4, 0xad50, 0x55d9, 0x4ba0, 0xa5b0, 0x5176, 0x52bf, 0xa930, 0x7954, 0x6aa0, 0xad50, 0x5b52, 0x4b60, 0xa6e6, 0xa4e0, 0xd260, 0xea65, 0xd530, 0x5aa0, 0x76a3, 0x96d0, 0x4afb, 0x4ad0, 0xa4d0, 0xd0b6, 0xd25f, 0xd520, 0xdd45, 0xb5a0, 0x56d0, 0x55b2, 0x49b0, 0xa577, 0xa4b0, 0xaa50, 0xb255, 0x6d2f, 0xada0, 0x4b63, 0x937f, 0x49f8, 0x4970, 0x64b0, 0x68a6, 0xea5f, 0x6b20, 0xa6c4, 0xaaef, 0x92e0, 0xd2e3, 0xc960, 0xd557, 0xd4a0, 0xda50, 0x5d55, 0x56a0, 0xa6d0, 0x55d4, 0x52d0, 0xa9b8, 0xa950, 0xb4a0, 0xb6a6, 0xad50, 0x55a0, 0xaba4, 0xa5b0, 0x52b0, 0xb273, 0x6930, 0x7337, 0x6aa0, 0xad50, 0x4b55, 0x4b6f, 0xa570, 0x54e4, 0xd260, 0xe968, 0xd520, 0xdaa0, 0x6aa6, 0x56df, 0x4ae0, 0xa9d4, 0xa4d0, 0xd150, 0xf252, 0xd520 }; private final static int[] solarTermInfo = { 0, 21208, 42467, 63836, 85337, 107014, 128867, 150921, 173149, 195551, 218072, 240693, 263343, 285989, 308563, 331033, 353350, 375494, 397447, 419210, 440795, 462224, 483532, 504758 }; public final static String[] Tianan = { "甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸" }; public final static String[] Deqi = { "子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥" }; public final static String[] Animals = { "鼠", "牛", "虎", "兔", "龙", "蛇", "马", "羊", "猴", "鸡", "狗", "猪" }; public final static String[] solarTerm = { "小寒", "大寒", "立春", "雨水", "惊蛰", "春分", "清明", "谷雨", "立夏", "小满", "芒种", "夏至", "小暑", "大暑", "立秋", "处暑", "白露", "秋分", "寒露", "霜降", "立冬", "小雪", "大雪", "冬至" }; public final static String[] lunarString1 = { "零", "一", "二", "三", "四", "五", "六", "七", "八", "九" }; public final static String[] lunarString2 = { "初", "十", "廿", "卅", "正", "腊", "冬", "闰" }; /** * 国历节日 *表示放假日 */ private final static String[] sFtv = { "0101*元旦", "0214 情人节", "0308 妇女节", "0312 植树节", "0315 消费者权益日", "0401 愚人节", "0501*劳动节", "0504 青年节", "0509 郝维节", "0512 护士节", "0601 儿童节", "0701 建党节 香港回归纪念", "0801 建军节", "0808 父亲节", "0816 燕衔泥节", "0909 毛泽东逝世纪念", "0910 教师节", "0928 孔子诞辰", "1001*国庆节", "1006 老人节", "1024 联合国日", "1111 光棍节", "1112 孙中山诞辰纪念", "1220 澳门回归纪念", "1225 圣诞节", "1226 毛泽东诞辰纪念" }; /** * 农历节日 *表示放假日 */ private final static String[] lFtv = { "0101*春节、弥勒佛诞", "0106 定光佛诞", "0115 元宵节", "0208 释迦牟尼佛出家", "0215 释迦牟尼佛涅槃", "0209 海空上师诞", "0219 观世音菩萨诞", "0221 普贤菩萨诞", "0316 准提菩萨诞", "0404 文殊菩萨诞", "0408 释迦牟尼佛诞", "0415 佛吉祥日——释迦牟尼佛诞生、成道、涅槃三期同一庆(即南传佛教国家的卫塞节)", "0505 端午节", "0513 伽蓝菩萨诞", "0603 护法韦驮尊天菩萨诞", "0619 观世音菩萨成道——此日放生、念佛,功德殊胜", "0707 七夕情人节", "0713 大势至菩萨诞", "0715 中元节", "0724 龙树菩萨诞", "0730 地藏菩萨诞", "0815 中秋节", "0822 燃灯佛诞", "0909 重阳节", "0919 观世音菩萨出家纪念日", "0930 药师琉璃光如来诞", "1005 达摩祖师诞", "1107 阿弥陀佛诞", "1208 释迦如来成道日,腊八节", "1224 小年", "1229 华严菩萨诞", "0100*除夕" }; /** * 某月的第几个星期几 */ private static String[] wFtv = { "0520 母亲节", "0716 合作节", "0730 被奴役国家周" }; private static int toInt(String str) { try { return Integer.parseInt(str); } catch (Exception e) { return -1; } } private final static Pattern sFreg = Pattern.compile("^(\\d{2})(\\d{2})([\\s\\*])(.+)$"); private final static Pattern wFreg = Pattern.compile("^(\\d{2})(\\d)(\\d)([\\s\\*])(.+)$"); private synchronized void findFestival() { int sM = this.getSolarMonth(); int sD = this.getSolarDay(); int lM = this.getLunarMonth(); int lD = this.getLunarDay(); int sy = this.getSolarYear(); Matcher m; for (int i = 0; i < Lunar.sFtv.length; i++) { m = Lunar.sFreg.matcher(Lunar.sFtv[i]); if (m.find()) { if (sM == Lunar.toInt(m.group(1)) && sD == Lunar.toInt(m.group(2))) { this.isSFestival = true; this.sFestivalName = m.group(4); if ("*".equals(m.group(3))) { this.isHoliday = true; } break; } } } for (int i = 0; i < Lunar.lFtv.length; i++) { m = Lunar.sFreg.matcher(Lunar.lFtv[i]); if (m.find()) { if (lM == Lunar.toInt(m.group(1)) && lD == Lunar.toInt(m.group(2))) { this.isLFestival = true; this.lFestivalName = m.group(4); if ("*".equals(m.group(3))) { this.isHoliday = true; } break; } } } // 月周节日 int w, d; for (int i = 0; i < Lunar.wFtv.length; i++) { m = Lunar.wFreg.matcher(Lunar.wFtv[i]); if (m.find()) { if (this.getSolarMonth() == Lunar.toInt(m.group(1))) { w = Lunar.toInt(m.group(2)); d = Lunar.toInt(m.group(3)); if (this.solar.get(Calendar.WEEK_OF_MONTH) == w && this.solar.get(Calendar.DAY_OF_WEEK) == d) { this.isSFestival = true; this.sFestivalName += "|" + m.group(5); if ("*".equals(m.group(4))) { this.isHoliday = true; } } } } } if (sy > 1874 && sy < 1909) { this.description = "光绪" + (((sy - 1874) == 1) ? "元" : "" + (sy - 1874)); } if (sy > 1908 && sy < 1912) { this.description = "宣统" + (((sy - 1908) == 1) ? "元" : String.valueOf(sy - 1908)); } if (sy > 1911 && sy < 1950) { this.description = "民国" + (((sy - 1911) == 1) ? "元" : String.valueOf(sy - 1911)); } if (sy > 1949) { this.description = "共和国" + (((sy - 1949) == 1) ? "元" : String.valueOf(sy - 1949)); } this.description += "年"; this.sFestivalName = this.sFestivalName.replaceFirst("^\\|", ""); this.isFinded = true; } private boolean isFinded = false; private boolean isSFestival = false; private boolean isLFestival = false; private String sFestivalName = ""; private String lFestivalName = ""; private String description = ""; private boolean isHoliday = false; /** * 返回农历年闰月月份 * * @param lunarYear 指定农历年份(数字) * @return 该农历年闰月的月份(数字, 没闰返回0) */ private static int getLunarLeapMonth(int lunarYear) { // 数据表中,每个农历年用16bit来表示, // 前12bit分别表示12个月份的大小月,最后4bit表示闰月 // 若4bit全为1或全为0,表示没闰, 否则4bit的值为闰月月份 int leapMonth = Lunar.lunarInfo[lunarYear - 1900] & 0xf; leapMonth = (leapMonth == 0xf ? 0 : leapMonth); return leapMonth; } /** * 返回农历年闰月的天数 * * @param lunarYear 指定农历年份(数字) * @return 该农历年闰月的天数(数字) */ private static int getLunarLeapDays(int lunarYear) { // 下一年最后4bit为1111,返回30(大月) // 下一年最后4bit不为1111,返回29(小月) // 若该年没有闰月,返回0 return Lunar.getLunarLeapMonth(lunarYear) > 0 ? ((Lunar.lunarInfo[lunarYear - 1899] & 0xf) == 0xf ? 30 : 29) : 0; } /** * 返回农历年的总天数 * * @param lunarYear 指定农历年份(数字) * @return 该农历年的总天数(数字) */ private static int getLunarYearDays(int lunarYear) { // 按小月计算,农历年最少有12 * 29 = 348天 int daysInLunarYear = 348; // 数据表中,每个农历年用16bit来表示, // 前12bit分别表示12个月份的大小月,最后4bit表示闰月 // 每个大月累加一天 for (int i = 0x8000; i > 0x8; i >>= 1) { daysInLunarYear += ((Lunar.lunarInfo[lunarYear - 1900] & i) != 0) ? 1 : 0; } // 加上闰月天数 daysInLunarYear += Lunar.getLunarLeapDays(lunarYear); return daysInLunarYear; } /** * 返回农历年正常月份的总天数 * * @param lunarYear 指定农历年份(数字) * @param lunarMonth 指定农历月份(数字) * @return 该农历年闰月的月份(数字, 没闰返回0) */ private static int getLunarMonthDays(int lunarYear, int lunarMonth) { // 数据表中,每个农历年用16bit来表示, // 前12bit分别表示12个月份的大小月,最后4bit表示闰月 int daysInLunarMonth = ((Lunar.lunarInfo[lunarYear - 1900] & (0x10000 >> lunarMonth)) != 0) ? 30 : 29; return daysInLunarMonth; } /** * 取 Date 对象中用全球标准时间 (UTC) 表示的日期 * * @param date 指定日期 * @return UTC 全球标准时间 (UTC) 表示的日期 */ public static synchronized int getUTCDay(Date date) { Lunar.makeUTCCalendar(); synchronized (utcCal) { utcCal.clear(); utcCal.setTimeInMillis(date.getTime()); return utcCal.get(Calendar.DAY_OF_MONTH); } } private static GregorianCalendar utcCal = null; private static synchronized void makeUTCCalendar() { if (Lunar.utcCal == null) { Lunar.utcCal = new GregorianCalendar(TimeZone.getTimeZone("UTC")); } } /** * 返回全球标准时间 (UTC) (或 GMT) 的 1970 年 1 月 1 日到所指定日期之间所间隔的毫秒数。 * * @param y 指定年份 * @param m 指定月份 * @param d 指定日期 * @param h 指定小时 * @param min 指定分钟 * @param sec 指定秒数 * @return 全球标准时间 (UTC) (或 GMT) 的 1970 年 1 月 1 日到所指定日期之间所间隔的毫秒数 */ public static synchronized long UTC(int y, int m, int d, int h, int min, int sec) { Lunar.makeUTCCalendar(); synchronized (utcCal) { utcCal.clear(); utcCal.set(y, m, d, h, min, sec); return utcCal.getTimeInMillis(); } } /** * 返回公历年节气的日期 * * @param solarYear 指定公历年份(数字) * @param index 指定节气序号(数字,0从小寒算起) * @return 日期(数字, 所在月份的第几天) */ private static int getSolarTermDay(int solarYear, int index) { return Lunar.getUTCDay(getSolarTermCalendar(solarYear, index)); } /** * 返回公历年节气的日期 * * @param solarYear 指定公历年份(数字) * @param index 指定节气序号(数字,0从小寒算起) * @return 日期(数字, 所在月份的第几天) */ public static Date getSolarTermCalendar(int solarYear, int index) { long l = (long) 31556925974.7 * (solarYear - 1900) + solarTermInfo[index] * 60000L; l = l + Lunar.UTC(1900, 0, 6, 2, 5, 0); return new Date(l); } private Calendar solar; private int lunarYear; private int lunarMonth; private int lunarDay; private boolean isLeap; private boolean isLeapYear; private int solarYear; private int solarMonth; private int solarDay; private int cyclicalYear = 0; private int cyclicalMonth = 0; private int cyclicalDay = 0; private int maxDayInMonth = 29; /** * 通过 Date 对象构建农历信息 * * @param date 指定日期对象 */ public Lunar(Date date) { if (date == null) { date = new Date(); } this.init(date.getTime()); } /** * 通过 TimeInMillis 构建农历信息 * * @param TimeInMillis */ public Lunar(long TimeInMillis) { this.init(TimeInMillis); } private void init(long TimeInMillis) { this.solar = Calendar.getInstance(); this.solar.setTimeInMillis(TimeInMillis); Calendar baseDate = new GregorianCalendar(1900, 0, 31); long offset = (TimeInMillis - baseDate.getTimeInMillis()) / 86400000; // 按农历年递减每年的农历天数,确定农历年份 this.lunarYear = 1900; int daysInLunarYear = Lunar.getLunarYearDays(this.lunarYear); while (this.lunarYear < 2100 && offset >= daysInLunarYear) { offset -= daysInLunarYear; daysInLunarYear = Lunar.getLunarYearDays(++this.lunarYear); } // 农历年数字 // 按农历月递减每月的农历天数,确定农历月份 int lunarMonth = 1; // 所在农历年闰哪个月,若没有返回0 int leapMonth = Lunar.getLunarLeapMonth(this.lunarYear); // 是否闰年 this.isLeapYear = leapMonth > 0; // 闰月是否递减 boolean leapDec = false; boolean isLeap = false; int daysInLunarMonth = 0; while (lunarMonth < 13 && offset > 0) { if (isLeap && leapDec) { // 如果是闰年,并且是闰月 // 所在农历年闰月的天数 daysInLunarMonth = Lunar.getLunarLeapDays(this.lunarYear); leapDec = false; } else { // 所在农历年指定月的天数 daysInLunarMonth = Lunar.getLunarMonthDays(this.lunarYear, lunarMonth); } if (offset < daysInLunarMonth) { break; } offset -= daysInLunarMonth; if (leapMonth == lunarMonth && isLeap == false) { // 下个月是闰月 leapDec = true; isLeap = true; } else { // 月份递增 lunarMonth++; } } this.maxDayInMonth = daysInLunarMonth; // 农历月数字 this.lunarMonth = lunarMonth; // 是否闰月 this.isLeap = (lunarMonth == leapMonth && isLeap); // 农历日数字 this.lunarDay = (int) offset + 1; // 取得干支历 this.getCyclicalData(); } /** * 取干支历 不是历年,历月干支,而是中国的从立春节气开始的节月,是中国的太阳十二宫,阳历的。 * */ private void getCyclicalData() { this.solarYear = this.solar.get(Calendar.YEAR); this.solarMonth = this.solar.get(Calendar.MONTH)+1; this.solarDay = this.solar.get(Calendar.DAY_OF_MONTH); // 干支历 int cyclicalYear = 0; int cyclicalMonth = 0; int cyclicalDay = 0; // 干支年 1900年立春後为庚子年(60进制36) int term2 = Lunar.getSolarTermDay(solarYear, 2); // 立春日期 // 依节气调整二月分的年柱, 以立春为界 if (solarMonth < 1 || (solarMonth == 1 && solarDay < term2)) { cyclicalYear = (solarYear - 1900 + 36 - 1) % 60; } else { cyclicalYear = (solarYear - 1900 + 36) % 60; } // 干支月 1900年1月小寒以前为 丙子月(60进制12) int firstNode = Lunar.getSolarTermDay(solarYear, solarMonth * 2); // 传回当月「节」为几日开始 // 依节气月柱, 以「节」为界 if (solarDay < firstNode) { cyclicalMonth = ((solarYear - 1900) * 12 + solarMonth + 12) % 60; } else { cyclicalMonth = ((solarYear - 1900) * 12 + solarMonth + 13) % 60; } // 当月一日与 1900/1/1 相差天数 // 1900/1/1与 1970/1/1 相差25567日, 1900/1/1 日柱为甲戌日(60进制10) cyclicalDay = (int) (Lunar.UTC(solarYear, solarMonth, solarDay, 0, 0, 0) / 86400000 + 25567 + 10) % 60; this.cyclicalYear = cyclicalYear; this.cyclicalMonth = cyclicalMonth; this.cyclicalDay = cyclicalDay; } /** * 取农历年生肖 * * @return 农历年生肖(例:龙) */ public String getAnimalString() { return Lunar.Animals[(this.lunarYear - 4) % 12]; } /** * 返回公历日期的节气字符串 * * @return 二十四节气字符串, 若不是节气日, 返回空串(例:冬至) */ public String getTermString() { // 二十四节气 String termString = ""; if (Lunar.getSolarTermDay(solarYear, solarMonth * 2) == solarDay) { termString = Lunar.solarTerm[solarMonth * 2]; } else if (Lunar.getSolarTermDay(solarYear, solarMonth * 2 + 1) == solarDay) { termString = Lunar.solarTerm[solarMonth * 2 + 1]; } return termString; } /** * 取得干支历字符串 * * @return 干支历字符串(例:甲子年甲子月甲子日) */ public String getCyclicalDateString() { return this.getCyclicaYear() + "年" + this.getCyclicaMonth() + "月" + this.getCyclicaDay() + "日"; } /** * 年份天干 * * @return 年份天干 */ public int getTiananY() { return Lunar.getTianan(this.cyclicalYear); } /** * 月份天干 * * @return 月份天干 */ public int getTiananM() { return Lunar.getTianan(this.cyclicalMonth); } /** * 日期天干 * * @return 日期天干 */ public int getTiananD() { return Lunar.getTianan(this.cyclicalDay); } /** * 年份地支 * * @return 年分地支 */ public int getDeqiY() { return Lunar.getDeqi(this.cyclicalYear); } /** * 月份地支 * * @return 月份地支 */ public int getDeqiM() { return Lunar.getDeqi(this.cyclicalMonth); } /** * 日期地支 * * @return 日期地支 */ public int getDeqiD() { return Lunar.getDeqi(this.cyclicalDay); } /** * 取得干支年字符串 * * @return 干支年字符串 */ public String getCyclicaYear() { return Lunar.getCyclicalString(this.cyclicalYear); } /** * 取得干支月字符串 * * @return 干支月字符串 */ public String getCyclicaMonth() { return Lunar.getCyclicalString(this.cyclicalMonth); } /** * 取得干支日字符串 * * @return 干支日字符串 */ public String getCyclicaDay() { return Lunar.getCyclicalString(this.cyclicalDay); } /** * 返回农历日期字符串 * * @return 农历日期字符串 */ public String getLunarDayString() { return Lunar.getLunarDayString(this.lunarDay); } /** * 返回农历日期字符串 * * @return 农历日期字符串 */ public String getLunarMonthString() { return (this.isLeap() ? "闰" : "") + Lunar.getLunarMonthString(this.lunarMonth); } /** * 返回农历日期字符串 * * @return 农历日期字符串 */ public String getLunarYearString() { return Lunar.getLunarYearString(this.lunarYear); } /** * 返回农历表示字符串 * * @return 农历字符串(例:甲子年正月初三) */ public String getLunarDateString() { return this.getLunarYearString() + "年" + this.getLunarMonthString() + "月" + this.getLunarDayString() + "日"; } /** * 农历年是否是闰月 * * @return 农历年是否是闰月 */ public boolean isLeap() { return isLeap; } /** * 农历年是否是闰年 * * @return 农历年是否是闰年 */ public boolean isLeapYear() { return isLeapYear; } /** * 当前农历月是否是大月 * * @return 当前农历月是大月 */ public boolean isBigMonth() { return this.getMaxDayInMonth() > 29; } /** * 当前农历月有多少天 * * @return 当前农历月有多少天 */ public int getMaxDayInMonth() { return this.maxDayInMonth; } /** * 农历日期 * * @return 农历日期 */ public int getLunarDay() { return lunarDay; } /** * 农历月份 * * @return 农历月份 */ public int getLunarMonth() { return lunarMonth; } /** * 农历年份 * * @return 农历年份 */ public int getLunarYear() { return lunarYear; } /** * 公历日期 * * @return 公历日期 */ public int getSolarDay() { return solarDay; } /** * 公历月份 * * @return 公历月份 (不是从0算起) */ public int getSolarMonth() { return solarMonth + 1; } /** * 公历年份 * * @return 公历年份 */ public int getSolarYear() { return solarYear; } /** * 星期几 * * @return 星期几(星期日为:1, 星期六为:7) */ public int getDayOfWeek() { return this.solar.get(Calendar.DAY_OF_WEEK); } /** * 黑色星期五 * * @return 是否黑色星期五 */ public boolean isBlackFriday() { return (this.getSolarDay() == 13 && this.solar.get(Calendar.DAY_OF_WEEK) == 6); } /** * 是否是今日 * * @return 是否是今日 */ public boolean isToday() { Calendar clr = Calendar.getInstance(); return clr.get(Calendar.YEAR) == this.solarYear && clr.get(Calendar.MONTH) == this.solarMonth && clr.get(Calendar.DAY_OF_MONTH) == this.solarDay; } /** * 取得公历节日名称 * * @return 公历节日名称, 如果不是节日返回空串 */ public String getSFestivalName() { return this.sFestivalName; } /** * 取得农历节日名称 * * @return 农历节日名称, 如果不是节日返回空串 */ public String getLFestivalName() { return this.lFestivalName; } /** * 是否是农历节日 * * @return 是否是农历节日 */ public boolean isLFestival() { if (!this.isFinded) { this.findFestival(); } return this.isLFestival; } /** * 是否是公历节日 * * @return 是否是公历节日 */ public boolean isSFestival() { if (!this.isFinded) { this.findFestival(); } return this.isSFestival; } /** * 是否是节日 * * @return 是否是节日 */ public boolean isFestival() { return this.isSFestival() || this.isLFestival(); } /** * 是否是放假日 * * @return 是否是放假日 */ public boolean isHoliday() { if (!this.isFinded) { this.findFestival(); } return this.isHoliday; } /** * 其它日期说明 * * @return 日期说明(如:民国2年) */ public String getDescription() { if (!this.isFinded) { this.findFestival(); } return this.description; } /** * 干支字符串 * * @param cyclicalNumber 指定干支位置(数字,0为甲子) * @return 干支字符串 */ private static String getCyclicalString(int cyclicalNumber) { return Lunar.Tianan[Lunar.getTianan(cyclicalNumber)] + Lunar.Deqi[Lunar.getDeqi(cyclicalNumber)]; } /** * 获得地支 * * @param cyclicalNumber * @return 地支 (数字) */ private static int getDeqi(int cyclicalNumber) { return cyclicalNumber % 12; } /** * 获得天干 * * @param cyclicalNumber * @return 天干 (数字) */ private static int getTianan(int cyclicalNumber) { return cyclicalNumber % 10; } /** * 返回指定数字的农历年份表示字符串 * * @param lunarYear 农历年份(数字,0为甲子) * @return 农历年份字符串 */ private static String getLunarYearString(int lunarYear) { return Lunar.getCyclicalString(lunarYear - 1900 + 36); } /** * 返回指定数字的农历月份表示字符串 * * @param lunarMonth 农历月份(数字) * @return 农历月份字符串 (例:正) */ private static String getLunarMonthString(int lunarMonth) { String lunarMonthString = ""; if (lunarMonth == 1) { lunarMonthString = Lunar.lunarString2[4]; } else { if (lunarMonth > 9) { lunarMonthString += Lunar.lunarString2[1]; } if (lunarMonth % 10 > 0) { lunarMonthString += Lunar.lunarString1[lunarMonth % 10]; } } return lunarMonthString; } /** * 返回指定数字的农历日表示字符串 * * @param lunarDay 农历日(数字) * @return 农历日字符串 (例: 廿一) */ private static String getLunarDayString(int lunarDay) { if (lunarDay < 1 || lunarDay > 30) { return ""; } int i1 = lunarDay / 10; int i2 = lunarDay % 10; String c1 = Lunar.lunarString2[i1]; String c2 = Lunar.lunarString1[i2]; if (lunarDay < 11) { c1 = Lunar.lunarString2[0]; } if (i2 == 0) { c2 = Lunar.lunarString2[1]; } return c1 + c2; } }
yyctz/destiny
src/main/java/com/ctz/destiny/resource/body/Lunar.java
66,233
package mapdemo1; import java.util.HashMap; import java.util.Map; /** * Map的基本方法 */ public class MyMap2 { public static void main(String[] args) { Map<String,String> map = new HashMap<>(); map.put("itheima001","小智"); map.put("itheima002","小美"); map.put("itheima003","大胖"); map.put("itheima004","小黑"); map.put("itheima005","大师"); //method1(map); //method2(map); //method3(map); //method4(map); //method5(map); //method6(map); //method7(map); } private static void method7(Map<String, String> map) { // int size() 集合的长度,也就是集合中键值对的个数 int size = map.size(); System.out.println(size); } private static void method6(Map<String, String> map) { // boolean isEmpty() 判断集合是否为空 boolean empty1 = map.isEmpty(); System.out.println(empty1);//false map.clear(); boolean empty2 = map.isEmpty(); System.out.println(empty2);//true } private static void method5(Map<String, String> map) { // boolean containsValue(Object value) 判断集合是否包含指定的值 boolean result1 = map.containsValue("aaa"); boolean result2 = map.containsValue("小智"); System.out.println(result1); System.out.println(result2); } private static void method4(Map<String, String> map) { // boolean containsKey(Object key) 判断集合是否包含指定的键 boolean result1 = map.containsKey("itheima001"); boolean result2 = map.containsKey("itheima006"); System.out.println(result1); System.out.println(result2); } private static void method3(Map<String, String> map) { // void clear() 移除所有的键值对元素 map.clear(); System.out.println(map); } private static void method2(Map<String, String> map) { // V remove(Object key) 根据键删除键值对元素 String s = map.remove("itheima001"); System.out.println(s); System.out.println(map); } private static void method1(Map<String, String> map) { // V put(K key,V value) 添加元素 //如果要添加的键不存在,那么会把键值对都添加到集合中 //如果要添加的键是存在的,那么会覆盖原先的值,把原先值当做返回值进行返回。 String s = map.put("itheima001", "aaa"); System.out.println(s); System.out.println(map); } }
fly-1-1/Distributed-framework-learning-for-Java
00basic/Collection/map/src/mapdemo1/MyMap2.java
66,234
package com.othershe.dutiltest; import android.content.Context; import android.os.Environment; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import com.othershe.baseadapter.ViewHolder; import com.othershe.baseadapter.interfaces.OnItemChildClickListener; import com.othershe.dutil.data.DownloadData; import com.othershe.dutil.db.Db; import com.othershe.dutil.download.DownloadManger; import java.util.ArrayList; import java.util.List; public class TaskManageActivity extends AppCompatActivity { private String url1 = "http://1.82.242.43/imtt.dd.qq.com/16891/DC9E925209B19E7913477E7A0CCE6E52.apk";//欢乐斗地主 private String url2 = "http://117.23.1.170/imtt.dd.qq.com/16891/37F5264B6EDC71F9A7888B5017A5A6C1.apk";//球球大作战 private String url3 = "http://117.23.1.172/imtt.dd.qq.com/16891/8AFB093FEFF9DE2A81EDC28EB1AF89C6.apk";//节奏大师 private String url4 = "http://1.82.242.43/imtt.dd.qq.com/16891/72517F996BB172A75F992962849B051A.apk";//部落冲突 private String url5 = "http://1.82.242.43/imtt.dd.qq.com/16891/1DF32C4166A703FC2AB7CCE33102123E.apk";//捕鱼达人 private String path = Environment.getExternalStorageDirectory() + "/DUtil/"; private RecyclerView downloadList; private DownloadListAdapter downloadListAdapter; private Context mContext; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_task_manage); mContext = this; // DownloadManger.getInstance(mContext).setTaskPoolSize(2, 10); downloadList = (RecyclerView) findViewById(R.id.download_list); final List<DownloadData> datas = new ArrayList<>(); if (Db.getInstance(mContext).getData(url1) != null){ datas.add(Db.getInstance(mContext).getData(url1)); }else{ datas.add(new DownloadData(url1, path, "欢乐斗地主.apk")); } if (Db.getInstance(mContext).getData(url2) != null){ datas.add(Db.getInstance(mContext).getData(url2)); }else{ datas.add(new DownloadData(url2, path, "球球大作战.apk")); } if (Db.getInstance(mContext).getData(url3) != null){ datas.add(Db.getInstance(mContext).getData(url3)); }else{ datas.add(new DownloadData(url3, path, "节奏大师.apk")); } if (Db.getInstance(mContext).getData(url4) != null){ datas.add(Db.getInstance(mContext).getData(url4)); }else{ datas.add(new DownloadData(url4, path, "部落冲突.apk")); } if (Db.getInstance(mContext).getData(url5) != null){ datas.add(Db.getInstance(mContext).getData(url5)); }else{ datas.add(new DownloadData(url5, path, "捕鱼达人.apk")); } downloadListAdapter = new DownloadListAdapter(this, datas, false); //开始 downloadListAdapter.setOnItemChildClickListener(R.id.start, new OnItemChildClickListener<DownloadData>() { @Override public void onItemChildClick(final ViewHolder viewHolder, final DownloadData data, int position) { DownloadManger.getInstance(mContext).start(data.getUrl()); } }); //暂停 downloadListAdapter.setOnItemChildClickListener(R.id.pause, new OnItemChildClickListener<DownloadData>() { @Override public void onItemChildClick(ViewHolder viewHolder, DownloadData data, int position) { DownloadManger.getInstance(mContext).pause(data.getUrl()); } }); //继续 downloadListAdapter.setOnItemChildClickListener(R.id.resume, new OnItemChildClickListener<DownloadData>() { @Override public void onItemChildClick(ViewHolder viewHolder, DownloadData data, int position) { DownloadManger.getInstance(mContext).resume(data.getUrl()); } }); //取消 downloadListAdapter.setOnItemChildClickListener(R.id.cancel, new OnItemChildClickListener<DownloadData>() { @Override public void onItemChildClick(ViewHolder viewHolder, DownloadData data, int position) { DownloadManger.getInstance(mContext).cancel(data.getUrl()); } }); //重新开始 downloadListAdapter.setOnItemChildClickListener(R.id.restart, new OnItemChildClickListener<DownloadData>() { @Override public void onItemChildClick(ViewHolder viewHolder, DownloadData data, int position) { DownloadManger.getInstance(mContext).restart(data.getUrl()); } }); final LinearLayoutManager layoutManager = new LinearLayoutManager(this); layoutManager.setOrientation(LinearLayoutManager.VERTICAL); downloadList.setLayoutManager(layoutManager); downloadList.setAdapter(downloadListAdapter); } @Override protected void onDestroy() { DownloadManger.getInstance(mContext).destroy(url1, url2, url3, url4, url5); super.onDestroy(); } }
shehuan/DUtil
app/src/main/java/com/othershe/dutiltest/TaskManageActivity.java
66,236
package com.ctz.destiny.resource.body; /** * Created by chentz on 2017/10/19. */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.text.ParseException; import java.util.Calendar; /**完整排盘系统 * * @author luozhuang 大师♂罗莊 */ public class LuozhuangPaipanClass { LuozhuangshenshaHehun myLuozhuangshenshaHehun = new LuozhuangshenshaHehun(); Luozhuanglvhehun myLuozhuanglvhehun = new Luozhuanglvhehun(); Luozhuangpaipandayun myLuozhuangpaipandayun = new Luozhuangpaipandayun(); LuozhuangshengSha myLuozhuangshengSha = new LuozhuangshengSha(); luozhuangpaipanshisheng myluozhuangpaipanshisheng = new luozhuangpaipanshisheng(); Luozhuangdizhang myLuozhuangdizhang = new Luozhuangdizhang(); /** * * @param man 生日 yyyy-MM-dd HH * @return * @throws ParseException */ public String paipan(String man, Sex isman) throws ParseException { Calendar mancal; try { mancal = myLuozhuangshenshaHehun.getCalendarfromString(man, "yyyy-MM-dd HH"); //原来的private 方法改了下 } catch (ParseException ex) { return "输入不正确" + ex.getMessage(); } return paipan(mancal, isman); } public String paipan(Calendar cal, Sex isman) throws ParseException { BaZi lunar = new BaZi(cal); Lunar lunaryue = new Lunar(cal.getTime()); System.out.println("此人农历的日期【" + lunar.toString() + "】"); /** * 子时23:00-1:00,丑时1.00-3.00,寅时3.00-5.00,卯时5.00-7.00, * 辰时7.00-9.00,巳时9.00-11.00,午时11.00-13.00,未时13.00-15.00 * 申时15.00-17.00,酉时17.00-19.00,戌时19.00-21.00,亥时21.00-23.00 * */ int time = (cal.get(Calendar.HOUR_OF_DAY)+25)%24/ 2; //获取生肖 System.out.println("此人的农历生肖【" + lunar.animalsYear() + "】"); String GanZhi = lunar.getYearGanZhi(time);//取八字 String[] tempchar = GanZhi.split(","); //我修改原来的,用,分割 String ganziyear = tempchar[0];//年柱 String ganzimonth = tempchar[1];//月柱 String ganziday = tempchar[2];//日柱 String ganzitime = tempchar[3];//时柱 System.out.println("此人八字【" + GanZhi + "】"); String[] arrayOfString = new String[9]; arrayOfString[0] = ""; arrayOfString[1] = ganziyear.substring(0, 1);//年干 arrayOfString[2] = ganziyear.substring(1, 2);//年支 arrayOfString[3] = ganzimonth.substring(0, 1);//月干 arrayOfString[4] = ganzimonth.substring(1, 2);//月支 arrayOfString[5] = ganziday.substring(0, 1);//日干 arrayOfString[6] = ganziday.substring(1, 2);//日支 arrayOfString[7] = ganzitime.substring(0, 1);//时干 arrayOfString[8] = ganzitime.substring(1, 2);//时支 System.out.println(myLuozhuangshengSha.shengsha(arrayOfString, isman)); //排食神生旺死绝 //用日干 日支分别查找位于表的对应值 //修改原文的类方法字段属性为public //我的表格均是按照顺序比如 //十天干生旺死绝表 十神概念按顺序排列 //查找某一行就可以查到对应值 String[] shengsibiao = {"甲", "丙", "戊", "庚", "壬", "乙", "丁", "己", "辛", "癸"};//十天干生旺死绝表顺序 //十天干生旺死绝表 用日干查表 int shengsibiaoshunxu = myLuozhuangpaipandayun.getyuezhuStart(shengsibiao, ganziday.substring(0, 1)); //十神表按顺序 int shishengbiaoshunxu = myLuozhuangpaipandayun.getyuezhuStart(BaZi.Gan, ganziday.substring(0, 1)); shengsibiaoshunxu++; shishengbiaoshunxu++; String[] DayunArray = myLuozhuangpaipandayun.Dayun(ganziyear, ganzimonth, isman); //排此人四柱十神生旺死绝 // 比    印    日元   劫   <- 这里直接用四柱干支计算  //乾造  庚    己    庚    辛 //    辰    卯    午    巳     //藏干  乙戊癸  乙    己丁   庚丙戊  <- 这里直接用藏干计算 //    才枭伤  才    印官   比杀枭  <- 这里直接用藏干计算 //地势  养    胎    沐浴   长生   <- 藏干不算生旺死绝 //纳音  白蜡金  城墙土  路旁土  白蜡金 System.out.println("此人四柱干支十神"); System.out.print(myluozhuangpaipanshisheng.shisheng[shishengbiaoshunxu][myLuozhuangpaipandayun.getyuezhuStart(myluozhuangpaipanshisheng.shisheng[0], ganziyear.substring(0, 1))]); //十神表 用支查表 System.out.print(" "); System.out.print(myluozhuangpaipanshisheng.shisheng[shishengbiaoshunxu][myLuozhuangpaipandayun.getyuezhuStart(myluozhuangpaipanshisheng.shisheng[0], ganzimonth.substring(0, 1))]); //十神表 用支查表 System.out.print(" "); System.out.print("日主"); //日柱不计算! System.out.print(" "); System.out.print(myluozhuangpaipanshisheng.shisheng[shishengbiaoshunxu][myLuozhuangpaipandayun.getyuezhuStart(myluozhuangpaipanshisheng.shisheng[0], ganzitime.substring(0, 1))]); //十神表 用支查表 System.out.println(""); System.out.println("此人年藏干"); String[] zhanggan = LuozhuangcommonClass.dizhuang(ganziyear.substring(1, 2)); for (int i = 0; i < zhanggan.length; i++) { if (zhanggan[i] == null) { continue; } System.out.print(zhanggan[i]); System.out.print(" "); System.out.print(myluozhuangpaipanshisheng.shisheng[shishengbiaoshunxu][myLuozhuangpaipandayun.getyuezhuStart(myluozhuangpaipanshisheng.shisheng[0], zhanggan[i])]); //十神表 用支查表 System.out.print(" "); } System.out.println(""); zhanggan = LuozhuangcommonClass.dizhuang(ganzimonth.substring(1, 2)); System.out.println("此人月藏干"); for (int i = 0; i < zhanggan.length; i++) { if (zhanggan[i] == null) { continue; } System.out.print(zhanggan[i]); System.out.print(" "); System.out.print(myluozhuangpaipanshisheng.shisheng[shishengbiaoshunxu][myLuozhuangpaipandayun.getyuezhuStart(myluozhuangpaipanshisheng.shisheng[0], zhanggan[i])]); //十神表 用支查表 System.out.print(" "); } System.out.println(""); System.out.println("此人日藏干"); zhanggan = LuozhuangcommonClass.dizhuang(ganziday.substring(1, 2)); for (int i = 0; i < zhanggan.length; i++) { if (zhanggan[i] == null) { continue; } System.out.print(zhanggan[i]); System.out.print(" "); System.out.print(myluozhuangpaipanshisheng.shisheng[shishengbiaoshunxu][myLuozhuangpaipandayun.getyuezhuStart(myluozhuangpaipanshisheng.shisheng[0], zhanggan[i])]); //十神表 用支查表 System.out.print(" "); } System.out.println(""); System.out.println("此人时藏干"); zhanggan = LuozhuangcommonClass.dizhuang(ganzitime.substring(1, 2)); for (int i = 0; i < zhanggan.length; i++) { if (zhanggan[i] == null) { continue; } System.out.print(zhanggan[i]); System.out.print(" "); System.out.print(myluozhuangpaipanshisheng.shisheng[shishengbiaoshunxu][myLuozhuangpaipandayun.getyuezhuStart(myluozhuangpaipanshisheng.shisheng[0], zhanggan[i])]); //十神表 用支查表 System.out.print(" "); } String[] DayunArrayshengsi = new String[DayunArray.length];//大运十天干生旺死绝表 String[] DayunArrayshisheng = new String[DayunArray.length];//大运十神表 for (int i = 0; i < DayunArray.length; i++) { DayunArrayshengsi[i] = myluozhuangpaipanshisheng.shengwang[0][myLuozhuangpaipandayun.getyuezhuStart(myluozhuangpaipanshisheng.shengwang[shengsibiaoshunxu], DayunArray[i].substring(1, 2))]; //十天干生旺死绝表 用干查表 DayunArrayshisheng[i] = myluozhuangpaipanshisheng.shisheng[shishengbiaoshunxu][myLuozhuangpaipandayun.getyuezhuStart(myluozhuangpaipanshisheng.shisheng[0], DayunArray[i].substring(0, 1))]; //十神表 用支查表 } System.out.println("此人大运"); myLuozhuangpaipandayun.pringst(DayunArray); System.out.println("此人起大运日期:"); System.out.println(myLuozhuangdizhang.dayunkaishi(cal, ganziyear.substring(0,1), isman)+ "岁"); System.out.println("此人大运生旺死绝"); myLuozhuangpaipandayun.pringst(DayunArrayshengsi); System.out.println("此人大运十神"); myLuozhuangpaipandayun.pringst(DayunArrayshisheng); String[] DayunArrayshengsha = new String[DayunArray.length]; for (int i = 0; i < DayunArray.length; i++) { DayunArrayshengsha[i] = myLuozhuangshengSha.shengshadayun(DayunArray[i], arrayOfString, isman); } System.out.println("此人大运神煞"); myLuozhuangpaipandayun.pringst(DayunArrayshengsha); System.out.println("此人流年"); int[] liunianarray = new int[80]; int start = lunar.getnumberYear(); start++; for (int i = 0; i < liunianarray.length; i++) { liunianarray[i] = start + i; } myLuozhuangpaipandayun.pringst(myLuozhuangshengSha.liunianshensha(liunianarray, arrayOfString, isman)); System.out.println("此人婚姻神煞:"); LuozhuangshenshaHehun myLuozhuangshenshaHehun = new LuozhuangshenshaHehun(); System.out.println(myLuozhuangshenshaHehun.shensha(cal)); return null; } /** * @param args the command line arguments */ public static void main(String[] args) throws ParseException, IOException { LuozhuangPaipanClass my = new LuozhuangPaipanClass(); System.out.println("请输入你的年月日时间类似 2013-3-14 20"); BufferedReader strin = new BufferedReader(new InputStreamReader(System.in)); String a = "1995-6-12 15"; System.out.println("输入的是:" + a); my.paipan(a, Sex.MAN); } }
yyctz/destiny
src/main/java/com/ctz/destiny/resource/body/LuozhuangPaipanClass.java
66,237
package cn.edu.jxnu.awesome_campus.model.jxnugo; import java.util.List; /** * Created by zpauly on 16-5-14. */ public class PublishGoodsBean { /** * body : 二手笔记本,成色非常好,见鲁大师,见鲁大师二手笔记本,成色非常好,见鲁大师,见鲁大师二手笔记本,成色非常好,见鲁大师,见鲁大师二手笔记本, * goodsName : 戴尔灵越5537 * goodsNum : 1 * goodsPrice : 2000 * goodsLocation : 一栋N204 * goodsQuality : 7成新 * goodsBuyTime : 2014年6月 * goodsTag : 1 * contact : 13361640744 * photos : [{"key":"84BE7838-E41C-4E60-A1B8-CA95DBEE326B"},{"key":"84BE7838-E41C-4E60-A1B8-CA95DBEE326B"},{"key":"84BE7838-E41C-4E60-A1B8-CA95DBEE326B"}] */ private String userId; private String body; private String goodsName; private int goodsNum; private float goodsPrice; private String goodsLocation; private String goodsQuality; private String goodsBuyTime; private int goodsTag; private String contact; private String auth_token; /** * key : 84BE7838-E41C-4E60-A1B8-CA95DBEE326B */ private List<PhotokeyBean> photos; public PublishGoodsBean(String userId, String body, String goodsName, int goodsNum, float goodsPrice , String goodsLocation, String goodsQuality, String goodsBuyTime , int goodsTag, String contact, List<PhotokeyBean> photos,String auth_token) { this.userId=userId; this.body = body; this.goodsName = goodsName; this.goodsNum = goodsNum; this.goodsPrice = goodsPrice; this.goodsLocation = goodsLocation; this.goodsQuality = goodsQuality; this.goodsBuyTime = goodsBuyTime; this.goodsTag = goodsTag; this.contact = contact; this.photos = photos; this.auth_token=auth_token; } public String getBody() { return body; } public void setBody(String body) { this.body = body; } public String getAuth_token() { return auth_token; } public void setAuth_token(String auth_token) { this.auth_token = auth_token; } public String getGoodsName() { return goodsName; } public void setGoodsName(String goodsName) { this.goodsName = goodsName; } public int getGoodsNum() { return goodsNum; } public void setGoodsNum(int goodsNum) { this.goodsNum = goodsNum; } public float getGoodsPrice() { return goodsPrice; } public void setGoodsPrice(float goodsPrice) { this.goodsPrice = goodsPrice; } public String getGoodsLocation() { return goodsLocation; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public void setGoodsLocation(String goodsLocation) { this.goodsLocation = goodsLocation; } public String getGoodsQuality() { return goodsQuality; } public void setGoodsQuality(String goodsQuality) { this.goodsQuality = goodsQuality; } public String getGoodsBuyTime() { return goodsBuyTime; } public void setGoodsBuyTime(String goodsBuyTime) { this.goodsBuyTime = goodsBuyTime; } public int getGoodsTag() { return goodsTag; } public void setGoodsTag(int goodsTag) { this.goodsTag = goodsTag; } public String getContact() { return contact; } public void setContact(String contact) { this.contact = contact; } public List<PhotokeyBean> getPhotos() { return photos; } public void setPhotos(List<PhotokeyBean> photos) { this.photos = photos; } }
MummyDing/Awesome-Campus
app/src/main/java/cn/edu/jxnu/awesome_campus/model/jxnugo/PublishGoodsBean.java
66,238
/* * * Copyright (C) 2020 iQIYI (www.iqiyi.com) * * 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.qiyi.lens.ui.viewinfo; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.DashPathEffect; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Rect; import android.graphics.RectF; import android.view.View; import android.view.ViewGroup; import androidx.core.graphics.ColorUtils; import com.qiyi.lens.utils.UIUtils; import static com.qiyi.lens.utils.UIUtils.dp2px; import static com.qiyi.lens.utils.UIUtils.sp2px; public class DrawKit { private final static int TEXT_DIMENSION_COLOR = Color.BLUE; private final static int CURRENT_WIDGET_COLOR = 0x30ea2020; private final static int SIBLING_WIDGET_COLOR = 0xff81f503; private final static int DEBUG_INFO_BG = 0x33242424; private final static int RELATIVE_WIDGET_COLOR = SIBLING_WIDGET_COLOR; protected Paint textPaint = new Paint(); Paint textBgPaint = new Paint(); private Paint selectedPaint = new Paint(); private Paint borderPaint = new Paint(); private Path borderPath = new Path(); private Paint dashLinePaint = new Paint(); private Path dashLinePath = new Path(); private Context mContext; private int savedColor; int screenWidth; int screenHeight; private TextReallocation allocation; private Widget currentWidget, relativeWidget; private int mDisplayOffset; private int textLineDistance; private int halfEndPointWidth; int textBgFillingSpace; public DrawKit(Context context, TextReallocation textReallocation) { mContext = context; allocation = textReallocation; screenWidth = allocation._swd; screenHeight = allocation._sht; } void init() { textPaint.setAntiAlias(true); textPaint.setTextSize(sp2px(getContext(), 10)); textPaint.setColor(Color.RED); textPaint.setStrokeWidth(dp2px(getContext(), 1)); textBgPaint.setAntiAlias(true); textBgPaint.setColor(Color.WHITE); textBgPaint.setStrokeJoin(Paint.Join.ROUND); selectedPaint.setAntiAlias(true); selectedPaint.setColor(0x30000000); borderPaint.setAntiAlias(true); borderPaint.setColor(0xff000000); borderPaint.setStyle(Paint.Style.STROKE); borderPaint.setStrokeWidth(dp2px(getContext(), 1)); dashLinePaint = new Paint(); dashLinePaint.setAntiAlias(true); dashLinePaint.setColor(0x90FF0000); dashLinePaint.setStyle(Paint.Style.STROKE); dashLinePaint.setPathEffect(new DashPathEffect(new float[]{dp2px(getContext(), 4), dp2px(getContext(), 8)}, 0)); textLineDistance = dp2px(getContext(), 5); halfEndPointWidth = dp2px(getContext(), 2.5f); textBgFillingSpace = dp2px(getContext(), 2); } Context getContext() { return mContext; } void pushColor(int color) { savedColor = textPaint.getColor(); textPaint.setColor(color); } void popColor() { textPaint.setColor(savedColor); } public void draw(Canvas canvas, Widget currentWidget, Widget relativeWidget, boolean showRelativePosition , boolean showSibling) { this.currentWidget = currentWidget; this.relativeWidget = relativeWidget; allocation.clear(); drawWidgetArea(canvas, showRelativePosition); if (showRelativePosition) { //[展示相对距离] drawRelativePosition(canvas); } if (showSibling) { //[绘制兄弟节点] drawSibling(canvas); } if (!showRelativePosition) { displayViewInfo(canvas); } //[draw debug info] if (currentWidget != null) { currentWidget.draw(canvas); } allocation.draw(canvas); this.currentWidget = null; this.relativeWidget = null; } private void drawWidgetArea(Canvas canvas, boolean showRelativePosition) { if (showRelativePosition && relativeWidget != null) { borderPath.reset(); borderPath.addRect(new RectF(relativeWidget.getOriginRect()), Path.Direction.CW); borderPaint.setColor(RELATIVE_WIDGET_COLOR); canvas.drawPath(borderPath, borderPaint); selectedPaint.setColor(ColorUtils.setAlphaComponent(RELATIVE_WIDGET_COLOR, 48)); canvas.drawRect(relativeWidget.getRect(), selectedPaint); } if (currentWidget != null) { selectedPaint.setColor(CURRENT_WIDGET_COLOR); canvas.drawRect(currentWidget.getRect(), selectedPaint); RectF innerRect = new RectF(currentWidget.getRect()); //[draw wd & ht] pushColor(TEXT_DIMENSION_COLOR); drawDimension(canvas, innerRect, textPaint); popColor(); View view = currentWidget.getView(); innerRect.left = innerRect.left + view.getPaddingLeft(); innerRect.bottom = innerRect.bottom - view.getPaddingBottom(); innerRect.right = innerRect.right - view.getPaddingRight(); innerRect.top = innerRect.top + view.getPaddingTop(); if (view.getPaddingLeft() != 0 && view.getPaddingRight() != 0 && view.getPaddingTop() != 0 && view.getPaddingBottom() != 0) { borderPath.reset(); borderPath.addRect(new RectF(innerRect), Path.Direction.CW); int contrastColor = ColorUtils.setAlphaComponent( getContrastColor(CURRENT_WIDGET_COLOR), 255); borderPaint.setColor(contrastColor); canvas.drawPath(borderPath, borderPaint); } borderPath.reset(); borderPaint.setColor( ColorUtils.setAlphaComponent(CURRENT_WIDGET_COLOR, 255)); borderPath.addRect(new RectF(currentWidget.getOriginRect()), Path.Direction.CW); canvas.drawPath(borderPath, borderPaint); } } void drawArea(Canvas canvas, RectF rect, int color) { int cl = borderPaint.getColor(); borderPath.reset(); borderPath.addRect(new RectF(rect), Path.Direction.CW); int contrastColor = ColorUtils.setAlphaComponent( getContrastColor(color), 255); borderPaint.setColor(contrastColor); canvas.drawPath(borderPath, borderPaint); borderPaint.setColor(cl); } private void drawSibling(Canvas canvas) { if (currentWidget == null) return; Widget parent = currentWidget.getParent(); if (parent == null) return; ViewGroup viewGroup = (ViewGroup) parent.getView(); for (int i = 0; i < viewGroup.getChildCount(); i++) { Widget child = new Widget(this, viewGroup.getChildAt(i), mDisplayOffset); if (child.equals(currentWidget)) continue; borderPaint.setColor( ColorUtils.setAlphaComponent(SIBLING_WIDGET_COLOR, 255)); canvas.drawRect(child.getRect(), borderPaint); } } private void drawRelativePosition(Canvas canvas) { boolean doubleNotNull = true; Widget[] selectedWidgets = new Widget[]{currentWidget, relativeWidget}; for (Widget widget : selectedWidgets) { if (widget != null) { RectF rect = widget.getRect(); drawDashLine(canvas, 0, rect.top, screenWidth, rect.top); drawDashLine(canvas, 0, rect.bottom, screenWidth, rect.bottom); drawDashLine(canvas, rect.left, 0, rect.left, screenHeight); drawDashLine(canvas, rect.right, 0, rect.right, screenHeight); } else { doubleNotNull = false; } } if (doubleNotNull) { RectF firstRect = currentWidget.getRect(); // A RectF secondRect = relativeWidget.getRect(); //B drawDistance(canvas, firstRect, secondRect); } } void drawDistance(Canvas canvas, RectF firstRect, RectF secondRect) { boolean drawn = false; if (secondRect.top > firstRect.bottom) { // A/B drawn = true; float x = secondRect.left + secondRect.width() / 2; drawLineWithText(canvas, x, firstRect.bottom, x, secondRect.top); } if (firstRect.top > secondRect.bottom) {//B/A drawn = true; float x = secondRect.left + secondRect.width() / 2; drawLineWithText(canvas, x, secondRect.bottom, x, firstRect.top); } if (secondRect.left > firstRect.right) {//A/B drawn = true; float y = secondRect.top + secondRect.height() / 2; drawLineWithText(canvas, secondRect.left, y, firstRect.right, y); } if (firstRect.left > secondRect.right) {//B/A drawn = true; float y = secondRect.top + secondRect.height() / 2; drawLineWithText(canvas, secondRect.right, y, firstRect.left, y); } drawn |= drawNestedAreaLine(canvas, firstRect, secondRect); if (!drawn) { drawn = drawNestedAreaLine(canvas, secondRect, firstRect); } if (!drawn) { drawNoLimited(canvas, secondRect, firstRect); } } private void drawDashLine(Canvas canvas, float startX, float startY, float endX, float endY) { dashLinePath.reset(); dashLinePath.moveTo(startX, startY); dashLinePath.lineTo(endX, endY); canvas.drawPath(dashLinePath, dashLinePaint); } private boolean drawNestedAreaLine(Canvas canvas, RectF firstRect, RectF secondRect) { if (secondRect.left >= firstRect.left && secondRect.right <= firstRect.right && secondRect.top >= firstRect.top && secondRect.bottom <= firstRect.bottom) { drawLineWithText(canvas, secondRect.left, secondRect.top + secondRect.height() / 2, firstRect.left, secondRect.top + secondRect.height() / 2); drawLineWithText(canvas, secondRect.right, secondRect.top + secondRect.height() / 2, firstRect.right, secondRect.top + secondRect.height() / 2); drawLineWithText(canvas, secondRect.left + secondRect.width() / 2, secondRect.top, secondRect.left + secondRect.width() / 2, firstRect.top); drawLineWithText(canvas, secondRect.left + secondRect.width() / 2, secondRect.bottom, secondRect.left + secondRect.width() / 2, firstRect.bottom); return true; } return false; } private void drawNoLimited(Canvas canvas, RectF firstRect, RectF secondRect) { drawLineWithText(canvas, secondRect.left, secondRect.top + secondRect.height() / 2, firstRect.left, secondRect.top + secondRect.height() / 2); drawLineWithText(canvas, secondRect.right, secondRect.top + secondRect.height() / 2, firstRect.right, secondRect.top + secondRect.height() / 2); drawLineWithText(canvas, secondRect.left + secondRect.width() / 2, secondRect.top, secondRect.left + secondRect.width() / 2, firstRect.top); drawLineWithText(canvas, secondRect.left + secondRect.width() / 2, secondRect.bottom, secondRect.left + secondRect.width() / 2, firstRect.bottom); } private void drawLineWithText(Canvas canvas, float startX, float startY, float endX, float endY, float endPointSpace) { if (startX == endX && startY == endY) { return; } if (startX > endX) { float tempX = startX; startX = endX; endX = tempX; } if (startY > endY) { float tempY = startY; startY = endY; endY = tempY; } if (startX == endX) {//[draw on y] drawLineWithEndPoint(canvas, startX, startY + endPointSpace, endX, endY - endPointSpace); String text = UIUtils.autoSize(getContext(), endY - startY); TextInfo info = new TextInfo(this, textPaint, text); int textWidth = (int) getTextWidth(text); info.setRange(startX - textWidth, endX + textWidth, startY, endY); float x = startX + textLineDistance; float y = startY + (endY - startY) / 2 + getTextHeight(text) / 2; allocation.measure(info, x, y); // drawText(canvas, text, x, y); } else if (startY == endY) {//draw on x drawLineWithEndPoint(canvas, startX + endPointSpace, startY, endX - endPointSpace, endY); String text = UIUtils.autoSize(getContext(), endX - startX); TextInfo info = new TextInfo(this, textPaint, text); int textHeight = (int) getTextHeight(text); info.setRange(startX, endX, startY - textHeight, endY + textHeight); float x = startX + (endX - startX) / 2 - getTextWidth(text) / 2; float y = startY - textLineDistance; allocation.measure(info, x, y); // drawText(canvas, text, startX + (endX - startX) / 2 - getTextWidth(text) / 2, startY - textLineDistance); } } protected void drawText(Canvas canvas, String text, float x, float y) { float left = x - textBgFillingSpace; float top = y - getTextHeight(text); float right = x + getTextWidth(text) + textBgFillingSpace; float bottom = y + textBgFillingSpace; // ensure text in screen bound if (left < 0) { right -= left; left = 0; } if (top < 0) { bottom -= top; top = 0; } if (bottom > screenHeight) { float diff = top - bottom; bottom = screenHeight; top = bottom + diff; } if (right > screenWidth) { float diff = left - right; right = screenWidth; left = right + diff; } canvas.drawRect(left, top, right, bottom, textBgPaint); canvas.drawText(text, left + textBgFillingSpace, bottom - textBgFillingSpace, textPaint); } private void drawLineWithEndPoint(Canvas canvas, float startX, float startY, float endX, float endY) { canvas.drawLine(startX, startY, endX, endY, textPaint); if (startX == endX) { canvas.drawLine(startX - halfEndPointWidth, startY, endX + halfEndPointWidth, startY, textPaint); canvas.drawLine(startX - halfEndPointWidth, endY, endX + halfEndPointWidth, endY, textPaint); } else if (startY == endY) { canvas.drawLine(startX, startY - halfEndPointWidth, startX, endY + halfEndPointWidth, textPaint); canvas.drawLine(endX, startY - halfEndPointWidth, endX, endY + halfEndPointWidth, textPaint); } } private void drawLineWithText(Canvas canvas, float startX, float startY, float endX, float endY) { drawLineWithText(canvas, startX, startY, endX, endY, 0); } private float getTextHeight(String text) { Rect rect = new Rect(); textPaint.getTextBounds(text, 0, text.length(), rect); return rect.height(); } private float getTextWidth(String text) { return textPaint.measureText(text); } private int getContrastColor(int sourceColor) { return Color.rgb(255 - Color.red(sourceColor), 255 - Color.green(sourceColor), 255 - Color.blue(sourceColor)); } private void drawDimension(Canvas canvas, RectF rect, Paint paint) { String wds = "wd: " + UIUtils.autoSize(getContext(), rect.width()); String hts = "ht: " + UIUtils.autoSize(getContext(), rect.height()); int padding = 10; float twd = paint.measureText(wds); float tht = paint.measureText(hts); float x; //[避免都在中间展示不下] x = rect.left; TextInfo info = new TextInfo(this, textPaint, wds); if (x + twd > screenWidth) { x = screenWidth - twd - mDisplayOffset; } Paint.FontMetrics metrics = paint.getFontMetrics(); float height = metrics.bottom - metrics.top; float y; if (rect.top - height - padding > mDisplayOffset) { y = rect.top - padding; } else { y = rect.bottom + padding; } //在整个宽度范围上可以移动 info.setRange(rect.left, rect.right, y - height, y + height); allocation.measure(info, x, y); // drawText(canvas, wds, x, y); //[draw ht] if (rect.right + tht + padding < screenWidth) { //[draw at right ] x = rect.right + padding; } else if (rect.left - tht - padding > 0) { x = (int) (rect.left - tht - padding); } else { x = rect.left + padding; } y = rect.top + height; //(rect.height() - height)/2 + rect.top; info = new TextInfo(this, textPaint, hts); info.setRange(x - twd, x + twd, rect.top, rect.bottom); allocation.measure(info, x, y); // drawText(canvas, hts, x, y); } /** * 绘制原则: 如果可以在视图内部区域展示,就展示到内部, 否则展示到外部合适地方 * * @param viewRect : 当前视图的VisibleRect 信心 * @message: 需要绘制的文案 */ void drawDebugInfo(Canvas canvas, String message, RectF viewRect) { MultiTextInfo info = new MultiTextInfo(this, textPaint, message); info.setRange(0, screenWidth, 0, screenHeight); allocation.measure(info, viewRect.left, viewRect.top); } private void displayViewInfo(Canvas canvas) { } void updateOffset(int offset) { mDisplayOffset = offset; } }
iqiyi/Lens
lenssdk/src/main/java/com/qiyi/lens/ui/viewinfo/DrawKit.java
66,239
package com.gpmall.commons.tool.email; import com.gpmall.commons.tool.email.emailConfig.EmailConfig; import com.gpmall.commons.tool.email.freeMarker.FreeMarkerUtil; import jodd.util.ArraysUtil; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import javax.activation.DataHandler; import javax.activation.FileDataSource; import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import java.io.File; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.Vector; /** * Administrator * 2019/8/26 0026 * 14:39 * 默认的邮件发送器 */ @Component public class DefaultEmailSender extends AbstractEmailSender { @Autowired EmailConfig emailConfig; /** * 在初始化的基础上修改Properties */ @Override public void initProperties(MailData mailData) throws Exception { if(mailData.getToAddresss() == null || mailData.getToAddresss().isEmpty()){ mailData.setToAddresss(emailConfig.getToAddresss()); } if(!StringUtils.isNoneBlank(mailData.getContent())){ mailData.setContent(emailConfig.getContent()); } if(!StringUtils.isNoneBlank(mailData.getSubject())){ mailData.setSubject(emailConfig.getSubject()); } if(mailData.getAttachFileNames() == null || mailData.getAttachFileNames().isEmpty()){ mailData.setAttachFileNames(mailData.getAttachFileNames()); } //emailConfig.setAttachFileNames(null); } @Override public void doSend(MailData mailData)throws Exception { /**创建一个邮件的会话**/ Authenticator authenticator = null; if (emailConfig.isMailSmtpAuth()) {//如果需要身份认证,则创建一个密码验证器 authenticator = new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(emailConfig.getUsername(),emailConfig.getPassword()); } }; } Session session = Session.getDefaultInstance(emailConfig.getProperties(),authenticator); /**创建邮件信心**/ Message message = new MimeMessage(session); //发送地址 message.setFrom(new InternetAddress(emailConfig.getFromAddress())); //发送邮件给自己,解决发送邮件554的问题 message.addRecipients(Message.RecipientType.CC ,new Address[]{new InternetAddress(emailConfig.getFromAddress())}); //接收地址 message.addRecipients(Message.RecipientType.TO ,mailData.getToInternetAddress()); //抄送地址 message.addRecipients(Message.RecipientType.CC ,mailData.getCcInternetAddress()); //邮件主题 message.setSubject(mailData.getSubject()); //邮件内容 message.setText(mailData.getContent()); //发送时间 message.setSentDate(new Date()); //发送邮件 Transport.send(message); } @Override public void doHtmlSend(MailData mailData) throws Exception { /**创建一个邮件的会话**/ Authenticator authenticator = null; if (emailConfig.isMailSmtpAuth()) {//如果需要身份认证,则创建一个密码验证器 authenticator = new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(emailConfig.getUsername(),emailConfig.getPassword()); } }; } Session session = Session.getDefaultInstance(emailConfig.getProperties(),authenticator); /**创建邮件信心**/ Message message = new MimeMessage(session); //发送地址 message.setFrom(new InternetAddress(emailConfig.getFromAddress())); //发送邮件给自己,解决发送邮件554的问题 message.addRecipients(Message.RecipientType.CC ,new Address[]{new InternetAddress(emailConfig.getFromAddress())}); //接收地址 message.addRecipients(Message.RecipientType.TO ,mailData.getToInternetAddress()); //抄送地址 message.addRecipients(Message.RecipientType.CC ,mailData.getCcInternetAddress()); //邮件主题 message.setSubject(mailData.getSubject()); //邮件内容 Multipart multipart = new MimeMultipart(); BodyPart bodyPart = new MimeBodyPart(); bodyPart.setContent(mailData.getContent(),mailData.getContent_type()); multipart.addBodyPart(bodyPart); message.setContent(multipart); message.setSentDate(new Date()); //发送邮件 Transport.send(message); } @Override public void doSendWithAttachFile(MailData mailData) throws Exception { /**创建一个邮件的会话**/ Authenticator authenticator = null; if (emailConfig.isMailSmtpAuth()) {//如果需要身份认证,则创建一个密码验证器 authenticator = new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(emailConfig.getUsername(),emailConfig.getPassword()); } }; } Session session = Session.getDefaultInstance(emailConfig.getProperties(),authenticator); /**创建邮件信心**/ Message message = new MimeMessage(session); //发送地址 message.setFrom(new InternetAddress(emailConfig.getFromAddress())); //发送邮件给自己,解决发送邮件554的问题 message.addRecipients(Message.RecipientType.CC ,new Address[]{new InternetAddress(emailConfig.getFromAddress())}); //接收地址 message.addRecipients(Message.RecipientType.TO ,mailData.getToInternetAddress()); //抄送地址 message.addRecipients(Message.RecipientType.CC ,mailData.getCcInternetAddress()); //邮件主题 message.setSubject(mailData.getSubject()); //邮件内容 Multipart multipart = new MimeMultipart(); BodyPart bodyPart= new MimeBodyPart(); ((MimeBodyPart) bodyPart).setText(mailData.getContent()); //添加文本类容 multipart.addBodyPart(bodyPart); //添加附件 Vector<String> files = mailData.getAttachFileNames(); if(files != null && files.size()>0){ files.forEach(filePath->{ MimeBodyPart bodyPartFile = new MimeBodyPart(); try { File file = new File(filePath); bodyPartFile.attachFile(file); bodyPartFile.setFileName(file.getName()); //bodyPartFile.setDataHandler(new DataHandler(new FileDataSource(file))); multipart.addBodyPart(bodyPartFile); } catch (IOException e) { e.printStackTrace(); } catch (MessagingException e) { e.printStackTrace(); } }); } message.setContent(multipart); message.setSentDate(new Date()); //发送邮件 Transport.send(message); } @Override public void doSendHtmlMailUseTemplate(MailData mailData) throws Exception { /**创建一个邮件的会话**/ Authenticator authenticator = null; if (emailConfig.isMailSmtpAuth()) {//如果需要身份认证,则创建一个密码验证器 authenticator = new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(emailConfig.getUsername(),emailConfig.getPassword()); } }; } Session session = Session.getDefaultInstance(emailConfig.getProperties(),authenticator); /**创建邮件信心**/ Message message = new MimeMessage(session); //发送地址 message.setFrom(new InternetAddress(emailConfig.getFromAddress())); //发送邮件给自己,解决发送邮件554的问题 message.addRecipients(Message.RecipientType.CC ,new Address[]{new InternetAddress(emailConfig.getFromAddress())}); //接收地址 message.addRecipients(Message.RecipientType.TO ,mailData.getToInternetAddress()); //抄送地址 message.addRecipients(Message.RecipientType.CC ,mailData.getCcInternetAddress()); //邮件主题 message.setSubject(mailData.getSubject()); //邮件内容 Multipart multipart = new MimeMultipart(); BodyPart bodyPart = new MimeBodyPart(); String content = FreeMarkerUtil.getMailTextForTemplate(emailConfig.getTemplatePath(),mailData.getFileName(),mailData.getDataMap()); bodyPart.setContent(content,mailData.getContent_type()); multipart.addBodyPart(bodyPart); message.setContent(multipart); message.setSentDate(new Date()); //发送邮件 Transport.send(message); } }
2227324689/gpmall
gpmall-commons/commons-tool/src/main/java/com/gpmall/commons/tool/email/DefaultEmailSender.java
66,241
package com.alipay.api.domain; import com.alipay.api.AlipayObject; import com.alipay.api.internal.mapping.ApiField; /** * 虚拟商品订单扩展信心 * * @author auto create * @since 1.0, 2022-09-29 16:37:37 */ public class VirtualItemOrderExtInfo extends AlipayObject { private static final long serialVersionUID = 4831647532773546232L; /** * 小程序appId */ @ApiField("notify_app_id") private String notifyAppId; public String getNotifyAppId() { return this.notifyAppId; } public void setNotifyAppId(String notifyAppId) { this.notifyAppId = notifyAppId; } }
alipay/alipay-sdk-java-all
v2/src/main/java/com/alipay/api/domain/VirtualItemOrderExtInfo.java
66,242
package com.glc.itbook; import androidx.appcompat.app.AppCompatActivity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.Volley; import org.json.JSONException; import org.json.JSONObject; public class LoginActivity extends AppCompatActivity { private EditText login_username; private EditText login_password; private Button btn_login; private Button btnRegister; private SharedPreferences sharedPreferences; @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); //透明状态栏           getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION); btnRegister = findViewById(R.id.btn_registerActivity); login_username = findViewById(R.id.edt_login_username); login_password = findViewById(R.id.edt_login_password); btn_login = findViewById(R.id.btn_login); sharedPreferences =getSharedPreferences("data",Context.MODE_PRIVATE); String userstr= sharedPreferences.getString("username",""); String phonestr= sharedPreferences.getString("phone",""); if(userstr.equals("")){ }else { Intent intent = new Intent(LoginActivity.this, MenuActivity.class); intent.putExtra("username", userstr); intent.putExtra("phone", phonestr); startActivity(intent); } Intent intent = getIntent(); final String username1 = intent.getStringExtra("username1"); login_username.setText(username1); btn_login.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String usernameStr = login_username.getText().toString().trim(); String passwordStr = login_password.getText().toString().trim(); if (usernameStr.equals("") || passwordStr.equals("")) { Toast.makeText(LoginActivity.this, "用户名密码不能为空", Toast.LENGTH_SHORT).show(); } else { JSONObject jsonObject = new JSONObject(); try { jsonObject.put("username", usernameStr); jsonObject.put("password", passwordStr); } catch (JSONException e) { e.printStackTrace(); } String url = "http://192.168.1.103:8085/user/login"; RequestQueue requestQueue = Volley.newRequestQueue(LoginActivity.this); JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, jsonObject, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject jsonObject) { try { Log.d("信心", jsonObject.toString()); String msg = jsonObject.getString("msg"); Log.d("msg", msg); if (msg.equals("登录成功")) { JSONObject detail = jsonObject.getJSONObject("detail"); String username = detail.getString("username"); String phone = detail.getString("phone"); sharedPreferences=getSharedPreferences("data",Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString("username",username); editor.putString("phone",phone); editor.commit(); Intent intent = new Intent(LoginActivity.this, MenuActivity.class); intent.putExtra("username", username); intent.putExtra("phone", phone); startActivity(intent); } else if (msg.equals("用户名或密码错误")) { Toast.makeText(LoginActivity.this, "用户名密码有误", Toast.LENGTH_SHORT).show(); } } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) { Toast.makeText(LoginActivity.this, "网络出错", Toast.LENGTH_SHORT).show(); } }); requestQueue.add(jsonObjectRequest); } } }); btnRegister.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { startActivity(new Intent(LoginActivity.this, RegistActivity.class)); } }); } }
GAOli-cong/ITBookDemo-springboot-android
ItBook/app/src/main/java/com/glc/itbook/LoginActivity.java
66,243
package io; import java.io.*; /** * 文件字节输出流 * 1、创建源 * 2、选择流 * 3、操作(读) * 4、释放资源 * @Author created by barrett in 2020/5/15 22:24 */ public class WriteDemo { public static void main(String[] args) { test1(); } static void test1(){ //创建源 File dest = new File("dest.txt"); Writer os=null; try { //选择流 os = new FileWriter(dest); String str = "it is so sasy! 信心、耐心"; //操作(写):字符串->字节数组(编码的过程) //方式一 // char[] c = str.toCharArray(); // os.write(c,0,c.length); //方式二 // os.write(str); //方式三 os.append(str).append("我是后来居上"); os.flush(); } catch (Exception e) { e.printStackTrace(); }finally { //释放资源 if(os != null) { try { os.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
tanyicheng/javathinking4
src/main/0study/io/WriteDemo.java
66,246
package org.openokr.manage.vo; import com.zzheng.framework.base.vo.BaseVO; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; public class ObjectivesVO extends BaseVO implements Serializable { private static final long serialVersionUID = 1L; /** * 主键 */ private String id; /** * 时间段id */ private String timeSessionId; /** * 名称 */ private String name; /** * 描述 */ private String description; /** * 负责人id */ private String ownerId; /** * 父目标 */ private String parentId; /** * 信心指数 */ private String confidenceLevel; /** * 公开类型 1-公开 2-团队公开 3-保密 */ private String visibility; /** * 类型 1-个人 2-团队 3-公司 */ private String type; /** * 确认状态 1.未提交,2.待确认,3.已确认,4.被驳回 */ private String status; /** * 删除标识 0-否 1-是 */ private String delFlag; /** * 当前进度(百分比) */ private BigDecimal progress; /** * 评分(季度结束的时候要对O的完成情况进行评分和自评) */ private String score; /** * 评分说明(季度结束的时候要对O的完成情况进行评分和自评) */ private String assessment; /** * 创建时间 */ private Date createTs; /** * 创建者 */ private String createUserId; /** * 更新时间 */ private Date updateTs; /** * 更新者 */ private String updateUserId; /** * 团队ID(type为团队和公司的时候才存储) */ private String teamId; /** * 排序 */ private Integer sort; /** * 主键 */ public String getId() { return id; } /** * 主键 */ public void setId(String id) { this.id = id; } /** * 时间段id */ public String getTimeSessionId() { return timeSessionId; } /** * 时间段id */ public void setTimeSessionId(String timeSessionId) { this.timeSessionId = timeSessionId; } /** * 名称 */ public String getName() { return name; } /** * 名称 */ public void setName(String name) { this.name = name; } /** * 描述 */ public String getDescription() { return description; } /** * 描述 */ public void setDescription(String description) { this.description = description; } /** * 负责人id */ public String getOwnerId() { return ownerId; } /** * 负责人id */ public void setOwnerId(String ownerId) { this.ownerId = ownerId; } /** * 父目标 */ public String getParentId() { return parentId; } /** * 父目标 */ public void setParentId(String parentId) { this.parentId = parentId; } /** * 信心指数 */ public String getConfidenceLevel() { return confidenceLevel; } /** * 信心指数 */ public void setConfidenceLevel(String confidenceLevel) { this.confidenceLevel = confidenceLevel; } /** * 公开类型 1-公开 2-团队公开 3-保密 */ public String getVisibility() { return visibility; } /** * 公开类型 1-公开 2-团队公开 3-保密 */ public void setVisibility(String visibility) { this.visibility = visibility; } /** * 类型 1-个人 2-团队 3-公司 */ public String getType() { return type; } /** * 类型 1-个人 2-团队 3-公司 */ public void setType(String type) { this.type = type; } /** * 确认状态 1.未提交,2.待确认,3.已确认,4.被驳回 */ public String getStatus() { return status; } /** * 确认状态 1.未提交,2.待确认,3.已确认,4.被驳回 */ public void setStatus(String status) { this.status = status; } /** * 删除标识 0-否 1-是 */ public String getDelFlag() { return delFlag; } /** * 删除标识 0-否 1-是 */ public void setDelFlag(String delFlag) { this.delFlag = delFlag; } /** * 当前进度(百分比) */ public BigDecimal getProgress() { return progress; } /** * 当前进度(百分比) */ public void setProgress(BigDecimal progress) { this.progress = progress; } /** * 评分(季度结束的时候要对O的完成情况进行评分和自评) */ public String getScore() { return score; } /** * 评分(季度结束的时候要对O的完成情况进行评分和自评) */ public void setScore(String score) { this.score = score; } /** * 评分说明(季度结束的时候要对O的完成情况进行评分和自评) */ public String getAssessment() { return assessment; } /** * 评分说明(季度结束的时候要对O的完成情况进行评分和自评) */ public void setAssessment(String assessment) { this.assessment = assessment; } /** * 创建时间 */ public Date getCreateTs() { return createTs; } /** * 创建时间 */ public void setCreateTs(Date createTs) { this.createTs = createTs; } /** * 创建者 */ public String getCreateUserId() { return createUserId; } /** * 创建者 */ public void setCreateUserId(String createUserId) { this.createUserId = createUserId; } /** * 更新时间 */ public Date getUpdateTs() { return updateTs; } /** * 更新时间 */ public void setUpdateTs(Date updateTs) { this.updateTs = updateTs; } /** * 更新者 */ public String getUpdateUserId() { return updateUserId; } /** * 更新者 */ public void setUpdateUserId(String updateUserId) { this.updateUserId = updateUserId; } /** * 团队ID(type为团队和公司的时候才存储) */ public String getTeamId() { return teamId; } /** * 团队ID(type为团队和公司的时候才存储) */ public void setTeamId(String teamId) { this.teamId = teamId; } /** * 排序 */ public Integer getSort() { return sort; } /** * 排序 */ public void setSort(Integer sort) { this.sort = sort; } }
OpenOKR/OpenOKR
okr-api/src/main/java/org/openokr/manage/vo/ObjectivesVO.java
66,247
/* * Copyright (C) 2006 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 android.view; import android.util.Pools.SynchronizedPool; /** * Helper for tracking the velocity of touch events, for implementing * flinging and other such gestures. * * Use {@link #obtain} to retrieve a new instance of the class when you are going * to begin tracking. Put the motion events you receive into it with * {@link #addMovement(MotionEvent)}. When you want to determine the velocity call * {@link #computeCurrentVelocity(int)} and then call {@link #getXVelocity(int)} * and {@link #getYVelocity(int)} to retrieve the velocity for each pointer id. */ public final class VelocityTracker { private static final SynchronizedPool<VelocityTracker> sPool = new SynchronizedPool<VelocityTracker>(2); private static final int ACTIVE_POINTER_ID = -1; private long mPtr; private final String mStrategy; /** * Retrieve a new VelocityTracker object to watch the velocity of a * motion. Be sure to call {@link #recycle} when done. You should * generally only maintain an active object while tracking a movement, * so that the VelocityTracker can be re-used elsewhere. * * @return Returns a new VelocityTracker. */ static public VelocityTracker obtain() { VelocityTracker instance = sPool.acquire(); return (instance != null) ? instance : new VelocityTracker(null); } /** * Obtains a velocity tracker with the specified strategy. * For testing and comparison 比较 purposes only. * * @param strategy The strategy, or null to use the default. * @return The velocity tracker. * * @hide */ public static VelocityTracker obtain(String strategy) { if (strategy == null) { return obtain(); } return new VelocityTracker(strategy); } /** * Return a VelocityTracker object back to be re-used by others. You must * not touch the object after calling this function. */ public void recycle() { if (mStrategy == null) { clear(); sPool.release(this); } } private VelocityTracker(String strategy) { mPtr = nativeInitialize(strategy); mStrategy = strategy; } @Override protected void finalize() throws Throwable { try { if (mPtr != 0) { nativeDispose(mPtr); mPtr = 0; } } finally { super.finalize(); } } /** * Reset the velocity tracker back to its initial state. */ public void clear() { nativeClear(mPtr); } /** * Add a user's movement to the tracker. You should call this for the * initial {@link MotionEvent#ACTION_DOWN}, the following * {@link MotionEvent#ACTION_MOVE} events that you receive, and the * final {@link MotionEvent#ACTION_UP}. You can, however, call this * for whichever events you desire. * * @param event The MotionEvent you received and would like to track. */ public void addMovement(MotionEvent event) { if (event == null) { throw new IllegalArgumentException("event must not be null"); } nativeAddMovement(mPtr, event); } /** * Equivalent to invoking {@link #computeCurrentVelocity(int, float)} with a maximum * velocity of Float.MAX_VALUE. * * @see #computeCurrentVelocity(int, float) */ public void computeCurrentVelocity(int units) { nativeComputeCurrentVelocity(mPtr, units, Float.MAX_VALUE); } /** * Compute the current velocity based on the points that have been * collected. Only call this when you actually want to retrieve velocity * information, as it is relatively expensive. You can then retrieve * the velocity with {@link #getXVelocity()} and * {@link #getYVelocity()}. * * @param units The units you would like the velocity in. A value of 1 * provides pixels per millisecond, 1000 provides pixels per second, etc. * @param maxVelocity The maximum velocity that can be computed by this method. * This value must be declared in the same unit as the units parameter. This value * must be positive. */ public void computeCurrentVelocity(int units, float maxVelocity) { nativeComputeCurrentVelocity(mPtr, units, maxVelocity); } /** * Retrieve the last computed X velocity. You must first call * {@link #computeCurrentVelocity(int)} before calling this function. * * @return The previously computed X velocity. */ public float getXVelocity() { return nativeGetXVelocity(mPtr, ACTIVE_POINTER_ID); } /** * Retrieve the last computed Y velocity. You must first call * {@link #computeCurrentVelocity(int)} before calling this function. * * @return The previously computed Y velocity. */ public float getYVelocity() { return nativeGetYVelocity(mPtr, ACTIVE_POINTER_ID); } /** * Retrieve the last computed X velocity. You must first call * {@link #computeCurrentVelocity(int)} before calling this function. * * @param id Which pointer's velocity to return. * @return The previously computed X velocity. */ public float getXVelocity(int id) { return nativeGetXVelocity(mPtr, id); } /** * Retrieve the last computed Y velocity. You must first call * {@link #computeCurrentVelocity(int)} before calling this function. * * @param id Which pointer's velocity to return. * @return The previously computed Y velocity. */ public float getYVelocity(int id) { return nativeGetYVelocity(mPtr, id); } /** * Get an estimator 估计量 for the movements of a pointer using past movements of the * pointer to predict 预测 future movements. * * It is not necessary to call {@link #computeCurrentVelocity(int)} before calling * this method. * * @param id Which pointer's velocity to return. * @param outEstimator The estimator to populate. * @return True if an estimator was obtained, false if there is no information * available about the pointer. * * @hide For internal use only. Not a final API. */ public boolean getEstimator(int id, Estimator outEstimator) { if (outEstimator == null) { throw new IllegalArgumentException("outEstimator must not be null"); } return nativeGetEstimator(mPtr, id, outEstimator); } /** * An estimator 估计量 for the movements of a pointer based on a polynomial 多项式 model. * * The last recorded position of the pointer is at time zero seconds. * Past estimated positions are at negative times and future estimated positions * are at positive times. * * First coefficient 系数 is position (in pixels), second is velocity (in pixels per second), * third is acceleration (in pixels per second squared). * * @hide For internal use only. Not a final API. */ public static final class Estimator { // Must match VelocityTracker::Estimator::MAX_DEGREE 程度 private static final int MAX_DEGREE = 4; /** * Polynomial 多项式 coefficients 系数 describing motion in X. */ public final float[] xCoeff = new float[MAX_DEGREE + 1]; /** * Polynomial coefficients describing motion in Y. */ public final float[] yCoeff = new float[MAX_DEGREE + 1]; /** * Polynomial degree, or zero if only position information is available. */ public int degree; /** * Confidence 信心;信任;秘密 (coefficient 系数 of determination 决心;果断;测定 ), between 0 (no fit) and 1 (perfect fit). */ public float confidence; /** * Gets an estimate of the X position of the pointer at the specified time point. * @param time The time point in seconds, 0 is the last recorded time. * @return The estimated X coordinate. */ public float estimateX(float time) { return estimate(time, xCoeff); } /** * Gets an estimate of the Y position of the pointer at the specified time point. * @param time The time point in seconds, 0 is the last recorded time. * @return The estimated Y coordinate. */ public float estimateY(float time) { return estimate(time, yCoeff); } /** * Gets the X coefficient 系数 with the specified index. * @param index The index of the coefficient to return. * @return The X coefficient, or 0 if the index is greater than the degree. */ public float getXCoeff(int index) { return index <= degree ? xCoeff[index] : 0; } /** * Gets the Y coefficient with the specified index. * @param index The index of the coefficient to return. * @return The Y coefficient, or 0 if the index is greater than the degree. */ public float getYCoeff(int index) { return index <= degree ? yCoeff[index] : 0; } private float estimate(float time, float[] c) { float a = 0; float scale = 1; for (int i = 0; i <= degree; i++) { // coeff[0] + coff[1] * time + coeff[2] * time * time + coeff[3] * time * time * time a += c[i] * scale; scale *= time; } return a; } } private static native long nativeInitialize(String strategy); private static native void nativeDispose(long ptr); private static native void nativeClear(long ptr); private static native void nativeAddMovement(long ptr, MotionEvent event); private static native void nativeComputeCurrentVelocity(long ptr, int units, float maxVelocity); private static native float nativeGetXVelocity(long ptr, int id); private static native float nativeGetYVelocity(long ptr, int id); private static native boolean nativeGetEstimator(long ptr, int id, Estimator outEstimator); }
fengyunmars/android-24
android/view/VelocityTracker.java
66,248
package 编程练习赛19; import java.util.Scanner; public class 自信心 { public static void main(String[] args) { Scanner in = new Scanner(System.in); while (in.hasNext()) { int T = in.nextInt(); for(int t = 0; t < T; t++){ int N = in.nextInt(); int[][]A = new int[N][5]; for(int i = 0; i < N; i++){ for(int j = 0; j < 5; j++){ A[i][j] = in.nextInt(); } } } } } }
vNKB7/hihoCoder
src/编程练习赛19/自信心.java
66,250
package com.apis.okre.util; import java.util.HashMap; import java.util.Map; import org.springframework.http.HttpStatus; public class Constants { public static final String WRONG_PASSWORD = "密码错误"; // HttpStatus.NON_AUTHORITATIVE_INFORMATION 203 public static final String NOT_FOUND_PHONE = "用用户电话找不到用户"; // HttpStatus.NOT_FOUND 404 public static final String NOT_FOUND_EMAIL = "用用户email找不到用户"; // HttpStatus.NOT_FOUND 404 public static final String PHONE_DUPLICATED = "电话号码重复"; // HttpStatus.CONFLICT 409 public static final String NOT_FOUND = "未找到"; // HttpStatus.NOT_FOUND 404 public static final String ADD_USER_SUCCESSFULLY = "添加用户成功"; public static final String BAD_REQUEST = "错误的请求"; // HttpStatus.BAD_REQUEST 400 public static final String UPDATE_FAILED = "更新失败"; // HttpStatus.BAD_REQUEST 400 public static final String DELETE_FAILED = "删除失败"; // HttpStatus.BAD_REQUEST 400 public static final String INSERT_FAILED = "插入失败"; // HttpStatus.BAD_REQUEST 400 public static final String UPDATE_SUCCESSFULLY = "更新成功"; public static final String INSERT_SUCCESSFULLY = "插入成功"; public static final String DELETE_SUCCESSFULLY = "删除成功"; public static final String SEARCH_SUCCESSFULLY = "搜索成功"; public static final String VALIDATION_ERROR= "验证错误"; public static final String HEALTH_COMMENT = "API 运行良好"; public static final String DB_HEALTH_COMMENT = "数据库连接不起作用"; public static final String UPDATE_PARENT_OBJECT_FAILED = "您不能将此目标设置为父目标。"; public static final String PERMISSION_FAILED = "您无权这样做。"; // HttpStatus.BAD_REQUEST 400 public static final int tb_department = 5; public static final int tb_intercom = 6; public static final int tb_item = 3; public static final int tb_kanban = 12; public static final int tb_kr = 1; public static final int tb_milestone = 13; public static final int tb_object = 0; public static final int tb_operating = 7; public static final int tb_progress = 8; public static final int tb_report = 4; public static final int tb_review = 9; public static final int tb_review_problem = 11; public static final int tb_tag = 14; public static final int tb_task = 2; public static final int tb_unit = 15; public static final int tb_user = 10; public static final int tb_task_intercom = 16; public static final int tb_item_intercom = 17; public static final int tb_e_report = 18; public static final int tb_share_ta = 19; public static final int tb_work_summary = 20; public static final int tb_dongtai = 21; public static Map<String, String> NAME_MAP; static { NAME_MAP = new HashMap<>(); NAME_MAP.put("krobject", "目标"); NAME_MAP.put("ob_name", "目标的名称"); NAME_MAP.put("ob_owner", ""); NAME_MAP.put("ob_creator", ""); NAME_MAP.put("ob_cycle", "目标的周期"); NAME_MAP.put("ob_start_date", "目标的开始日"); NAME_MAP.put("ob_end_date", "目标的终止日"); NAME_MAP.put("ob_company_id", ""); NAME_MAP.put("ob_parent_object", ""); NAME_MAP.put("ob_status", ""); NAME_MAP.put("ob_progress", "目标完成度"); NAME_MAP.put("ob_auto_progress", ""); NAME_MAP.put("ob_visible_type", ""); NAME_MAP.put("ob_visible_range", ""); NAME_MAP.put("ob_participant", ""); NAME_MAP.put("ob_attention", ""); NAME_MAP.put("ob_score", "目标评分"); NAME_MAP.put("ob_mstatus", ""); NAME_MAP.put("kr", "关键结果"); NAME_MAP.put("kr_name", "关键成果的名称"); NAME_MAP.put("kr_owner", ""); NAME_MAP.put("kr_creator", ""); NAME_MAP.put("kr_parent_object", ""); NAME_MAP.put("kr_completion", "关键成果的进度"); NAME_MAP.put("kr_confidence", "信心"); NAME_MAP.put("kr_score", "评分"); NAME_MAP.put("kr_order", ""); NAME_MAP.put("kr_score_description", ""); NAME_MAP.put("kr_ta", ""); NAME_MAP.put("kr_rate", ""); NAME_MAP.put("kr_start_date", ""); NAME_MAP.put("kr_end_date", ""); NAME_MAP.put("task", "任务"); NAME_MAP.put("task_name", "任务的名称"); NAME_MAP.put("task_status", ""); NAME_MAP.put("task_start_date", "起时间"); NAME_MAP.put("task_end_date", "止时间"); NAME_MAP.put("task_complete_date", ""); NAME_MAP.put("task_priority", "任务的优先"); NAME_MAP.put("task_description", "任务描述与备注"); NAME_MAP.put("task_target_price", "任务的目标值"); NAME_MAP.put("task_unit", ""); NAME_MAP.put("task_real_price", "任务的实际值"); NAME_MAP.put("task_feedback_time", "反馈时间"); NAME_MAP.put("task_est_worktime", ""); NAME_MAP.put("task_creator", ""); NAME_MAP.put("task_owner", ""); NAME_MAP.put("task_approver", ""); NAME_MAP.put("task_collaborator", ""); NAME_MAP.put("task_parent_object", ""); NAME_MAP.put("task_parent_kr", ""); NAME_MAP.put("task_parent_item", ""); NAME_MAP.put("task_parent_review", ""); NAME_MAP.put("task_parent_task", ""); NAME_MAP.put("task_refer", ""); NAME_MAP.put("task_visible_type", ""); NAME_MAP.put("task_visible_range", ""); NAME_MAP.put("task_uploaded_files", ""); NAME_MAP.put("task_order", ""); NAME_MAP.put("task_vice_leader", ""); NAME_MAP.put("task_progress", "任务的进度"); NAME_MAP.put("item", "项目"); NAME_MAP.put("item_name", "项目的名称"); NAME_MAP.put("item_progress", "项目的进度"); NAME_MAP.put("item_start_date", "起时间"); NAME_MAP.put("item_end_date", "止时间"); NAME_MAP.put("item_owner", ""); NAME_MAP.put("item_creator", ""); NAME_MAP.put("item_parent_object", ""); NAME_MAP.put("item_parent_kr", ""); NAME_MAP.put("item_participant", ""); NAME_MAP.put("item_followers", ""); NAME_MAP.put("item_approver", ""); NAME_MAP.put("item_description", ""); NAME_MAP.put("item_visible_range", ""); NAME_MAP.put("item_company_id", ""); NAME_MAP.put("item_tag", ""); NAME_MAP.put("item_uploaded_file", ""); NAME_MAP.put("item_status", ""); NAME_MAP.put("item_mstatus", ""); NAME_MAP.put("milestone", "里程碑"); NAME_MAP.put("ms_name", "里程碑的名称"); NAME_MAP.put("ms_description", "里程碑的描述"); NAME_MAP.put("ms_progress", "里程碑的进度"); NAME_MAP.put("ms_start_date", "起时间"); NAME_MAP.put("ms_end_date", "止时间"); NAME_MAP.put("ms_owner", ""); NAME_MAP.put("ms_parent_item", ""); NAME_MAP.put("ms_task", ""); NAME_MAP.put("kanban", "看板"); NAME_MAP.put("kb_name", "看板的名称"); NAME_MAP.put("kb_order", ""); NAME_MAP.put("kb_parent_item", ""); NAME_MAP.put("kb_task", ""); NAME_MAP.put("report", "日报"); NAME_MAP.put("rp_date", "日报日期"); NAME_MAP.put("rp_type", ""); NAME_MAP.put("rp_abstract", "总结与障碍"); NAME_MAP.put("rp_todo", "下一步工作安排"); NAME_MAP.put("rp_attatch_files", ""); NAME_MAP.put("rp_visible_range", ""); NAME_MAP.put("rp_ta_contacts", ""); NAME_MAP.put("rp_send_check", ""); NAME_MAP.put("rp_publish_type", ""); NAME_MAP.put("rp_creator", ""); NAME_MAP.put("rp_tag", ""); NAME_MAP.put("rp_progress_tasks", ""); NAME_MAP.put("rp_expired_tasks", ""); NAME_MAP.put("rp_completed_tasks", ""); } // --------------- Kresult Operating ----------------- public static final String UPDATE_KRESULT_RECORD = "更新了%s为 \"%s\" "; public static final String ADD_KRESULT_RECORD = "创建了名为 \"%s\" 的关键结果"; public static final String DEL_KRESULT_RECORD = "删除了名为 %s 的关键结果"; // -------------Object Operating------------------- public static final String UPDATE_OBJECT_RECORD = "更新了%s为 %s "; public static final String ADD_OBJECT_RECORD = "创建了名为 \"%s\" 的目标"; public static final String DEL_OBJECT_RECORD = "删除了名为 %s 的目标"; // -------------Operating------------------- public static final String UPDATE_RECORD = "更新了%s为 %s "; public static final String ADD_RECORD = "创建了名为 \"%s\" 的%s"; public static final String DEL_RECORD = "删除了名为 %s 的%s"; // -------------Operating------------------- public static final String UPDATE_DREPORT = "修改了日报"; public static final String ADD_DREPORT= "提交了日报"; public static final String DEL_DREPORT = "删除了日报"; public static final String UPDATE_WREPORT = "修改了周报"; public static final String ADD_WREPORT= "提交了周报"; public static final String DEL_WREPORT = "删除了周报"; public static final String UPDATE_MREPORT = "修改了月报"; public static final String ADD_MREPORT= "提交了月报"; public static final String DEL_MREPORT = "删除了月报"; // --------------Validation--------------------- public static final String VALID_OBJECT_NAME = "目标名称必须存在"; public static final String VALID_VISIBLE_TYPE= "可见范围必须存在"; public static final String VALID_OBJECT_OWNER = "负责人必须存在"; public static final String VALID_OBJECT_CYCLE = "周期必须存在"; }
TopDeveloper51/okr-backend
src/main/java/com/apis/okre/util/Constants.java
66,251
/* * The MIT License * * Copyright 2019 The OpenNARS authors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package nars.entity; import nars.inference.TruthFunctions; import nars.io.Symbols; import nars.language.Term; import nars.storage.Memory; /** * A Sentence is an abstract class, mainly containing a Term, a TruthValue, and * a Stamp. * <p> * It is used as the premises and conclusions of all inference rules. */ public class Sentence implements Cloneable { private boolean temporalInduction = false; /** * The content of a Sentence is a Term */ private Term content; /** * The punctuation also indicates the type of the Sentence: Judgment, * Question, or Goal */ private char punctuation; /** * The truth value of Judgment */ private TruthValue truth; /** * Partial record of the derivation path */ private Stamp stamp; /** * Whether the sentence can be revised */ private boolean revisible; private boolean observable; /** * Create a Sentence with the given fields * * @param content The Term that forms the content of the sentence * @param punctuation The punctuation indicating the type of the sentence * @param truth The truth value of the sentence, null for question * @param stamp The stamp of the sentence indicating its derivation time and * base */ public Sentence(Term content, char punctuation, TruthValue truth, Stamp stamp) { this.content = content; this.content.renameVariables(); this.punctuation = punctuation; this.truth = truth; this.stamp = stamp; this.revisible = true; observable = false; } /** * Create a Sentence with the given fields * * @param content The Term that forms the content of the sentence * @param punctuation The punctuation indicating the type of the sentence * @param truth The truth value of the sentence, null for question * @param stamp The stamp of the sentence indicating its derivation time and * base * @param revisible Whether the sentence can be revised */ public Sentence(Term content, char punctuation, TruthValue truth, Stamp stamp, boolean revisible) { this.content = content; this.content.renameVariables(); this.punctuation = punctuation; this.truth = truth; this.stamp = stamp; this.revisible = revisible; observable = false; } public boolean getObservable(){ return observable; } public void setObservable(boolean observable){ this.observable = observable; } /** * To check whether two sentences are equal * * @param that The other sentence * @return Whether the two sentences have the same content */ @Override public boolean equals(Object that) { if (that instanceof Sentence) { Sentence t = (Sentence) that; return content.equals(t.getContent()) && punctuation == t.getPunctuation() && truth.equals(t.getTruth()) && stamp.equals(t.getStamp()); } return false; } public int getTemporalOrder(){ return content.getTemporalOrder(); } public long getOccurrenceTime(){ return stamp.getOccurrenceTime(); } public boolean getTemporalInduction(){ return temporalInduction; } public void setTemporalInduction(boolean temporalIndution){ this.temporalInduction = temporalInduction; } /** * To produce the hashcode of a sentence * * @return A hashcode */ @Override public int hashCode() { int hash = 5; hash = 67 * hash + (this.content != null ? this.content.hashCode() : 0); hash = 67 * hash + this.punctuation; hash = 67 * hash + (this.truth != null ? this.truth.hashCode() : 0); hash = 67 * hash + (this.stamp != null ? this.stamp.hashCode() : 0); return hash; } /** * Check whether the judgment is equivalent to another one * <p> * The two may have different keys * * @param that The other judgment * @return Whether the two are equivalent */ public boolean equivalentTo(Sentence that) { assert content.equals(that.getContent()) && punctuation == that.getPunctuation(); return (truth.equals(that.getTruth()) && stamp.equals(that.getStamp())); } /** * Clone the Sentence * * @return The clone */ @Override public Sentence clone() { if (truth == null) { return new Sentence((Term) content.clone(), punctuation, null, (Stamp) stamp.clone()); } return new Sentence((Term) content.clone(), punctuation, new TruthValue(truth), (Stamp) stamp.clone(), revisible); } /** * Get the content of the sentence * * @return The content Term */ public Term getContent() { return content; } /** * Get the punctuation of the sentence * * @return The character '.' or '?' */ public char getPunctuation() { return punctuation; } /** * Clone the content of the sentence * * @return A clone of the content Term */ public Term cloneContent() { return (Term) content.clone(); } /** * Set the content Term of the Sentence * * @param t The new content */ public void setContent(Term t) { content = t; } /** * Get the truth value of the sentence * * @return Truth value, null for question */ public TruthValue getTruth() { return truth; } /** * Get the stamp of the sentence * * @return The stamp */ public Stamp getStamp() { return stamp; } public void setStamp(Stamp s) { stamp = s; } /** * Distinguish Judgment from Goal ("instanceof Judgment" doesn't work) * * @return Whether the object is a Judgment */ public boolean isJudgment() { return (punctuation == Symbols.JUDGMENT_MARK); } /** * Distinguish Question from Quest ("instanceof Question" doesn't work) * * @return Whether the object is a Question */ public boolean isQuestion() { return (punctuation == Symbols.QUESTION_MARK); } public boolean isQuest(){ return (punctuation == Symbols.QUEST_MARK); } public boolean isGoal(){ return (punctuation == Symbols.GOAL_MARK); } public boolean containQueryVar() { return (content.getName().indexOf(Symbols.VAR_QUERY) >= 0); } public boolean getRevisible() { return revisible; } public void setRevisible(boolean b) { revisible = b; } /** * Get a String representation of the sentence * * @return The String */ @Override public String toString() { StringBuilder s = new StringBuilder(); s.append(content.toString()); s.append(punctuation).append(" "); if (truth != null) { s.append(truth.toString()); } s.append(stamp.toString()); return s.toString(); } /** * Get a String representation of the sentence, with 2-digit accuracy * * @return The String */ public String toStringBrief() { return toKey() + stamp.toString(); } public String toStringBrief(String tense){ return toKey(tense) + stamp.toString(); } /** * Get a String representation of the sentence for key of Task and TaskLink * * @return The String */ public String toKey() { StringBuilder s = new StringBuilder(); s.append(content.toString()); s.append(punctuation).append(" "); if (truth != null) { s.append(truth.toStringBrief()); } return s.toString(); } public String toKey(String tense){ StringBuilder s = new StringBuilder(); s.append(content.toString()); s.append(punctuation).append(" "); s.append(tense).append(" "); if (truth != null) { s.append(truth.toStringBrief()); } return s.toString(); } public boolean isEternal(){ return stamp.isEternal(); } /** * 将一个语句投影到另一个目标时间,如果所要投影的时间为永恒 * 那么语句将从事件变为永恒 * @param targetTime * @param currentTime * @param memory * @return */ public Sentence projection(long targetTime, long currentTime, Memory memory){ TruthValue newTruth = projectionTruth(targetTime, currentTime, memory); boolean eternalizing = newTruth.isEternal(); Stamp newStamp = new Stamp(stamp); if(eternalizing) newStamp.setOccurrenceTime(Stamp.ETERNAL); else newStamp.setOccurrenceTime(targetTime); return new Sentence(content, punctuation, newTruth, newStamp, false); } /** * 投影真值,将一个真值按照给定的目标事件进行投影 * @param targetTime * @param currentTime * @param memory * @return */ public TruthValue projectionTruth(long targetTime, long currentTime, Memory memory){ TruthValue newTruth = null; // 如果当前时间戳不是永恒的 if(!stamp.isEternal()){ // 先永恒化当前的真值 newTruth = TruthFunctions.eternalize(truth); if(targetTime != Stamp.ETERNAL){ long occurrenceTime = stamp.getOccurrenceTime(); // 按照目标时间算出更新信念的参数 float factor = TruthFunctions.temporalProjection(occurrenceTime, targetTime, currentTime); // 更新信心 float newConfidence = factor * truth.getConfidence(); // 如果新的信心大于永恒化之后的信心,创建一个以新的信心为信心的真值 if(newConfidence > newTruth.getConfidence()) newTruth = new TruthValue(truth.getFrequency(), newConfidence, truth.getAnalytic(), false); } } // 如果newTruth为空,证明当前语句为永恒,则直接返回当前真值,永恒不能非永恒化 if(newTruth == null) newTruth = truth.clone(); return newTruth; } }
opennars/opennars_core
nars_core_java/nars/entity/Sentence.java
66,252
package com.regent.rpush.api.server; import com.regent.rpush.dto.ApiResult; import com.regent.rpush.dto.rpushserver.ServerInfoDTO; import lombok.SneakyThrows; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; @FeignClient(name = "rpush-server", contextId = "ServerInfoService") @RequestMapping("/server-info") public interface ServerInfoService { /** * 返回对应服务器的信心 */ @SneakyThrows @GetMapping ApiResult<ServerInfoDTO> serverInfo(); }
shuangmulin/rpush
rpush-api/src/main/java/com/regent/rpush/api/server/ServerInfoService.java
66,253
package net.kdks.model.sf; import java.util.List; import lombok.Data; /** * 查询信心. * * @author Ze.Wang * @since 0.0.1 */ @Data public class MsgData { /** * 路由集. */ private List<RouteResps> routeResps; /** * 单号集. */ private List<WaybillNoInfo> waybillNoInfoList; }
fuzui/aggregatelogistics
src/main/java/net/kdks/model/sf/MsgData.java
66,255
/** * MIT License * <p> * Copyright (c) 2017 James * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package me.zbl.bridge; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 强大的敌人 */ public class IntrepidEnemy implements Enemy { private static final Logger LOGGER = LoggerFactory.getLogger(IntrepidEnemy.class); @Override public void onStartWar() { LOGGER.info("敌人信心满满,准备迎战"); } @Override public void onCombatting() { LOGGER.info("敌人正在积极反抗"); } @Override public void onStopWar() { LOGGER.info("双方达成了平手"); } }
JamesZBL/java_design_patterns
bridge/src/main/java/me/zbl/bridge/IntrepidEnemy.java
66,257
package jdk_8_sample; import com.alibaba.fastjson.JSONObject; public class PunctuationCheckerMain { public static void main(String[] args) { String url = ""; url = "http://"+comm_consts.APIHost+"/spellcheck/json_check/json_phrase"; /** * 我们的 api 测试接口 和 www.CuoBieZi.net 是两套系统 * * */ System.out.println("测试的时候,不要只是输入一个词语。没有上下文比较难判断。 要输入一段话,放到真实的文章上下文中测试, 谢谢!"); System.out.println("测试的时候,不要只是输入一个词语。没有上下文比较难判断。 要输入一段话,放到真实的文章上下文中测试, 谢谢!"); System.out.println("测试的时候,不要只是输入一个词语。没有上下文比较难判断。 要输入一段话,放到真实的文章上下文中测试, 谢谢!"); String sentence = "测试文本中国人民共和国张可诺雷非科技2018年23月35号习近平国家主席十九精神李克强总理这根邮寄达老旧烟囱已走到生命进头,中国人民解军雷落科技中国特色会社主义马少黄股票她的离去让哦们很悲伤, 客户侧中华人民共和李洪志台万第二大金融控股公司富邦金控已与腾讯谈成合作,上述保险产品将由富邦金控旗下内地子公司富邦财险开发或引进。"; // sentence = "讲座现场,宋振美教授首先向大家简要介绍了中国共产党历史上的十八次全国代表大会情况,然后以十九大报告的“四个新”(新时代、新使命、新思想、新征程)为切入点讲解了十九大召开情况。宋教授着重解读了中国特色社会主义新时代,围绕新时代提出的依据、新时代提出的意义、新时代的内涵和“三个前所未有”,对近平新时代中国特色社会主义思想的重大创新进行讲解。习近平总书记指出三个“前所未有”,即中国前所未有地靠近世界舞台中心,前所未有地接近实现中华民族伟大复兴的目标,前所未有地具有实现这个目标的能力和信心。"; //sentence = "今天近平参加了会议\n\n\n"; //敏感字测试 //sentence = "十九大习京平暗示法举案说法急死了房间爱上了咖啡的回复回复对象存储福务中国人民共和国你擦微博擦诶日本发吧按时发货撒返回三分啥地方啦时代峻峰了司法局了撒附近阿斯利康福建省冷风机奥说了就分手了就爱睡懒觉了设计费垃圾费链接离开家里卡死机拉上来家里就啊沙发沙发萨法萨法"; //sentence = "自从在他们公司代理之后每天还收到各种企业服务电话骚扰。。。"; //sentence = "华为云专业名词测试:对像存储服务是稳定、安全、高效、易用的云存储服务,具备标准Restful API接口,可存储任意数量和形式的非结构化数据,提供99.999999999%的数据可靠性。"; System.out.println("post sentence is:" + sentence); JSONObject json = new JSONObject(); json.put("content",sentence);//固定 参数 json.put("username","user_name");// 可替换参数 --> 请注册账号后,向管理员申请权限, :-) json.put("password","test_password");//固定测试参数 json.put("biz_type","show");//固定参数 json.put("mode","advanced");//固定参数 //json.put("is_return_sentence",true);// 是否返回句子 , 具体说明,可以参考文档。 json.put("user_channel","api.cuobiezi.net"); //固定参数 //json.put("check_sensitive_word",true); // 敏感词检测 String str = HttpUtils.doPostJson(url, json.toJSONString()); System.out.println(str); System.out.println("测试的时候,不要只是输入一个词语。没有上下文比较难判断。 要输入一段话,放到真实的文章上下文中测试, 谢谢!"); System.out.println("测试的时候,不要只是输入一个词语。没有上下文比较难判断。 要输入一段话,放到真实的文章上下文中测试, 谢谢!"); } }
textproofreading/JcJcCuoBieZiJavaClient
src/main/java/jdk_8_sample/PunctuationCheckerMain.java
66,259
package com.app.service.tuser; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.app.aop.SystemServiceLog; import com.app.dao.tuser.TUserMapper; import com.app.dto.TuserDto; import com.app.model.TUser; import com.app.util.PageUtil; @Service public class TUserServInteImpl implements TUserServInte{ @Autowired private TUserMapper tusermapper; @Override @SystemServiceLog(description = "根据主键id删除用户") public int deleteByPrimaryKey(Long id) { // TODO Auto-generated method stub return tusermapper.deleteByPrimaryKey(id); } @Override @SystemServiceLog(description = "保存用户信息") public int insert(TUser record) { // TODO Auto-generated method stub return tusermapper.insert(record); } @Override @SystemServiceLog(description = "保存用户信息,可选择字段") public int insertSelective(TUser record) { // TODO Auto-generated method stub //DBContextHolder.setDbType(DBContextHolder.DB_TYPE_RW); int res=tusermapper.insertSelective(record); if(res==0){ throw new RuntimeException(); } return res; } @Override @SystemServiceLog(description = "根据主键id查询用户信息") public TUser selectByPrimaryKey(Long id) { // TODO Auto-generated method stub return tusermapper.selectByPrimaryKey(id); } @Override @SystemServiceLog(description = "更新用户信息,可选择字段") public int updateByPrimaryKeySelective(TUser record) { // TODO Auto-generated method stub //DBContextHolder.setDbType(DBContextHolder.DB_TYPE_RW); return tusermapper.updateByPrimaryKeySelective(record); } @Override @SystemServiceLog(description = "更新用户信心,全字段") public int updateByPrimaryKey(TUser record) { // TODO Auto-generated method stub //DBContextHolder.setDbType(DBContextHolder.DB_TYPE_RW); return tusermapper.updateByPrimaryKey(record); } @Override @SystemServiceLog(description = "登录方法") public TUser selectByLogin(TUser tu) { // TODO Auto-generated method stub //DBContextHolder.setDbType(DBContextHolder.DB_TYPE_R); return tusermapper.selectByLogin(tu); } @Override @SystemServiceLog(description = "用户列表分页查询") public List<TuserDto> selectListTuser(PageUtil pu) { // TODO Auto-generated method stub //DBContextHolder.setDbType(DBContextHolder.DB_TYPE_R); return tusermapper.selectListTuser(pu); } @Override @SystemServiceLog(description = "根据username查询用户是否存在") public int selectCountByUsername(String username) { // TODO Auto-generated method stub //DBContextHolder.setDbType(DBContextHolder.DB_TYPE_R); return tusermapper.selectCountByUsername(username); } @Override @SystemServiceLog(description = "查询所有用户,map形式传参") public List<TuserDto> selectAll(Map map) { // TODO Auto-generated method stub return tusermapper.selectAll(map); } }
charlierui/spring-mvc
src/main/java/com/app/service/tuser/TUserServInteImpl.java
66,260
package chapter12.adt; import java.util.NoSuchElementException; /** * 红黑树,线程不安全 * 红黑树4个性质 * 1.每个节点要么是红色,要么是黑色 * 2.根是黑色的,(可选:null节点默认为黑色) * 3.一个节点是红色的,它的子节点必须是黑色的 * 4.从一个节点到一个null引用必须包含相同个数的黑色节点 * @author wenl * @param <AnyType> */ public class RedBlackTree<AnyType extends Comparable<? super AnyType>> { private static class RedBlackNode<AnyType>{ AnyType element; RedBlackNode<AnyType> left; RedBlackNode<AnyType> right; int color; public RedBlackNode(AnyType element){ this(element,null,null); } public RedBlackNode(AnyType element, RedBlackNode<AnyType> left, RedBlackNode<AnyType> right) { this.element = element; this.left = left; this.right = right; this.color = BLACK;//根式黑色,默认为黑色 } } private static final int BLACK=1; private static final int RED=0; //header.right是根节点,header.left是上次插入元素到 private RedBlackNode<AnyType>header; //用于辅助 , private RedBlackNode<AnyType>nullNode; //用于插入找到当前节点 private RedBlackNode<AnyType>current; //用于插入维护 插入节点与父链的关系 private RedBlackNode<AnyType>parent; //用于判断是否是 之字形,用于维护祖父关系。 private RedBlackNode<AnyType>grand; //用于一字形和之字形旋转 private RedBlackNode<AnyType>great; /** * 构造方法 */ public RedBlackTree( ) { nullNode = new RedBlackNode<>( null ); nullNode.left = nullNode.right = nullNode; header = new RedBlackNode<>( null ); header.left = header.right = nullNode; } /** * 自顶向下插入 */ public void insert( AnyType item ){ nullNode.element=item; current=parent=grand=header; //自顶向下调整,避免插入的父节点和父节点的兄弟节点为黑色的情况,该情况复杂不利于恢复平衡信心. while(compare(item,current)!=0){ great=grand; grand=parent; parent=current; current=compare(item,current)<0?current.left:current.right; if(current.left.color==RED&&current.right.color==RED){ handleReorientAfterInsert(item); } } if(current!=nullNode){//重复元素跳过 return; } //找到位置 //构建新的节点 current=new RedBlackNode<AnyType>(item,nullNode,nullNode); //维护与父节点的关系 if(compare(item,parent)<0){ parent.left=current; }else{ parent.right=current; } //插入完成后,维护平衡信息 handleReorientAfterInsert(item); nullNode.element=null; } /** * 删除一个节点, * 依据可以删除一个叶子, * 自顶向下删除, * 1如果要删除项有右儿子,先删除右儿子最小项,之后使用原右儿子的最小项内容替换要删除项的内容. * 2.如果只有左儿子,先删除左儿子最大,之后使用左儿子的最大项替换要删除项的内容. * 3.如果没有儿子 * 若父节点为header,将树变为空树 * 否则如果当前节点为黑色,进行调整,保证删除项为红色,之后将要删除项的父节点的引用设置为nullNode. * @param x */ public AnyType remove( AnyType x ){ //需要自己尝试书写 //先查找是否存在,存在后删除 RedBlackNode<AnyType>p=find(x); RedBlackNode<AnyType>pParent=parent; if (p == null){ return null; } AnyType item=p.element; //自顶向下删除 //找到后,如果存在左儿子和右儿子(或 只有右儿子), //使用右儿子的最小,替换当前 ,之后删除右儿子最小 //只有左儿子使用左儿子最大替换, RedBlackNode<AnyType>replacement=findReplaceMent(p); if(replacement!=null){ //进行替换 p.element=remove(replacement.element); }else{ //没有替换者, if(pParent==header){ makeEmpty(); }else{ if(p.color==BLACK){ //将p地调整为红色 fixbeforedelete(p.element) ; pParent=parent; } //调整为删除 if(pParent.left==p){ pParent.left=nullNode; }else if(pParent.right==p){ pParent.right=nullNode; } } } current=p; parent=pParent; return item; } /** * 删除前调整数的平衡信息,保证要删除的项是红色 * @param item */ private void fixbeforedelete(AnyType item) { grand=header; RedBlackNode<AnyType>p=header.right; RedBlackNode<AnyType>x=nullNode; RedBlackNode<AnyType>t=nullNode; RedBlackNode<AnyType>i=find(item); //先把p涂成红色,最后恢复 p.color=RED; x=item.compareTo(p.element)<=0?p.left:p.right; t=item.compareTo(p.element)<=0?p.right:p.left; //保证要删除的项是红色 while(i.color!=RED){ if(x.color==RED|| (x.color==BLACK&&(x.left.color==RED&&x.right.color==RED)|| t.color==BLACK&&(x.left.color==RED||x.right.color==RED)) ){ //x为红色或x儿子为红色,x为黑色&&t为黑色,x有一个儿子为红色,向下探索 grand=p; p=x; x=item.compareTo(p.element)<0?p.left:p.right; t=item.compareTo(p.element)<0?p.right:p.left; }else if(x.color==BLACK&&t.color==BLACK &&x.right.color==BLACK&&x.left.color==BLACK){ //3中情况需要,调整的情况 if(t.left.color==BLACK&&t.right.color==BLACK){ //t的两个儿子,直接变换p和t,x的颜色,重新再该位置下探 p.color=BLACK; t.color=RED; x.color=RED; }else if(t.left.color==RED&&t.right.color==RED){ //t有两个红色的儿子,调整后下探 if(p.right==t){ RedBlackNode<AnyType>red=t.left; p.right=red.left; t.left=red.right; red.right=t; red.left=p; //更新祖父节点 if(grand.left==p){ grand.left=red; }else{ grand.right=red; } grand=red; p.color=BLACK; x.color=RED; t=p.right; }else{ RedBlackNode<AnyType>red=t.right; p.left=red.right; t.right=red.left; red.right=p; red.left=t; if(grand.left==p){ grand.left=red; }else{ grand.right=red; } grand=red; p.color=BLACK; x.color=RED; t=p.left; } }else if(p.right==t&&t.left.color==RED){ //右左,之字调整后继续下探 RedBlackNode<AnyType>red=t.left; p.right=red.left; t.left=red.right; red.right=t; red.left=p; if(grand.left==p){ grand.left=red; }else{ grand.right=red; } grand=red; p.color=BLACK; x.color=RED; t=p.right; }else if(p.left==t&&(t.right.color==RED)){ //左右,之字调整后继续下探 RedBlackNode<AnyType>red=t.right; p.left=red.right; t.right=red.left; red.right=p; red.left=t; if(grand.left==p){ grand.left=red; }else{ grand.right=red; } grand=red; p.color=BLACK; x.color=RED; t=p.left; }else if(p.right==t&&t.right.color==RED){ //右右 一字,交换t和p p.right=t.left; t.left=p; if(grand.left==p){ grand.left=t; }else{ grand.right=t; } grand=t; t.color=RED; p.color=BLACK; t=p.right; }else if(p.left==t&&t.left.color==RED){ //左左 一字 交换t和p p.left=t.right; t.right=p; if(grand.left==p){ grand.left=t; }else{ grand.right=t; } grand=t; t.color=RED; p.color=BLACK; t=p.left; } }else if(x.color==BLACK&&p.color==BLACK&&t.color==RED){ //x的兄弟为黑色,x和x的父节点都是红色,调整t和p,保证p为红色后,继续下探 if(p.left==x){ p.right=t.left; t.left=p; if(grand.left==p){ grand.left=t; }else{ grand.right=t; } grand=t; t.color=BLACK; p.color=RED; t=p.right; }else{ p.left=t.right; t.right=p; if(grand.left==p){ grand.left=t; }else{ grand.right=t; } grand=t; t.color=BLACK; p.color=RED; t=p.left; } }else if(header.right==p&&x.color==BLACK &&p.color==RED&&t.color==RED){ p.color=BLACK; } } header.right.color=BLACK; parent=p; } /** * 用于删除,查找替换的节点 * @param p * @return */ private RedBlackNode<AnyType> findReplaceMent(RedBlackNode<AnyType> p) { RedBlackNode<AnyType>replacement=null; parent=null; if (p == null){ return null; }else if (p.right != nullNode) { parent=p; replacement = p.right; while (replacement.left != nullNode){ parent=replacement; replacement = replacement.left; } return replacement; } else if(p.left!=nullNode){ parent=p; replacement = p.left; while (replacement != nullNode) { parent=replacement; replacement = replacement.right; } return replacement; }else{ return null; } } /** * 查找项对应的节点 * @param x * @return */ private RedBlackNode<AnyType> find(AnyType x) { nullNode.element = x; current = header.right; parent=current; while(true){ int compare=x.compareTo(current.element); if(compare<0){ parent=current; current=current.left; }else if(compare>0){ parent=current; current=current.right; }else if(current!=nullNode){ nullNode.element = null; return current; }else { nullNode.element = null; return null; } } } /** * 找最小项 * @return */ public AnyType findMin( ){ if(isEmpty()){ throw new NoSuchElementException(); } RedBlackNode<AnyType>iter=header.right; while(iter.left!=nullNode){ iter=iter.left; } return iter.element; } /** * 找最大项 * @return */ public AnyType findMax(){ if(isEmpty()){ throw new NoSuchElementException(); } RedBlackNode<AnyType>t=header.right; while(t.right!=nullNode){ t=t.right; } return t.element; } /** * 判断树是否包含x项 * @param x * @return */ public boolean contains( AnyType x ){ nullNode.element=x; RedBlackNode<AnyType>iter=header.right; boolean flag=false; for(;;){ if(x.compareTo(iter.element)<0){ iter=iter.left; }else if(x.compareTo(iter.element)>0){ iter=iter.right; }else if(iter!=nullNode){ flag= true; break; }else { flag= false; break; } } nullNode.element=null; return flag; } /** * 清空这棵树 */ public void makeEmpty( ){ header.right=nullNode; } /** * 打印这棵树 */ public void printTree(){ if(isEmpty()){ throw new NoSuchElementException(); } printTree(header.right); } /** * 打印这棵树 * @param t */ private void printTree(RedBlackNode<AnyType> t) { if( t != nullNode ) { printTree( t.left ); System.out.println( t.element +"color is"+( t.color==RED?"RED":"BLACK")+" left:"+t.left.element+" right:"+t.right.element); printTree( t.right ); } } /** * 判断是否为空 * @return */ public boolean isEmpty(){ return header.right==nullNode; } /** * 使用的比较方法 * @param item * @param t 如果t是header,任何item都大于header * @return */ private int compare( AnyType item, RedBlackNode<AnyType> t ){ if( t == header ) return 1; else return item.compareTo( t.element ); } /** * 插入后维护平衡信息 * @param item */ private void handleReorientAfterInsert(AnyType item) { //初步调整的变换颜色 自己变为红色,两个儿子变为红色 current.color=RED; current.left.color=BLACK; current.right.color=BLACK; if(parent.color==RED){//调整后破坏了红黑树性质,需要旋转 //分两种类型 一字形和之字形,之字形比一字形调整了多一步 grand.color = RED; if((compare(item,grand)<0)!=(compare(item,parent)<0)){//之字形 parent=rotate(item,grand);//调整parent和他的儿子,并将调整后的节点W设置成parent } //调整完成,重新设置当前节点 current=rotate(item,great); //并将当前节点设置为黑色 current.color=BLACK; } //保证根节点是黑色 header.right.color=BLACK; } /** * 根据item和根,旋转对应的儿子 * @param item 插入的项 * @param parent 当前根 * @return */ private RedBlackNode<AnyType> rotate(AnyType item, RedBlackNode<AnyType> parent) { // if(compare(item,parent)<0){//L return parent.left=compare(item,parent.left)<0? rotateWithLeftChild(parent.left): rotateWithRightChild(parent.left); }else {//R return parent.right=compare(item,parent.right)<0? rotateWithLeftChild(parent.right): rotateWithRightChild(parent.right); } } /** * 旋转一颗树的右儿子,返回新的根 * @param t 需要旋转的树的根 * @return */ private RedBlackNode<AnyType> rotateWithRightChild(RedBlackNode<AnyType> t) { // RedBlackNode<AnyType>newT=t.right; t.right=newT.left; newT.left=t; return newT; } /** * 旋转一颗树的左儿子,返回新的根 * @param t * @return */ private RedBlackNode<AnyType> rotateWithLeftChild(RedBlackNode<AnyType> t) { // RedBlackNode<AnyType>newT=t.left; t.left=newT.right; newT.right=t; return newT; } public static void main( String [ ] args ) { RedBlackTree<Integer> t = new RedBlackTree<>( ); final int NUMS = 10; for(int i=0;i<NUMS;i++){ t.insert(i); } t.printTree(); t.remove(0); System.out.println("================================="); t.printTree(); } }
floor07/DataStructuresAndAlgorithm-Demo
src/main/java/chapter12/adt/RedBlackTree.java
66,261
package cn.finder.wx.corp.domain; /*** * 微信用户信心 * @author whl * */ public class User { private String userid; private String name; private Integer[] department; private String position; private String mobile; private String gender; private String email; private String weixinid; private String avatar; private int status; private String extattr; public String getUserid() { return userid; } public void setUserid(String userid) { this.userid = userid; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer[] getDepartment() { return department; } /*public void setDepartment(Integer[] department) { this.department = department; }*/ public void setDepartment(Object[] department) { if(department!=null){ this.department=new Integer[department.length]; for(int i=0;i<department.length;i++){ this.department[i]=Integer.valueOf(department[i].toString()); } } } public String getPosition() { return position; } public void setPosition(String position) { this.position = position; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getWeixinid() { return weixinid; } public void setWeixinid(String weixinid) { this.weixinid = weixinid; } public String getAvatar() { return avatar; } public void setAvatar(String avatar) { this.avatar = avatar; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public String getExtattr() { return extattr; } public void setExtattr(String extattr) { this.extattr = extattr; } }
cnfinder/wae
wx-sdk/src/main/java/cn/finder/wx/corp/domain/User.java
66,262
/* 题目: 客户端给服务端发送文本,服务端会将文本转成大写在返回给客户端 * */ package com.java.exercise; import org.junit.Test; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.util.Scanner; public class TCPSocketExercise2 { @Test public void server() { ServerSocket serverSocket = null; Socket socket = null; InputStream inputStream = null; OutputStream outputStream = null; try { serverSocket = new ServerSocket(8000); socket = serverSocket.accept(); System.out.println("等待客户端连接..."); inputStream = socket.getInputStream(); byte[] b = inputStream.readAllBytes(); String str = new String(b); System.out.println("接受到客户端的信息:" + str); String str2 = str.toUpperCase(); // 响应客户端 outputStream = socket.getOutputStream(); outputStream.write(str2.getBytes()); } catch (IOException e) { e.printStackTrace(); } finally { // 关闭流、socket、ServerSocket try { if (outputStream != null) { outputStream.close(); } if (inputStream != null) { inputStream.close(); } if (socket != null) { socket.close(); } if (serverSocket != null) { serverSocket.close(); } } catch (IOException e) { e.printStackTrace(); } } } @Test public void client() { Socket socket = null; OutputStream outputStream = null; Scanner sc = null; InputStream inputStream = null; try { socket = new Socket(InetAddress.getByName("127.0.0.1"), 8000); outputStream = socket.getOutputStream(); sc = new Scanner(System.in); System.out.println("请输入多个字符:\n"); String str = sc.nextLine(); outputStream.write(str.getBytes()); // socket.shutdownOutput(); outputStream.flush(); // 接受服务端信心 inputStream = socket.getInputStream(); byte[] b = inputStream.readAllBytes(); String str2 = new String(b); System.out.println("服务端响应信息,服务端将响应装换成大写的内容:" + str2); } catch (IOException e) { e.printStackTrace(); } finally { // 关闭流、socket try { if (inputStream != null) { inputStream.close(); } if (sc != null) { sc.close(); } if (outputStream != null) { outputStream.close(); } if (socket != null) { socket.close(); } } catch (IOException e) { e.printStackTrace(); } } } }
cucker0/java
day20/src/com/java/exercise/TCPSocketExercise2.java
66,263
package org.cxj.listener; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.http.HttpSessionAttributeListener; import javax.servlet.http.HttpSessionBindingEvent; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; /** * * @author sae * @date 2016-05-26 * * 在sae上使用struts2,需要添加的Listener * 由于sae无法部署tomcat下的应用,powered by Jetty 失去信心,转BAE试试 */ public class SaeListener implements ServletContextListener,HttpSessionListener,HttpSessionAttributeListener{ public void contextDestroyed(ServletContextEvent arg0) {} public void contextInitialized(ServletContextEvent arg0) {} public void sessionCreated(HttpSessionEvent arg0) {} public void sessionDestroyed(HttpSessionEvent arg0) {} public void attributeAdded(HttpSessionBindingEvent arg0) {} public void attributeRemoved(HttpSessionBindingEvent arg0) {} public void attributeReplaced(HttpSessionBindingEvent arg0) {} }
ShouldChan/trafficBussiness
src/org/cxj/listener/SaeListener.java
66,264
package com.cdeledu.crawler.other; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.cdeledu.common.constant.ConstantHelper; import com.cdeledu.util.apache.lang.DateUtilHelper; import com.cdeledu.util.network.tcp.HttpURLConnHelper; /** * @类描述: 从相关网抓取有关信息数据 * @创建者: 独泪了无痕 * @创建日期: 2016年3月23日 下午10:39:33 * @版本: V1.0 * @since: JDK 1.7 */ public class CtripHelperUtil { /** ----------------------------------------------------- Fields start */ // 编码格式 private static HttpURLConnHelper conn = null; static { conn = HttpURLConnHelper.getInstance(ConstantHelper.UTF_8.name()); } /** ----------------------------------------------------- Fields end */ /** * @方法:历史上的今天查询服务 * @创建人:独泪了无痕 * @see <a href="http://www.rijiben.com/">历史上今天大事记</a> * @return */ public static String getTodayInHistory() throws Exception { /** * 1.发起http get请求获取指定url的网页源码 */ String html = conn.sendGetRequest("http://www.rijiben.com"); /** * 2.利用正则表达式从网页源码中抽取"历史上的今天"信心数据<br/> */ StringBuilder sb = new StringBuilder(); // 日期标签:用以确定区分今天还是昨天 String dateTag = DateUtilHelper.getMonthDay(0); String regex = "(.*)(<div class=\"listren\">)(.*?)(</div>)(.*)"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(html); if (matcher.matches()) { // ① 因为不能保证网站上的数据一定在凌晨准时更新,所有必须判断截取到的数据是当天的还是前一天的 if (matcher.group(3).contains(DateUtilHelper.getMonthDay(-1))) { dateTag = DateUtilHelper.getMonthDay(-1); } // ② 封装标题 sb.append("== ").append("历史上的今天").append(dateTag).append(" ==").append("\n\n"); // ③ 抽取内容 for (String info : matcher.group(3).split(" ")) { info = info.replace(dateTag, "").replace("(图)", "").replaceAll("</?[^>]+>", "") .replace("&nbsp;&nbsp;", "").trim(); // 在每行的末尾追加换行 if (!"".equals(info)) { sb.append(info).append("\n\n"); } } } return (null == sb) ? "" : sb.substring(0, sb.lastIndexOf("\n\n")); } }
dllwh/wechat
wechat-webCrawler/src/main/java/com/cdeledu/crawler/other/CtripHelperUtil.java
66,268
package com.hs_vae.Lambda; import java.util.Arrays; import java.util.List; import java.util.function.Predicate; public class Demo08Predicate { public static void main(String[] args) { List<Integer> number = Arrays.asList(1, 2, 3, 4, 5, 6); //Predicate来定义测试的标准,返回是否测试通过,传统(匿名内部类)写法 show(number, new Predicate() { @Override public boolean test(Object o) { return (int)o%2==0; } }); //使用Lambda表达式过滤能被2整除的number show(number,x->(int)x%2==0); } public static void show(List list,Predicate condition){ //过滤filter方法中传入Predicate接口,再调用测试方法test,根据测试的规则,判断输入的参数是否测试通过 list.stream().filter(x->condition.test(x)).forEach(System.out::println); } }
hs-vae/java-load
src源代码/Lambda/Demo08Predicate.java
66,270
// 传统递归方法 class Solution { public List<Integer> inorderTraversal(TreeNode root) { List<Integer> result = new ArrayList<>(); traverse(root, result); return result; } public void traverse(TreeNode root, List<Integer> result) { if (root != null) { if (root.left != null) { traverse(root.left, result); } result.add(root.val); if (root.right != null) { traverse(root.right, result); } } } } // 参考题解中的染色法,通过栈进行递推 // 定义内部类包装TreeNode,但是因为类的操作需要额外开销,时间反而落后于递归 class Solution { class ColorNode { TreeNode node; String color; public ColorNode(TreeNode node,String color){ this.node = node; this.color = color; } } public List<Integer> inorderTraversal(TreeNode root) { if(root == null) return new ArrayList<Integer>(); List<Integer> res = new ArrayList<>(); Stack<ColorNode> stack = new Stack<>(); stack.push(new ColorNode(root,"white")); while(!stack.empty()){ ColorNode cn = stack.pop(); if(cn.color.equals("white")){ if(cn.node.right != null) stack.push(new ColorNode(cn.node.right,"white")); stack.push(new ColorNode(cn.node,"gray")); if(cn.node.left != null)stack.push(new ColorNode(cn.node.left,"white")); }else{ res.add(cn.node.val); } } return res; } }
algorithm004-01/algorithm004-01
Week 02/id_556/LeetCode_94_556.java
66,271
package Adapter.Java; /** * Created by prefert on 2017/11/19. * 耳机适配器 传统 => lightning */ public class HeadsetAdapter extends LightningConnector implements PhoneJackInterface { @Override public void audioTraditionally() { // 传统接口兼容 lightning super.audioWithLightning(); } }
YarenTang/Design_Patterns_Examples
src/Adapter/Java/HeadsetAdapter.java
66,272
/** * Hutool-db是一个在JDBC基础上封装的数据库操作工具类,通过包装,使用ActiveRecord思想操作数据库。<br> * 在Hutool-db中,使用Entity(本质上是个Map)代替Bean来使数据库操作更加灵活,同时提供Bean和Entity的转换提供传统ORM的兼容支持。 * * @author looly * */ package cn.hutool.db;
dromara/hutool
hutool-db/src/main/java/cn/hutool/db/package-info.java
66,273
package internet.tcp.cs3; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.InetSocketAddress; import java.net.Socket; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; import java.util.Arrays; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; /** * @author tianmingbo */ public class Client { public static void main(String[] args) throws InterruptedException { int clientCount = 10000; ExecutorService executorServiceIO = Executors.newFixedThreadPool(10); ExecutorService executorServiceNIO = Executors.newFixedThreadPool(10); // 使用传统 IO 的客户端 Runnable ioClient = () -> { try { Socket socket = new Socket("localhost", 30000); OutputStream out = socket.getOutputStream(); // InputStream in = socket.getInputStream(); InputStreamReader in = new InputStreamReader(socket.getInputStream()); out.write("old IO!".getBytes()); // char[] buffer = new char[1024]; // int n; // while ((n = in.read(buffer)) != -1) { // System.out.println(new String(buffer, 0, n)); // } in.close(); out.close(); socket.close(); } catch (IOException e) { e.printStackTrace(); } }; // 使用 NIO 的客户端 Runnable nioClient = () -> { try { SocketChannel socketChannel = SocketChannel.open(); socketChannel.connect(new InetSocketAddress("localhost", 8081)); ByteBuffer buffer = ByteBuffer.wrap("NIO".getBytes()); socketChannel.write(buffer); buffer.clear(); socketChannel.read(buffer); socketChannel.close(); } catch (IOException e) { e.printStackTrace(); } }; // 分别测试 NIO 和传统 IO 的服务器性能 long startTime, endTime; startTime = System.currentTimeMillis(); for (int i = 0; i < clientCount; i++) { executorServiceIO.execute(ioClient); } executorServiceIO.shutdown(); executorServiceIO.awaitTermination(1, TimeUnit.MINUTES); endTime = System.currentTimeMillis(); System.out.println("传统 IO 服务器处理 " + clientCount + " 个客户端耗时: " + (endTime - startTime) + "ms"); startTime = System.currentTimeMillis(); for (int i = 0; i < clientCount; i++) { executorServiceNIO.execute(nioClient); } executorServiceNIO.shutdown(); executorServiceNIO.awaitTermination(1, TimeUnit.MINUTES); endTime = System.currentTimeMillis(); System.out.println("NIO 服务器处理 " + clientCount + " 个客户端耗时: " + (endTime - startTime) + "ms"); } }
tianmingbo/GOOD-GOOD-STUDY
DAYDAYUP/javaCode/internet/tcp/cs3/Client.java
66,274
package io.zsy.study.zimug; import org.junit.jupiter.api.Test; import java.io.File; import java.io.IOException; import java.nio.file.*; import java.nio.file.attribute.BasicFileAttributes; import java.util.Comparator; import java.util.stream.Stream; /** * @author: zsy * @date: 2021/1/26 16:59 */ public class DeleteFileTest { /** * 传统 IO File.delete() * 成功-true * 失败-false 不同给出失败原因 */ @Test void testDeleteFile1() { File file = new File("D:\\data\\test"); boolean delete = file.delete(); } /** * 传统 IO File.deleteOnExit() * 成功-void * 失败-void */ @Test void testDeleteFile2() { File file = new File("D:\\data\\test"); file.deleteOnExit(); } /** * NIO Files.delete() * 成功-void * 失败-NoSuchFileException/DirectoryNotEmptyException * * @throws IOException */ @Test void testDeleteFile3() throws IOException { Path path = Paths.get("D:\\data\\test"); Files.delete(path); } /** * NIO Files.delete() * 成功-true * 失败(文件夹不存在)-false * 失败(文件夹有子文件夹)-DirectoryNotEmptyException * * @throws IOException */ @Test void testDeleteFile4() throws IOException { Path path = Paths.get("D:\\data\\test"); Files.deleteIfExists(path); } private void createMoreFiles() { } @Test void testDeleteFile5() throws IOException { createMoreFiles(); Path path = Paths.get("D:\\data\\test1\\test2"); Files.walkFileTree(path, new SimpleFileVisitor<Path>() { // 先遍历删除文件 @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.delete(file); System.out.printf("文件被删除: %s%n", file); return FileVisitResult.CONTINUE; } // 再遍历删除目录 @Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { // 此时文件已被删除,目录为空目录 Files.delete(dir); System.out.printf("文件夹被删除: %s%n", dir); return FileVisitResult.CONTINUE; } }); } @Test void testDeleteFile6() throws IOException { createMoreFiles(); Path path = Paths.get("D:\\data\\test1\\test2"); try (Stream<Path> walk = Files.walk(path)) { // 按字符串排序,倒序时文件会排在目录前面,会先删除文件再删除目录 walk.sorted(Comparator.reverseOrder()) .forEach(DeleteFileTest::deleteDirectoryStream); } } private static void deleteDirectoryStream(Path path) { try { Files.delete(path); System.out.printf("删除文件成功: %s%n", path.toString()); } catch (IOException e) { System.out.printf("无法删除的路径: %s%n%s", path, e); } } /** * 传统 IO 递归删除 * * @throws IOException */ @Test void testDeleteFile7() throws IOException { createMoreFiles(); File file = new File("D:\\data\\test1\\test2"); deleteDirectoryLegacyIO(file); } private void deleteDirectoryLegacyIO(File file) { // 无法做到 遍历多层文件夹数据 File[] files = file.listFiles(); // 递归调用 if (files != null) { for (File temp : files) { deleteDirectoryLegacyIO(temp); } } if (file.delete()) { System.out.printf("删除成功: %s%n", file); } else { System.out.printf("删除失败: %s%n", file); } } }
zsy0216/BatchModifyBilibiliName
src/main/java/io/zsy/study/zimug/DeleteFileTest.java
66,275
package com.best.hello.mapper; import com.best.hello.entity.User; import org.apache.ibatis.annotations.*; import java.util.List; // 标识这个类是一个数据访问层的bean,并交给spring容器管理 @Mapper public interface UserMapper { /** * 传统的xml配置 */ List<User> orderBy(String field, String sort); List<User> orderBySafe(String field); /** * MyBatis3提供了新的基于注解的配置,通过注解不在需要配置繁杂的xml文件 */ @Select("select * from users where user like CONCAT('%', #{user}, '%')") List<User> queryByUser(@Param("user") String user); @Select("select * from users where id = ${id}") List<User> queryById1(@Param("id") String id); @Select("select * from users where id = ${id}") List<User> queryById2(@Param("id") Integer id); // 使用#{}会产生报错 @Select("select * from users order by ${field} desc") List<User> orderBy2(@Param("field") String field); @Select("select * from users") List<User> list(); // 模糊搜索,直接'%#{q}%' 会报错 // 安全代码:@Select("select * from users where user like concat('%',#{q},'%')") @Select("select * from users where user like '%${q}%'") List<User> search(String q); }
j3ers3/Hello-Java-Sec
src/main/java/com/best/hello/mapper/UserMapper.java
66,278
package com.wang.basic.io; import java.io.*; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.file.Files; import java.nio.file.Paths; /** * @description: 文件拷贝 * @author: wei·man cui * @date: 2021/2/5 10:04 */ public class FileCopy { public static void main(String[] args) { String sourcePath = "E:/test.txt"; String targetPath = "E:/test_copied.txt"; File source = new File(sourcePath); File target = new File(targetPath); // copyFileByStream(source, target); // copyFileByNioFilesCopy(source, target); copyFileByNio(source, target); } /** * 传统 IO * 通过 文件流 拷贝 * * @param source 源 * @param target 目标 */ public static void copyFileByStream(File source, File target) { try (final InputStream inputStream = new FileInputStream(source); OutputStream outputStream = new FileOutputStream(target)) { byte[] buffer = new byte[1024]; int length; while ((length = inputStream.read(buffer)) > -1) { outputStream.write(buffer, 0, length); } outputStream.flush(); } catch (IOException e) { e.printStackTrace(); } } /** * NIO 工具类 * {@link java.nio.file.Files#copy(java.nio.file.Path, java.io.OutputStream)}方法拷贝 * * @param source 源 * @param target 目标 */ public static void copyFileByNioFilesCopy(File source, File target) { try { Files.copy(Paths.get(source.getPath()), new FileOutputStream(target)); } catch (IOException e) { e.printStackTrace(); } } /** * 使用 NIO 的 Channel 和 ByteBuffer 拷贝 * * @param source 源 * @param target 目标 */ public static void copyFileByNio(File source, File target) { try (FileInputStream in = new FileInputStream(source); FileOutputStream out = new FileOutputStream(target)) { FileChannel inChannel = in.getChannel(); FileChannel outChannel = out.getChannel(); // 设置缓冲区大小为 1M(每次即可读取 1M) ByteBuffer byteBuffer = ByteBuffer.allocate(1024 * 1024); while ((inChannel.read(byteBuffer)) > -1) { // 切换读写模式 byteBuffer.flip(); outChannel.write(byteBuffer); // 清空缓冲区,循环读 byteBuffer.clear(); } } catch (IOException e) { e.printStackTrace(); } } }
cuiweiman/wang-wen-jun
java-basic/src/main/java/com/wang/basic/io/FileCopy.java
66,282
/* * 文件名:Joiner_Study.java * 版权:Copyright 2007-2016 zxiaofan.com. Co. Ltd. All Rights Reserved. * 描述: Joiner_Study.java * 修改人:zxiaofan * 修改时间:2016年12月29日 * 修改内容:新增 */ package guava.base; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.junit.Test; import com.google.common.base.Joiner; import com.google.common.base.Joiner.MapJoiner; /** * 连接器Joiner.join(Iterable<?> parts) * * joiner实例总是不可变的,线程安全,建议定义为static final常量。 * * @author zxiaofan */ public class Joiner_Study { String str1 = "a "; String str2 = ""; String str_null = null; String str4 = "d"; String[] arr = new String[]{"a", null, "c"}; static final Joiner joiner = Joiner.on(";").skipNulls(); // 以;分隔,忽略null static final MapJoiner mapJoin = Joiner.on(";").withKeyValueSeparator("-->"); // key-value分隔符 @Test public void basicTest() { String result = joiner.join(str1, str2, str_null, str4); System.out.println(result); // a ;;d Joiner joiner2 = Joiner.on("&&").useForNull("default"); // 以&&分隔,使用default替换null result = joiner2.join(str1, str2, str_null, str4); System.out.println(result); // a &&&&default&&d // 错误用法 Joiner err = Joiner.on(";"); err.skipNulls(); // does nothing! System.out.println(err.join(str2, str_null, str4)); // NullPointerException } /** * appendTo拼接StringBuffer需捕获IOException,拼接StringBuilder则不需要. * */ @Test public void otherTest() { String result = joiner.join(arr); System.out.println(result); // a;c StringBuffer buf = new StringBuffer(); buf.append("buf"); StringBuffer res = new StringBuffer(); try { res = joiner.appendTo(buf, arr); // appendTo直接拼接 } catch (IOException e) { e.printStackTrace(); } System.out.println(res.toString()); // bufa;c StringBuilder build = new StringBuilder("build"); System.out.println(joiner.appendTo(build, arr)); // builda;c } @Test public void mapJoinerTest() { Map<String, String> map = new HashMap(); map.put("name", "zxiaofan.com"); map.put("age", "20"); String result = mapJoin.join(map); System.out.println(result); } /** * MapJoiner遍历map比传统遍历map.entrySet()慢很多(but百万级别数据拼接在1s以内,so常规程序可以忽略这点性能差距)。 * * Joiner遍历List在百万级别以上时比传统方式更高效。 * * Joiner优势:代码更优雅(null;末尾的分隔符)。 * */ @Test public void performanceCompare() { System.out.println("----拼接Map---"); joinCompareMap(5000); joinCompareMap(10000); joinCompareMap(100000); joinCompareMap(1000000); // ---key_value数量:5000--- // 传统遍历拼接方式:2ms // MapJoin拼接方式:4ms // ---key_value数量:10000--- // 传统遍历拼接方式:4ms // MapJoin拼接方式:5ms // ---key_value数量:100000--- // 传统遍历拼接方式:27ms // MapJoin拼接方式:40ms // ---key_value数量:1000000--- // 传统遍历拼接方式:147ms // MapJoin拼接方式:622ms System.out.println(); System.out.println("----拼接List---"); joinCompareList(5000); joinCompareList(10000); joinCompareList(100000); joinCompareList(500000); joinCompareList(1000000); // 百万 // ---key_value数量:5000--- // 传统遍历拼接方式:1ms // Joiner拼接方式:1ms // ---key_value数量:10000--- // 传统遍历拼接方式:2ms // Joiner拼接方式:2ms // ---key_value数量:100000--- // 传统遍历拼接方式:6ms // Joiner拼接方式:21ms // ---key_value数量:500000--- // 传统遍历拼接方式:21ms // Joiner拼接方式:43ms // ---key_value数量:1000000--- // 传统遍历拼接方式:66ms // Joiner拼接方式:33ms } private void joinCompareMap(int num) { System.out.println("// ---key_value数量:" + num + "---"); Map<String, String> map = new HashMap(); for (int i = 0; i < num; i++) { map.put("k" + i, "val" + i); } long time1 = System.currentTimeMillis(); StringBuilder buf = new StringBuilder(); // 单线程StringBuilder,多线程StringBuffer for (Entry<String, String> entry : map.entrySet()) { buf.append(entry.getKey()).append("-->").append(entry.getValue()).append(";"); } long time2 = System.currentTimeMillis(); System.out.println("// 传统遍历拼接方式:" + (time2 - time1) + "ms"); time1 = System.currentTimeMillis(); String result = mapJoin.join(map); time2 = System.currentTimeMillis(); System.out.println("// MapJoin拼接方式:" + (time2 - time1) + "ms"); } private void joinCompareList(int num) { System.out.println("// ---key_value数量:" + num + "---"); List<String> list = new ArrayList<>(); for (int i = 0; i < num; i++) { list.add("val" + i); } long time1 = System.currentTimeMillis(); StringBuilder buf = new StringBuilder(); for (String entry : list) { buf.append(entry).append(";"); } long time2 = System.currentTimeMillis(); System.out.println("// 传统遍历拼接方式:" + (time2 - time1) + "ms"); time1 = System.currentTimeMillis(); String result = joiner.join(list); time2 = System.currentTimeMillis(); System.out.println("// Joiner拼接方式:" + (time2 - time1) + "ms"); } }
zxiaofan/OpenSource_Study
google/src/guava/base/Joiner_Study.java
66,284
/* * 文件名:Implements_Java8.java * 版权:Copyright 2007-2016 zxiaofan.com. Co. Ltd. All Rights Reserved. * 描述: Implements_Java8.java * 修改人:yunhai * 修改时间:2016年3月21日 * 修改内容:新增 */ package other; import org.junit.Test; /** * Java8中implements新特性default * * Java8的Default方法:接口新增default方法,而不破坏现有实现架构。【无缝结合Lambda表达式】 * * @author yunhai */ interface A { String sys(); // 传统接口 default void sysNew() { // default关键字,所有实现此接口的类都会默认继承这个方法 System.out.println("new sysout"); } } public class Implements_Java8 implements A { /** * {@inheritDoc}. */ @Override public String sys() { System.out.println("sysout"); return null; } // // @Override // public void sysNew() { // System.out.println("sysout-Override"); // } @Test public void test() { sys(); sysNew(); // 直接使用,不必重写;重写亦可 } }
limm33/jdk-source
study/src/main/java/other/Implements_Java8.java
66,286
package com.bili; import com.alibaba.fastjson.JSON; import com.bili.model.AutoBilibili; import com.bili.model.task.BiliData; import com.bili.model.task.BiliTaskInfo; import com.bili.model.task.config.BiliTaskConfig; import com.bili.util.BiliTaskUtil; import com.oldwu.constant.SystemConstant; import com.oldwu.entity.TaskResult; import com.oldwu.util.DateUtils; import com.oldwu.util.NumberUtil; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public class BiliTaskMain { private final Log logger = LogFactory.getLog(BiliTaskMain.class); //创建一个String来保存简易日志 StringBuilder simpleLog = new StringBuilder(); //只要有一个任务失败了,这个标识就应该为false boolean flag = true; public static void main(String[] args) { BiliTaskMain biliTaskMain = new BiliTaskMain(); AutoBilibili autoBilibili = new AutoBilibili(); autoBilibili.setBiliJct(""); autoBilibili.setDedeuserid(""); autoBilibili.setSessdata(""); autoBilibili.setTaskConfig(""); TaskResult run = biliTaskMain.run(autoBilibili); System.out.println(run.toString()); } /** * bili任务入口 * * @param autoBilibili 任务参数 * @return 任务结果 */ public TaskResult run(AutoBilibili autoBilibili) { //加载taskConfig任务配置 String taskConfigJsonStr = autoBilibili.getTaskConfig(); BiliTaskConfig taskConfig = JSON.parseObject(taskConfigJsonStr, BiliTaskConfig.class); BiliTaskInfo taskInfo = new BiliTaskInfo(autoBilibili.getDedeuserid(), autoBilibili.getSessdata(), autoBilibili.getBiliJct()); taskInfo.setTaskConfig(taskConfig); //实例化一个对象 BiliTaskUtil biliTaskUtil = new BiliTaskUtil(taskInfo); //首先需要执行登录任务以及硬币检查任务 try { biliTaskUtil.userCheck(); } catch (Exception e) { //登录检查失败,直接返回失败 return TaskResult.doLoginError(e.getMessage(), biliTaskUtil.getLog()); } try { biliTaskUtil.coinLogs(); } catch (Exception e) { simpleLog.append(e.getMessage()).append("\n"); } //传统办法生成随机数来决定任务执行顺序 int[] randoms = NumberUtil.getRandoms(0, 9, 10); for (int random : randoms) { try { switch (random) { //需要检测某些特定任务是否开启,没有开启则跳过 case 0: biliTaskUtil.cartoonSign(); break; case 1: biliTaskUtil.chargeMe(); break; case 2: biliTaskUtil.coinAdd(); break; case 3: biliTaskUtil.liveGift(); break; case 4: biliTaskUtil.liveSign(); break; case 5: biliTaskUtil.matchGame(); break; case 6: biliTaskUtil.readCartoon(); break; case 7: biliTaskUtil.silver2Coin(); break; case 8: biliTaskUtil.vipCartoonRec(); break; case 9: biliTaskUtil.watchVideo(); break; } } catch (Exception e) { logger.warn("b站任务运行时出错:" + e.getMessage()); simpleLog.append("任务运行中出现错误:").append(e.getMessage()).append("\n"); flag = false; } //随机延迟执行下一个任务 DateUtils.threadSleep(SystemConstant.BILI_DEFAULT_DELAY); } //执行最后的统计任务 BiliData biliData = null; try { biliData = biliTaskUtil.calculateUpgradeDays(); } catch (Exception e) { simpleLog.append(e.getMessage()).append("\n"); } //判断任务是否部分失败 if (!flag) { return TaskResult.doTaskPartError(simpleLog.toString(), biliTaskUtil.getLog(), biliData); } //任务执行成功 return TaskResult.doAllSuccess(simpleLog.toString(), biliTaskUtil.getLog(), biliData); } } //暂时不做部分失败判断,感觉没必要 // int[] randoms = NumberUtil.getRandoms(0, 9, 10); // boolean flag0 = true, flag1 = true, flag2 = true, flag3 = true, flag4 = true, flag5 = true, flag6 = true, flag7 = true, flag8 = true, flag9 = true; ////随机延迟执行下一个任务 // for (int random : randoms) { // switch (random) { // //需要检测某些特定任务是否开启,没有开启则跳过 // case 0: // try { // biliTaskUtil.cartoonSign(); // } catch (Exception e) { // simpleLog.append(e.getMessage()).append("\n"); // flag0 = false; // } // break; // case 1: // try { // biliTaskUtil.chargeMe(); // } catch (Exception e) { // simpleLog.append(e.getMessage()).append("\n"); // flag1 = false; // } // break; // case 2: // try { // biliTaskUtil.coinAdd(); // } catch (Exception e) { // simpleLog.append(e.getMessage()).append("\n"); // flag2 = false; // } // break; // case 3: // try { // biliTaskUtil.liveGift(); // } catch (Exception e) { // simpleLog.append(e.getMessage()).append("\n"); // flag3 = false; // } // break; // case 4: // try { // biliTaskUtil.liveSign(); // } catch (Exception e) { // simpleLog.append(e.getMessage()).append("\n"); // flag4 = false; // } // break; // case 5: // try { // biliTaskUtil.matchGame(); // } catch (Exception e) { // simpleLog.append(e.getMessage()).append("\n"); // flag5 = false; // } // break; // case 6: // try { // biliTaskUtil.readCartoon(); // } catch (Exception e) { // simpleLog.append(e.getMessage()).append("\n"); // flag6 = false; // } // break; // case 7: // try { // biliTaskUtil.silver2Coin(); // } catch (Exception e) { // simpleLog.append(e.getMessage()).append("\n"); // flag7 = false; // } // break; // case 8: // try { // biliTaskUtil.vipCartoonRec(); // } catch (Exception e) { // simpleLog.append(e.getMessage()).append("\n"); // flag8 = false; // } // break; // case 9: // try { // biliTaskUtil.watchVideo(); // } catch (Exception e) { // simpleLog.append(e.getMessage()).append("\n"); // flag9 = false; // } // break; // } // } // //执行最后的统计任务 // try { // biliTaskUtil.calculateUpgradeDays(); // } catch (Exception e) { // simpleLog.append(e.getMessage()).append("\n"); // } // //判断任务是否全部失败 // if (flag0 && flag1){ // // }
wyt1215819315/autoplan
src/main/java/com/bili/BiliTaskMain.java
66,287
package OIO; import java.io.IOException; import java.io.InputStream; import java.net.ServerSocket; import java.net.Socket; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * 传统socket服务端 * */ public class OioServer { @SuppressWarnings("resource") public static void main(String[] args) throws Exception { ExecutorService newCachedThreadPool = Executors.newCachedThreadPool(); //创建socket服务,监听10101端口 ServerSocket server=new ServerSocket(10101); System.out.println("服务器启动!"); while(true){ //获取一个套接字(阻塞) final Socket socket = server.accept(); System.out.println("来个一个新客户端!"); newCachedThreadPool.execute(new Runnable() { @Override public void run() { //业务处理 handler(socket); } }); } } /** * 读取数据 * @param socket * @throws Exception */ public static void handler(Socket socket){ try { byte[] bytes = new byte[1024]; InputStream inputStream = socket.getInputStream(); while(true){ //读取数据(阻塞) int read = inputStream.read(bytes); if(read != -1){ System.out.println(new String(bytes, 0, read)); }else{ break; } } } catch (Exception e) { e.printStackTrace(); }finally{ try { System.out.println("socket关闭"); socket.close(); } catch (IOException e) { e.printStackTrace(); } } } }
csy512889371/learndemo
netty/IOServer/src/OIO/OioServer.java
66,289
package com.bewind.list; import java.util.ArrayList; import java.util.Iterator; import java.util.List; // 集合遍历 public class Traverse { public static void main(String[] args) { // 初始化List集合 List<String> list = new ArrayList<>(); list.add("张三"); list.add("李四"); list.add("王五"); iteratorExample(list); foreachExample(list); forIndexExample(list); } // ✅推荐 for each 遍历 public static void foreachExample(List<String> list) { for (String s : list) { System.out.println("for each: " + s); } } // 迭代器遍历 public static void iteratorExample(List<String> list) { Iterator<String> iterator = list.iterator(); while (iterator.hasNext()) { System.out.println("迭代器: " + iterator.next()); } // 迭代器作用域更低的写法 for (Iterator<String> it = list.iterator(); it.hasNext(); ) { System.out.println("迭代器控制作用域: " + it.next()); } } // 传统 for 循环遍历数组 public static void forIndexExample(List<String> list) { for (int i = 0; i < list.size(); i++) { String j = list.get(i); System.out.println("Index: " + j); } } }
leoxiewl/java-case-library
src/main/java/com/bewind/list/Traverse.java
66,290
package algorithms; /** * 爬楼梯 * * <p> 假设你正在爬楼梯。需要 n 阶你才能到达楼顶。 * * <p> 每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢 * * @author samin * @date 2021-01-11 */ public class ClimbStairs { public static void main(String[] args) { // 2 System.out.println(new ClimbStairs().climbStairs(2)); // 3 System.out.println(new ClimbStairs().climbStairs(3)); } /** * 使用动态规划法,得出结论为斐波那契数列 * * @param n 需要到底的层数 * @return 结果 */ public int climbStairs(int n) { if (n == 1 || n == 2) { return n; } // a 表示第n-2个台阶的走法,b表示第n-1个台阶的走法,传统迭代 int a = 1, b = 2; int count = 0; for (int i = 3; i <= n; i++) { // 累加结果 count = a + b; // 向下迭代,下次迭代的第 n-2 个台阶的走法等于上次迭代 n-1 个台阶的走法 a = b; // 下次迭代的第 n-1 个台阶的走法等于上次迭代的第 n 个台阶走法 b = count; } return count; } }
SaminZou/study-prj
leetcode/src/algorithms/ClimbStairs.java
66,291
package com.cdkj.loan.enums; /** * 利率类型 * @author: jiafr * @since: 2018年6月16日 下午10:06:00 * @history: */ public enum ERateType { CT("1", "传统"), ZK("2", "直客"); ERateType(String code, String value) { this.code = code; this.value = value; } private String code; private String value; public String getCode() { return code; } public String getValue() { return value; } }
ibisTime/xn-wzcd
src/main/java/com/cdkj/loan/enums/ERateType.java
66,293
import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class ListFor { public static void main(String[] args) { //List接口的实现子类Vector LinkedList //List list = new ArrayList(); //跟下面 List 的遍历方式一样 //List list = new Vector(); //跟下面 List 的遍历方式一样 List list = new ArrayList(); list.add("jack"); list.add("tom"); list.add("鱼香肉丝"); list.add("北京烤鸭"); //遍历 //1.迭代器 System.out.println("=====迭代器:====="); Iterator iterator = list.iterator(); while (iterator.hasNext()) { Object obj = iterator.next(); System.out.println(obj); } //2.增强 for System.out.println("=====增强 for====="); for (Object o : list) { System.out.println("o = " + o); } //2.传统 for System.out.println("=====传统for====="); for (int i = 0; i < list.size(); i++) { System.out.println("对象 = " + list.get(i)); } } }
icebear32/JAVA_CODE
chapter07/list/list/ListFor.java
66,295
H 1520570560 tags: Backtracking, Trie, DFS 给一串words, 还有一个2D character matrix. 找到所有可以形成的words. 条件: 2D matrix 只可以相邻走位. #### Trie, DFS - 相比之前的implementation, 有一些地方可以优化: - 1. Backtracking时候, 在board[][] 上面mark就可以, 不需要开一个visited[][] - 2. 不需要implement trie的所有方程, 用不到: 这里只需要insert. - 普通的trie题目会让你search a word, 但是这里是用一个board, 看board的每一个字母能不能走出个Word. - 也就是: 这里的search是自己手动写, 不是传统的trie search() funcombination - 3. TrieNode里面存在 end的时候存string word, 表示到底. 用完了 word = null, 刚好截断重复查找的问题. ##### 关于Trie - Build Trie with target words: insert, search, startWith. Sometimes, just: `buildTree(words)` and return root. - 依然要对board matrix做DFS。 - no for loop on words. 直接对board DFS: - 每一层,都会有个up-to-this-point的string. 在Trie里面check它是不是存在。以此判断。 - 若不存在,就不必继续DFS下去了。 - Trie solution time complexity, much better: - build Trie: n * wordMaxLength - search: boardWidth * boardHeight * (4^wordMaxLength + wordMaxLength[Trie Search]) #### Regular DFS - for loop on words: inside, do board DFS based on each word. - Time cpmplexity: word[].length * boardWidth * boardHeight * (4^wordMaxLength) #### Previous Notes - Big improvement: use boolean visited on TrieNode! - 不要用rst.contains(...), 因为这个是O(n) 在leetcode还是会timeout(lintcode竟然可以pass)! - 在Trie search() method 里面,凡是visit过的,mark一下。 ``` /* LeetCode Given a 2D board and a list of words from the dictionary, find all words in the board. Each word must be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once in a word. For example, Given words = ["oath","pea","eat","rain"] and board = [ ['o','a','a','n'], ['e','t','a','e'], ['i','h','k','r'], ['i','f','l','v'] ] Return ["eat","oath"]. Note: You may assume that all inputs are consist of lowercase letters a-z. Hint: You would need to optimize your backtracking to pass the larger test. Could you stop backtracking earlier? If the current candidate does not exist in all words' prefix, you could stop backtracking immediately. What kind of data structure could answer such query efficiently? Does a hash table work? Why or why not? How about a Trie? If you would like to learn how to implement a basic trie, please work on this problem: Implement Trie (Prefix Tree) first. */ /* Thoughts: Simplify the problem: want to find the words' existance based on the trie structure. 1. Build the trie with the words. 2. DFS and backtracking with the board and see if the combination exist. Build Trie: time: O(mn), m = words.length, n = max word.length Search with dfs board[k][k] -> k^2 longest word: n O(k^2 * n) Overall: O(k^2 * n) + O(mn) = O(mn), k should be small */ /* Thoughts: Simplify the problem: want to find the words' existance based on the trie structure. 1. Build the trie with the words. 2. DFS and backtracking with the board and see if the combination exist. */ class Solution { class TrieNode { String word; TrieNode[] children; public TrieNode() { this.word = null; this.children = new TrieNode[26]; } } int[] dx = {0, 0, 1, -1}; int[] dy = {1, -1, 0, 0}; public List<String> findWords(char[][] board, String[] words) { List<String> result = new ArrayList<>(); if (validateInput(board, words)) return result; // Build trie TrieNode root = buildTrie(words); Set<String> set = new HashSet<>(); // DFS and populate the result for (int i = 0; i < board.length; i++) { for (int j = 0; j < board[0].length; j++) { dfs(root, board, i, j, set); } } result.addAll(set); return result; } private void dfs(TrieNode node, char[][] board, int x, int y, Set<String> set) { if (x < 0 || x >= board.length || y < 0 || y >= board[0].length) return; char c = board[x][y]; if (c == '#' || node.children[c - 'a'] == null) return; node = node.children[c - 'a']; // Found the match if (node.word != null && !set.contains(node.word)) set.add(node.word); // Moving forward and backtracking board[x][y] = '#'; for (int i = 0; i < 4; i++) { dfs(node, board, x + dx[i], y + dy[i], set); } board[x][y] = c; } private TrieNode buildTrie(String[] dict) { TrieNode root = new TrieNode(); for (String word : dict) { TrieNode node = root; for (char c : word.toCharArray()) { int index = c - 'a'; if (node.children[index] == null) node.children[index] = new TrieNode(); node = node.children[index]; } node.word = word; } return root; } private boolean validateInput(char[][] board, String[] words) { return board == null || board.length == 0 || board[0] == null || board[0].length == 0 || words == null || words.length == 0; } } /* Given a matrix of lower alphabets and a dictionary. Find all words in the dictionary that can be found in the matrix. A word can start from any position in the matrix and go left/right/up/down to the adjacent position. Example Given matrix: doaf agai dcan and dictionary: {"dog", "dad", "dgdg", "can", "again"} return {"dog", "dad", "can", "again"} dog: doaf agai dcan dad: doaf agai dcan can: doaf agai dcan again: doaf agai dcan Challenge Using trie to implement your algorithm. Tags Expand LintCode Copyright Trie */ /* Attemp2: Trie solution. http://www.jiuzhang.com/solutions/word-search-ii/ Here is how Tire works, from my understanding: it creates a new data strucutre that maps all words into a trie structure. Then, based on the given 2D matrix of letters, using each individual letter as starting point, and grab all possible combinations, then save the possibilities into final resuts. The magic 'checking point' is the use of 'isString' of trie. Note: should also be careful with marking board[x][y] = '#', which helps to prevent re-use used letters. About TrieTree: Each string obtains a particular/unique path. Different strings could share same prefix path, but at certain index when the two strings are differentiating, they will start the following path on different TrieNode, which leads to completely separate subtree path. At end of the tree, a string will have isString== true and the real string value stored. That is, insert: for all letter, make sure they are all created as nodes and linked together by using subtree. find: for loop to iterate through subtrees of nodes, then return target on last index letter. In the search: node.subtree.get(current).isString: this determines if a string exists or not. */ /*NOTE: is boolean visited on Trie!!! */ public class Solution { class TrieNode { String str; boolean isEnd; boolean visited; HashMap<Character, TrieNode> children; public TrieNode () { this.isEnd = false; this.visited = false; this.str = ""; children = new HashMap<Character, TrieNode>(); } } public TrieNode root; public List<String> findWords(char[][] board, String[] words) { List<String> rst = new ArrayList<String>(); if (board == null || board.length == 0 || board[0].length == 0 || words == null || words.length == 0) { return rst; } //Build Trie with words root = new TrieNode(); for (int i = 0; i < words.length; i++) { insert(words[i]); } //Validate existance of the words in board boolean[][] visited = new boolean[board.length][board[0].length]; for (int i = 0; i < board.length; i++) { for (int j = 0; j < board[0].length; j++) { dfs(rst, "", i, j, visited, board); } } return rst; } //4 direction DFS search public void dfs(List<String> rst, String s, int x, int y, boolean[][] visited, char[][] board) { if (x < 0 || x >= board.length || y < 0 || y >= board[0].length) { return; } if (visited[x][y]) { return; } s += board[x][y]; if (!startWith(s)) { return; } if (search(s)) { rst.add(s); } int[] dx = {0,0,1,-1}; int[] dy = {1,-1,0,0}; visited[x][y] = true; for (int i = 0; i < 4; i++) { int nx = x + dx[i]; int ny = y + dy[i]; dfs(rst, s, nx, ny, visited, board); } visited[x][y] = false; } /**************************Trie section *********************/ public void insert (String s){ char[] arr = s.toCharArray(); TrieNode node = root; for (int i = 0; i < arr.length; i++) { char c = arr[i]; if (!node.children.containsKey(c)) { node.children.put(c, new TrieNode()); } node = node.children.get(c); if (i == arr.length - 1) { node.isEnd = true; node.str = s; } } } public boolean search(String s) { char[] arr = s.toCharArray(); TrieNode node = root; for (int i = 0; i < arr.length; i++) { char c = arr[i]; if (!node.children.containsKey(c)) { return false; } node = node.children.get(c); } if (node.visited || !node.isEnd) { return false; } node.visited = true; return true; } public boolean startWith(String s) { char[] arr = s.toCharArray(); TrieNode node = root; for (int i = 0; i < arr.length; i++) { char c = arr[i]; if (!node.children.containsKey(c)) { return false; } node = node.children.get(c); } return true; } } /* Attempt1: Thoughts: Use word search1, and do for loop on the words... and that works .........Well, that's not the Trie solution */ public class Solution { public ArrayList<String> wordSearchII(char[][] board, ArrayList<String> words) { ArrayList<String> rst = new ArrayList<String>(); if (board == null || words == null || words.size() == 0) { return rst; } for (String word : words) { if (exist(board, word)) { rst.add(word); } } return rst; } //The following are from Word Search I public boolean exist(char[][] board, String word) { if (word == null || word.length() == 0) { return true; } if (board == null) { return false; } for (int i = 0; i < board.length; i++) { for (int j = 0; j < board[0].length; j++) { if (board[i][j] == word.charAt(0)) { boolean rst = search(board, word, i, j, 0); if (rst) { return true; } } } } return false; } public boolean search(char[][] board, String word, int i, int j, int start) { if (start == word.length()) { return true; } if (i < 0 || i >= board.length || j < 0 || j >= board[0].length || board[i][j] != word.charAt(start)) { return false; } board[i][j] = '#'; boolean rst = search(board, word, i, j - 1, start + 1) || search(board, word, i, j + 1, start + 1) || search(board, word, i + 1, j, start + 1) || search(board, word, i - 1, j, start + 1); board[i][j] = word.charAt(start); return rst; } } ```
awangdev/leet-code
Java/Word Search II.java
66,297
package com.javaTest.reflection23.class_; /** * @author * @version 1.0 * @date 2023/11/10 12:05 * @Description 对Class类的内容梳理 */ public class Class01 { public static void main(String[] args) throws ClassNotFoundException { //看看 Class 类图 //1. Class 也是类,因此也继承 Object 类 //Class //2. Class 类对象不是 new 出来的,而是系统创建的 //(1) 传统 new 对象 /* ClassLoader 类 public Class<?> loadClass(String name) throws ClassNotFoundException { return loadClass(name, false); } */ //Cat cat = new Cat(); //(2) 反射方式, 刚才老师没有 debug 到 ClassLoader 类的 loadClass, 原因是,我没有注销 Cat cat = new Cat(); /* ClassLoader 类, 仍然是通过 ClassLoader 类加载 Cat 类的 Class 对象 public Class<?> loadClass(String name) throws ClassNotFoundException { return loadClass(name, false); } */ Class cls1 = Class.forName("com.javaTest.reflection23.Cat"); //3. 对于某个类的 Class 类对象,在内存中只有一份,因为类只加载一次 Class cls2 = Class.forName("com.javaTest.reflection23.Cat"); System.out.println(cls1.hashCode()); System.out.println(cls2.hashCode()); Class cls3 = Class.forName("com.javaTest.reflection23.Dog"); System.out.println(cls3.hashCode()); } }
lzf31501597/MTJavaWeb
javaTest/reflection23/class_/Class01.java
66,311
package com.tophant import java.text.SimpleDateFormat import com.tophant.html.Util_html import com.tophant.util.Util import org.apache.commons.lang.{StringEscapeUtils, StringUtils} import org.apache.hadoop.hbase.HBaseConfiguration import org.apache.hadoop.hbase.client.Scan import org.apache.hadoop.hbase.filter.CompareFilter.CompareOp import org.apache.hadoop.hbase.filter.SingleColumnValueFilter import org.apache.hadoop.hbase.util.{Base64, Bytes} import org.apache.spark.rdd.RDD import org.apache.spark.{SparkConf, SparkContext} import org.slf4j.LoggerFactory object Hbase2hdfs { def main(args: Array[String]): Unit = { val logger = LoggerFactory.getLogger(getClass) // 命令行参数个数必须为2 if (args.length != 5) { logger.error("参数个数错误") logger.error("Usage: Classify <开始日期> <结束日期> <存储位置> <host>") System.exit(1) } // 获取命令行参数中的行为数据起止日期 val tableName = args(0).trim //hbase表的前缀 val startDate = args(1).trim //hbase表的后缀起始日期 val endDate = args(2).trim //hbase表的后缀截至日期 val path = args(3).trim val host = args(4).trim // 根据起止日志获取日期列表 // 例如起止时间为20160118,20160120,那么日期列表为(20160118,20160119,20160120) val dateSet = getDateSet(startDate, endDate) val sparkConf = new SparkConf() .setAppName("hbase2hdfs") // .set("spark.default.parallelism","12") val sc = new SparkContext(sparkConf) val conf = HBaseConfiguration.create() //设置zooKeeper集群地址,也可以通过将hbase-site.xml导入classpath,但是建议在程序里这样设置 conf.set("hbase.zookeeper.quorum", "10.0.71.501,10.0.71.502,10.0.71.503") //设置zookeeper连接端口,默认2181 conf.set("hbase.zookeeper.property.clientPort", "2181") //组装scan语句 val scan=new Scan() scan.setCacheBlocks(false) scan.addFamily(Bytes.toBytes("rd")) scan.addColumn(Bytes.toBytes("rd"), Bytes.toBytes("host")) scan.addColumn("rd".getBytes, "url".getBytes) scan.addColumn("rd".getBytes, "http.request.method".getBytes) scan.addColumn("rd".getBytes, "http.request.header".getBytes) val hostFilter = new SingleColumnValueFilter(Bytes.toBytes("rd"), Bytes.toBytes("host"), CompareOp.EQUAL, Bytes.toBytes(host)) scan.setFilter(hostFilter) import org.apache.hadoop.hbase.mapreduce.TableInputFormat import org.apache.hadoop.hbase.protobuf.ProtobufUtil val proto = ProtobufUtil.toScan(scan) val ScanToString = Base64.encodeBytes(proto.toByteArray) // 按照日期列表读出多个RDD存在一个Set中,再用SparkContext.union()合并成一个RDD var rddSet: Set[RDD[(org.apache.hadoop.hbase.io.ImmutableBytesWritable, org.apache.hadoop.hbase.client.Result)] ] = Set() dateSet.foreach(date => { conf.set(TableInputFormat.SCAN, ScanToString) conf.set(TableInputFormat.INPUT_TABLE, tableName + date) // 设置表名 val bRdd: RDD[(org.apache.hadoop.hbase.io.ImmutableBytesWritable, org.apache.hadoop.hbase.client.Result)] = sc.newAPIHadoopRDD(conf, classOf[TableInputFormat], classOf[org.apache.hadoop.hbase.io.ImmutableBytesWritable], classOf[org.apache.hadoop.hbase.client.Result]) rddSet += bRdd }) val hBaseRDD = sc.union(rddSet.toSeq) val kvRDD = hBaseRDD. map { case (_, result) => //通过列族和列名获取列 var url = Bytes.toString(result.getValue("rd".getBytes, "url".getBytes)) val host = Bytes.toString(result.getValue("rd".getBytes, "host".getBytes)) var httpRequestHeaders = Bytes.toString(result.getValue("rd".getBytes, "http.request.header".getBytes)) var httpResponseHeaders = Bytes.toString(result.getValue("rd".getBytes, "http.response.header".getBytes)) val value = (url + "$$$" + httpRequestHeaders + "$$$" + httpResponseHeaders ) ( host, value) } .saveAsTextFile(path) } def getDateSet(sDate:String, eDate:String): Set[String] = { // 定义要生成的日期列表 var dateSet: Set[String] = Set() // 定义日期格式 val sdf = new SimpleDateFormat("yyyyMMdd") // 按照上边定义的日期格式将起止时间转化成毫秒数 val sDate_ms = sdf.parse(sDate).getTime val eDate_ms = sdf.parse(eDate).getTime // 计算一天的毫秒数用于后续迭代 val day_ms = 24*60*60*1000 // 循环生成日期列表 var tm = sDate_ms while (tm <= eDate_ms) { val dateStr = sdf.format(tm) dateSet += dateStr tm = tm + day_ms } // 日期列表作为返回 dateSet } }
githuber002/test
main.java
66,332
import java.util.Arrays; /** * LC#1365:How Many Numbers Are Smaller Than the Current Number * Link:https://leetcode-cn.com/problems/how-many-numbers-are-smaller-than-the-current-number/ * 思路一:首先想到的就是:嵌套循环的暴力解法,打败 46% 对手,时间:O(n2),效率并不高 * 思路二:计数排序(桶排序),时间复杂度:O(N + K),应该是最优解 */ public class S1365 { public int[] smallerNumbersThanCurrent(int[] nums) { int[] cnt = new int[101]; int n = nums.length; // 把数组放入桶中 for (int i = 0; i < n; i++) { cnt[nums[i]]++; } for (int i = 1; i <= 100; i++) { cnt[i] += cnt[i - 1]; } int[] ret = new int [n]; // 从桶中取出结果 for (int i = 0; i < n; i++) { ret[i] = nums[i] == 0 ? 0 : cnt[nums[i] - 1]; } return ret; } public static void main(String[] args) { int[] nums = {8, 1, 2, 2, 3}; int[] res = new S1365().smallerNumbersThanCurrent(nums); System.out.println("res --------->"); System.out.println(Arrays.toString(res)); } }
xiao2shiqi/leetcode
src/main/java/S1365.java
66,333
package common.dp; /** * @author luoyuntian * @program: p40-algorithm * @description: 纸牌游戏 * @date 2022-02-27 15:24:13 */ public class CardsInLine { // 递归实现 public static int getWinnerScore1(int[] arr){ int xian = xian1(arr,0,arr.length-1); int hou = hou1(arr,0,arr.length-1); return Math.max(xian,hou); } // 目前,是在arr[L...R]这个范围上玩牌 // 返回先手最终的最大得分 public static int xian1(int[] arr,int L,int R){ // 只有最后一张牌 if(L == R){ return arr[L]; } // 还剩两张牌 if(L == R -1){ return Math.max(arr[L],arr[R]); } // L...R上,不止两张牌 // 可能1:拿走L位置的牌 int p1 = arr[L] + hou1(arr,L+1,R); // 可能2:拿走R位置的牌 int p2 = arr[R] + hou1(arr,L,R-1); return Math.max(p1,p2); } // 目前,是在arr[L...R]这个范围上玩牌 // 返回后手最终的最大得分 public static int hou1(int[] arr,int L,int R){ // 只剩一张牌,被先手拿走 if(L == R){ return 0; } // 剩下两张牌,大的被先手拿走,只能拿小的 if(L == R-1){ return Math.min(arr[L],arr[R]); } // L...R上,不止两张牌 // 后手! // 可能性1:对手,先手,拿走L位置的牌,接下来,你就可以在L+1...R上先手了 int p1 = xian1(arr,L+1,R); // 可能性2:对手,先手,拿走R位置的牌,接下来,你就可以在L...R-1上先手了 int p2 = xian1(arr,L,R-1); return Math.max(p1,p2); } // 加缓存 public static int getWinnerScore2(int[] arr){ int n = arr.length; int[][] dpxian = new int[n][n]; int[][] dphou = new int[n][n]; for(int i=0;i<n;i++){ for(int j=0;j<n;j++){ dpxian[i][j] = -1; dphou[i][j] = -1; } } int xian = xian2(arr,0,arr.length-1,dpxian,dphou); int hou = hou2(arr,0,arr.length-1,dpxian,dphou); return Math.max(xian,hou); } // 目前,是在arr[L...R]这个范围上玩牌 // 返回先手最终的最大得分 public static int xian2(int[] arr,int L,int R,int[][] dpxian ,int[][] dphou ){ // 算过 if (dpxian[L][R] != -1) { return dpxian[L][R]; } int ans = 0; // 只有最后一张牌 if(L == R){ ans = arr[L]; }else if(L == R -1){ // 还剩两张牌 ans = Math.max(arr[L],arr[R]); }else { // L...R上,不止两张牌 // 可能1:拿走L位置的牌 int p1 = arr[L] + hou2(arr,L+1,R,dpxian,dphou); // 可能2:拿走R位置的牌 int p2 = arr[R] + hou2(arr,L,R-1,dpxian,dphou); ans = Math.max(p1,p2); } dpxian[L][R] = ans; return ans; } // 目前,是在arr[L...R]这个范围上玩牌 // 返回后手最终的最大得分 public static int hou2(int[] arr,int L,int R,int[][] dpxian,int[][] dphou){ if(dphou[L][R] != -1){ return dphou[L][R]; } int ans=0; // 只剩一张牌,被先手拿走 if(L == R){ return 0; }else if(L == R-1){ // 剩下两张牌,大的被先手拿走,只能拿小的 ans = Math.min(arr[L],arr[R]); }else { // L...R上,不止两张牌 // 后手! // 可能性1:对手,先手,拿走L位置的牌,接下来,你就可以在L+1...R上先手了 int p1 = xian2(arr,L+1,R,dpxian,dphou); // 可能性2:对手,先手,拿走R位置的牌,接下来,你就可以在L...R-1上先手了 int p2 = xian2(arr,L,R-1,dpxian,dphou); ans = Math.max(p1,p2); } dphou[L][R] = ans; return ans; } }
AlexNOCoder/p40-algorithm
src/main/java/common/dp/CardsInLine.java
66,335
package com.shinnytech.futures.model.engine; import android.os.Handler; import android.os.Looper; import com.shinnytech.futures.application.BaseApplication; import com.shinnytech.futures.amplitude.api.Amplitude; import com.shinnytech.futures.amplitude.api.Identify; import com.shinnytech.futures.model.bean.accountinfobean.AccountEntity; import com.shinnytech.futures.model.bean.accountinfobean.BankEntity; import com.shinnytech.futures.model.bean.accountinfobean.BrokerEntity; import com.shinnytech.futures.model.bean.accountinfobean.OrderEntity; import com.shinnytech.futures.model.bean.accountinfobean.PositionEntity; import com.shinnytech.futures.model.bean.accountinfobean.TradeBean; import com.shinnytech.futures.model.bean.accountinfobean.TradeEntity; import com.shinnytech.futures.model.bean.accountinfobean.TransferEntity; import com.shinnytech.futures.model.bean.accountinfobean.UserEntity; import com.shinnytech.futures.model.bean.conditionorderbean.COrderEntity; import com.shinnytech.futures.model.bean.conditionorderbean.ConditionEntity; import com.shinnytech.futures.model.bean.conditionorderbean.ConditionOrderBean; import com.shinnytech.futures.model.bean.conditionorderbean.ConditionOrderEntity; import com.shinnytech.futures.model.bean.conditionorderbean.ConditionUserEntity; import com.shinnytech.futures.model.bean.futureinfobean.ChartEntity; import com.shinnytech.futures.model.bean.futureinfobean.DiffEntity; import com.shinnytech.futures.model.bean.futureinfobean.FutureBean; import com.shinnytech.futures.model.bean.futureinfobean.KlineEntity; import com.shinnytech.futures.model.bean.futureinfobean.QuoteEntity; import com.shinnytech.futures.utils.SPUtils; import com.shinnytech.futures.utils.ToastUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.lang.reflect.Field; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.TimeZone; import static com.shinnytech.futures.application.BaseApplication.CO_BROADCAST; import static com.shinnytech.futures.application.BaseApplication.MD_BROADCAST; import static com.shinnytech.futures.application.BaseApplication.TD_BROADCAST; import static com.shinnytech.futures.application.BaseApplication.sendMessage; import static com.shinnytech.futures.constants.AmpConstants.AMP_CONDITION_FAILED; import static com.shinnytech.futures.constants.AmpConstants.AMP_CONDITION_SUCCEED; import static com.shinnytech.futures.constants.AmpConstants.AMP_EVENT_LOGIN_FAIL_REASON; import static com.shinnytech.futures.constants.AmpConstants.AMP_EVENT_LOGIN_TYPE; import static com.shinnytech.futures.constants.AmpConstants.AMP_EVENT_LOGIN_TYPE_VALUE_AUTO; import static com.shinnytech.futures.constants.AmpConstants.AMP_EVENT_LOGIN_TYPE_VALUE_LOGIN; import static com.shinnytech.futures.constants.AmpConstants.AMP_EVENT_NOTIFY_CONTENT; import static com.shinnytech.futures.constants.AmpConstants.AMP_LOGIN_FAILED; import static com.shinnytech.futures.constants.AmpConstants.AMP_LOGIN_SUCCEEDED; import static com.shinnytech.futures.constants.AmpConstants.AMP_NOTIFY; import static com.shinnytech.futures.constants.AmpConstants.AMP_USER_ACCOUNT_ID_FIRST; import static com.shinnytech.futures.constants.AmpConstants.AMP_USER_ACCOUNT_ID_LAST; import static com.shinnytech.futures.constants.AmpConstants.AMP_USER_BROKER_ID_FIRST; import static com.shinnytech.futures.constants.AmpConstants.AMP_USER_BROKER_ID_LAST; import static com.shinnytech.futures.constants.AmpConstants.AMP_USER_LOGIN_SUCCESS_TIME_FIRST; import static com.shinnytech.futures.constants.BroadcastConstants.TD_MESSAGE_LOGIN_TIMEOUT; import static com.shinnytech.futures.constants.CommonConstants.BROKER_ID_SIMNOW; import static com.shinnytech.futures.constants.CommonConstants.BROKER_ID_SIMULATION; import static com.shinnytech.futures.constants.ServerConstants.CODE_CHANGE_PASSWORD_INIT; import static com.shinnytech.futures.constants.ServerConstants.CODE_CHANGE_PASSWORD_SUCCEED; import static com.shinnytech.futures.constants.ServerConstants.CODE_CHANGE_PASSWORD_WEAK; import static com.shinnytech.futures.constants.ServerConstants.CODE_CHECK_UNREADY_CTP; import static com.shinnytech.futures.constants.ServerConstants.CODE_CONDITION_FAIL_LEFT; import static com.shinnytech.futures.constants.ServerConstants.CODE_CONDITION_FAIL_RIGHT; import static com.shinnytech.futures.constants.ServerConstants.CODE_CONDITION_SUCCEED; import static com.shinnytech.futures.constants.ServerConstants.CODE_LOGIN_FAIL_CTP_LEFT; import static com.shinnytech.futures.constants.ServerConstants.CODE_LOGIN_FAIL_CTP_RIGHT; import static com.shinnytech.futures.constants.ServerConstants.CODE_LOGIN_FAIL_SIMULATOR; import static com.shinnytech.futures.constants.ServerConstants.CODE_LOGIN_PASSWORD_MISMATCH_CTP; import static com.shinnytech.futures.constants.ServerConstants.CODE_LOGIN_PASSWORD_MISMATCH_SIMULATOR; import static com.shinnytech.futures.constants.ServerConstants.CODE_LOGIN_SUCCEED_CTP; import static com.shinnytech.futures.constants.ServerConstants.CODE_LOGIN_SUCCEED_SIMULATOR; import static com.shinnytech.futures.constants.ServerConstants.CODE_LOGIN_TIMEOUT_CTP; import static com.shinnytech.futures.constants.ServerConstants.CODE_SETTLEMENT; import static com.shinnytech.futures.constants.ServerConstants.PARSE_CONDITION_KEY_CONDITION_LIST; import static com.shinnytech.futures.constants.ServerConstants.PARSE_CONDITION_KEY_CONDITION_ORDERS; import static com.shinnytech.futures.constants.ServerConstants.PARSE_CONDITION_KEY_HIS_CONDITION_ORDERS; import static com.shinnytech.futures.constants.ServerConstants.PARSE_CONDITION_KEY_ORDER_ID; import static com.shinnytech.futures.constants.ServerConstants.PARSE_CONDITION_KEY_ORDER_LIST; import static com.shinnytech.futures.constants.ServerConstants.PARSE_CONDITION_KEY_RTN_CONDITION_ORDERS; import static com.shinnytech.futures.constants.ServerConstants.PARSE_CONDITION_KEY_TRADING_DAY; import static com.shinnytech.futures.constants.ServerConstants.PARSE_CONDITION_KEY_USER_ID; import static com.shinnytech.futures.constants.ServerConstants.PARSE_MARKET_KEY_CHARTS; import static com.shinnytech.futures.constants.ServerConstants.PARSE_MARKET_KEY_DATA; import static com.shinnytech.futures.constants.ServerConstants.PARSE_MARKET_KEY_INS_LIST; import static com.shinnytech.futures.constants.ServerConstants.PARSE_MARKET_KEY_KLINES; import static com.shinnytech.futures.constants.ServerConstants.PARSE_MARKET_KEY_KLINES_BINDING; import static com.shinnytech.futures.constants.ServerConstants.PARSE_MARKET_KEY_KLINES_DATA; import static com.shinnytech.futures.constants.ServerConstants.PARSE_MARKET_KEY_MDHIS_MORE_DATA; import static com.shinnytech.futures.constants.ServerConstants.PARSE_MARKET_KEY_QUOTES; import static com.shinnytech.futures.constants.ServerConstants.PARSE_MARKET_KEY_CHARTS_STATE; import static com.shinnytech.futures.constants.ServerConstants.PARSE_MARKET_KEY_TICKS; import static com.shinnytech.futures.constants.ServerConstants.PARSE_TRADE_KEY_CODE; import static com.shinnytech.futures.constants.ServerConstants.PARSE_TRADE_KEY_CONTENT; import static com.shinnytech.futures.constants.ServerConstants.PARSE_TRADE_KEY_DATA; import static com.shinnytech.futures.constants.ServerConstants.PARSE_TRADE_KEY_LEVEL; import static com.shinnytech.futures.constants.ServerConstants.PARSE_TRADE_KEY_NOTIFY; import static com.shinnytech.futures.constants.ServerConstants.PARSE_TRADE_KEY_TRADE; import static com.shinnytech.futures.constants.ServerConstants.PARSE_TRADE_KEY_ACCOUNTS; import static com.shinnytech.futures.constants.ServerConstants.PARSE_TRADE_KEY_BANKS; import static com.shinnytech.futures.constants.ServerConstants.PARSE_TRADE_KEY_ORDERS; import static com.shinnytech.futures.constants.ServerConstants.PARSE_TRADE_KEY_POSITIONS; import static com.shinnytech.futures.constants.ServerConstants.PARSE_TRADE_KEY_SESSION; import static com.shinnytech.futures.constants.ServerConstants.PARSE_TRADE_KEY_TRADES; import static com.shinnytech.futures.constants.ServerConstants.PARSE_TRADE_KEY_TRANSFERS; import static com.shinnytech.futures.constants.ServerConstants.PARSE_TRADE_KEY_USER_ID; import static com.shinnytech.futures.constants.SettingConstants.CONFIG_INIT_TIME; import static com.shinnytech.futures.constants.BroadcastConstants.CO_HIS_MESSAGE; import static com.shinnytech.futures.constants.BroadcastConstants.CO_MESSAGE; import static com.shinnytech.futures.constants.BroadcastConstants.MD_MESSAGE; import static com.shinnytech.futures.constants.BroadcastConstants.TD_MESSAGE; import static com.shinnytech.futures.constants.BroadcastConstants.TD_MESSAGE_CHANGE_SUCCESS; import static com.shinnytech.futures.constants.BroadcastConstants.TD_MESSAGE_LOGIN_FAIL; import static com.shinnytech.futures.constants.BroadcastConstants.TD_MESSAGE_LOGIN_SUCCEED; import static com.shinnytech.futures.constants.BroadcastConstants.TD_MESSAGE_SETTLEMENT; import static com.shinnytech.futures.constants.BroadcastConstants.TD_MESSAGE_WEAK_PASSWORD; /** * date: 7/9/17 * author: chenli * description: 服务器返回数据解析 * version: * state: basically done */ public class DataManager { private static final DataManager INSTANCE = new DataManager(); /** * date: 2018/11/7 * description: appVersion */ public String APP_VERSION = ""; /** * date: 2018/11/7 * description: appCode */ public int APP_CODE = 0; /** * date: 2019/4/16 * description: user_agent */ public String USER_AGENT = "android-github"; /** * date: 2019/6/24 * description: client_app_id */ public String CLIENT_APP_ID = "android-github"; /** * date: 2018/11/7 * description: 用户下单价格类型 */ public String PRICE_TYPE = "对手"; /** * date: 2018/12/13 * description: 持仓点击方向 */ public String POSITION_DIRECTION = ""; /** * date: 2019/3/18 * description: 是否显示副图判断 */ public boolean IS_SHOW_VP_CONTENT = false; /** * date: 2019/6/1 * description: 登录入口 */ public String LOGIN_TYPE = AMP_EVENT_LOGIN_TYPE_VALUE_AUTO; /** * date: 2019/6/1 * description: 期货公司及账号 */ public String BROKER_ID = ""; public String USER_ID = ""; /** * date: 2019/7/4 * description: 页面来源 */ public String SOURCE = ""; /** * date: 2019/3/18 * description: 用户最后一次发送的订阅请求 */ public String QUOTES = ""; public String CHARTS = ""; /** * date: 2019/4/19 * description: 用户最后一次切换的交易所 */ public String EXCHANGE_ID = ""; /** * date: 2019/7/4 * description: 进程开启时间 */ public long INIT_TIME = 0; /** * date: 2019/7/4 * description: 上一个事件时间 */ public long LAST_TIME = 0; /** * date: 2019/7/4 * description: 切前台时间 */ public long FOREGROUND_TIME = 0; /** * date: 2019/7/4 * description: 本事件次序 */ public Map<String, Long> COUNT = new HashMap<>(); /** * date: 2019/7/4 * description: 行情重连次数 */ public int MD_SESSION = 0; /** * date: 2019/7/4 * description: 交易重连次数 */ public int TD_SESSION = 0; /** * date: 2019/7/4 * description: 行情收包数 */ public int MD_PACK_COUNT = 0; /** * date: 2019/7/4 * description: 交易收包数 */ public int TD_PACK_COUNT = 0; private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss", Locale.getDefault()); /** * date: 7/9/17 * description: 账户信息实例 */ private TradeBean TRADE_DATA = new TradeBean(); /** * date: 7/9/17 * description: 单例模式,行情数据类实例 */ private FutureBean RTN_DATA = new FutureBean(); /** * date: 2019/8/8 * description: 条件单信息 */ private ConditionOrderBean CONDITION_ORDER_DATA = new ConditionOrderBean(); /** * date: 2019/8/12 * description: 历史条件单 */ private ConditionOrderBean CONDITION_ORDER_HIS_DATA = new ConditionOrderBean(); /** * date: 7/9/17 * description: 账户登录返回信息实例 */ private BrokerEntity BROKER = new BrokerEntity(); private DataManager() { simpleDateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai")); } public static DataManager getInstance() { return INSTANCE; } /** * date: 6/16/17 * author: chenli * description: 获取实例 */ public DiffEntity getRtnData() { return RTN_DATA.getData(); } public TradeBean getTradeBean() { return TRADE_DATA; } public ConditionOrderBean getConditionOrderBean() { return CONDITION_ORDER_DATA; } public BrokerEntity getBroker() { return BROKER; } public SimpleDateFormat getSimpleDateFormat() { return simpleDateFormat; } public ConditionOrderBean getHisConditionOrderBean() { return CONDITION_ORDER_HIS_DATA; } /** * date: 6/16/17 * author: chenli * description: 刷新行情数据,K线数据 */ public void refreshFutureBean(JSONObject rtnData) { try { JSONArray dataArray = rtnData.getJSONArray(PARSE_MARKET_KEY_DATA); DiffEntity diffEntity = RTN_DATA.getData(); for (int i = 0; i < dataArray.length(); i++) { if (dataArray.isNull(i)) continue; JSONObject dataObject = dataArray.getJSONObject(i); Iterator<String> iterator = dataObject.keys(); while (iterator.hasNext()) { String key0 = iterator.next(); if (dataObject.isNull(key0)) continue; switch (key0) { case PARSE_MARKET_KEY_QUOTES: parseQuotes(dataObject, diffEntity); break; case PARSE_MARKET_KEY_KLINES: parseKlines(dataObject, diffEntity); break; case PARSE_MARKET_KEY_TICKS: parseTicks(dataObject, diffEntity); break; case PARSE_MARKET_KEY_CHARTS: parseCharts(dataObject, diffEntity); break; case PARSE_MARKET_KEY_INS_LIST: diffEntity.setIns_list(dataObject.optString(key0)); break; case PARSE_MARKET_KEY_MDHIS_MORE_DATA: diffEntity.setMdhis_more_data(dataObject.optBoolean(key0)); break; default: break; } } } sendMessage(MD_MESSAGE, MD_BROADCAST); } catch (JSONException e) { e.printStackTrace(); } } private void parseCharts(JSONObject dataObject, DiffEntity diffEntity) throws JSONException { JSONObject chartsObject = dataObject.getJSONObject(PARSE_MARKET_KEY_CHARTS); Map<String, ChartEntity> chartsEntities = diffEntity.getCharts(); Iterator<String> iterator = chartsObject.keys(); while (iterator.hasNext()) { String key = iterator.next(); if (chartsObject.isNull(key)) continue; JSONObject chartObject = chartsObject.getJSONObject(key); ChartEntity chartEntity = chartsEntities.get(key); if (chartEntity == null) chartEntity = new ChartEntity(); Class clChart = chartEntity.getClass(); Iterator<String> iterator1 = chartObject.keys(); Map<String, String> stateEntity = chartEntity.getState(); while (iterator1.hasNext()) { String key1 = iterator1.next(); if (chartObject.isNull(key1)) continue; if (PARSE_MARKET_KEY_CHARTS_STATE.equals(key1)) { JSONObject stateObject = chartObject.optJSONObject(key1); Iterator<String> iterator511 = stateObject.keys(); while (iterator511.hasNext()) { String key511 = iterator511.next(); stateEntity.put(key511, stateObject.optString(key511)); } } else { try { Field f = clChart.getDeclaredField(key1); f.setAccessible(true); f.set(chartEntity, chartObject.optString(key1)); } catch (NoSuchFieldException e) { e.printStackTrace(); continue; } catch (IllegalAccessException e) { e.printStackTrace(); continue; } } } chartsEntities.put(key, chartEntity); } } private void parseTicks(JSONObject dataObject, DiffEntity diffEntity) throws JSONException { // JSONObject ticks = dataObject.getJSONObject("ticks"); // Iterator<String> iterator = ticks.keys(); // while (iterator.hasNext()) { // String key = iterator.next(); // } } private void parseKlines(JSONObject dataObject, DiffEntity diffEntity) throws JSONException { JSONObject futureKlineObjects = dataObject.getJSONObject(PARSE_MARKET_KEY_KLINES); Map<String, Map<String, KlineEntity>> futureKlineEntities = diffEntity.getKlines(); Iterator<String> iterator = futureKlineObjects.keys(); while (iterator.hasNext()) { String key = iterator.next(); //future "cu1601" if (futureKlineObjects.isNull(key)) continue; JSONObject futureKlineObject = futureKlineObjects.getJSONObject(key); Iterator<String> iterator1 = futureKlineObject.keys(); Map<String, KlineEntity> futureKlineEntity = futureKlineEntities.get(key); if (futureKlineEntity == null) futureKlineEntity = new HashMap<>(); while (iterator1.hasNext()) { String key1 = iterator1.next(); //kline"M3" if (futureKlineObject.isNull(key1)) continue; JSONObject klineObject = futureKlineObject.getJSONObject(key1); KlineEntity klineEntity = futureKlineEntity.get(key1); if (klineEntity == null) klineEntity = new KlineEntity(); Class clKline = klineEntity.getClass(); Iterator<String> iterator2 = klineObject.keys(); while (iterator2.hasNext()) { String key2 = iterator2.next(); if (klineObject.isNull(key2)) continue; switch (key2) { case PARSE_MARKET_KEY_KLINES_DATA: JSONObject dataObjects = klineObject.getJSONObject(key2); Iterator<String> iterator3 = dataObjects.keys(); Map<String, KlineEntity.DataEntity> dataEntities = klineEntity.getData(); while (iterator3.hasNext()) { String key3 = iterator3.next(); if (dataObjects.isNull(key3)) continue; JSONObject dataObjectInner = dataObjects.getJSONObject(key3); KlineEntity.DataEntity dataEntity = dataEntities.get(key3); Iterator<String> iterator4 = dataObjectInner.keys(); if (dataEntity == null) dataEntity = new KlineEntity.DataEntity(); Class clData = dataEntity.getClass(); while (iterator4.hasNext()) { String key4 = iterator4.next(); if (dataObjectInner.isNull(key4)) continue; try { Field f = clData.getDeclaredField(key4); f.setAccessible(true); f.set(dataEntity, dataObjectInner.optString(key4)); } catch (NoSuchFieldException e) { e.printStackTrace(); continue; } catch (IllegalAccessException e) { e.printStackTrace(); continue; } } dataEntities.put(key3, dataEntity); } break; case PARSE_MARKET_KEY_KLINES_BINDING: JSONObject bindingObjects = klineObject.getJSONObject(PARSE_MARKET_KEY_KLINES_BINDING); Iterator<String> iterator5 = bindingObjects.keys(); Map<String, KlineEntity.BindingEntity> bindingEntities = klineEntity.getBinding(); while (iterator5.hasNext()) { String key5 = iterator5.next(); if (bindingObjects.isNull(key5)) continue; JSONObject bindingObject = bindingObjects.getJSONObject(key5); KlineEntity.BindingEntity bindingEntity = bindingEntities.get(key5); Iterator<String> iterator6 = bindingObject.keys(); if (bindingEntity == null) { bindingEntity = new KlineEntity.BindingEntity(); } while (iterator6.hasNext()) { String key6 = iterator6.next(); if (bindingObject.isNull(key6)) continue; bindingEntity.getBindingData().put(key6, bindingObject.optString(key6)); } bindingEntities.put(key5, bindingEntity); } break; default: try { Field field = clKline.getDeclaredField(key2); field.setAccessible(true); field.set(klineEntity, klineObject.optString(key2)); } catch (NoSuchFieldException e) { e.printStackTrace(); continue; } catch (IllegalAccessException e) { e.printStackTrace(); continue; } break; } } futureKlineEntity.put(key1, klineEntity); } futureKlineEntities.put(key, futureKlineEntity); } } private void parseQuotes(JSONObject dataObject, DiffEntity diffEntity) throws JSONException { JSONObject quoteObjects = dataObject.getJSONObject(PARSE_MARKET_KEY_QUOTES); Map<String, QuoteEntity> quoteEntities = diffEntity.getQuotes(); Iterator<String> iterator = quoteObjects.keys(); while (iterator.hasNext()) { String key = iterator.next(); if (quoteObjects.isNull(key)) continue; JSONObject quoteObject = quoteObjects.getJSONObject(key); Iterator<String> iterator1 = quoteObject.keys(); QuoteEntity quoteEntity = quoteEntities.get(key); if (quoteEntity == null) quoteEntity = new QuoteEntity(); Class clQuote = quoteEntity.getClass(); while (iterator1.hasNext()) { String key1 = iterator1.next(); if (quoteObject.isNull(key1)) continue; try { Field f = clQuote.getDeclaredField(key1); f.setAccessible(true); f.set(quoteEntity, quoteObject.optString(key1)); } catch (NoSuchFieldException e) { e.printStackTrace(); continue; } catch (IllegalAccessException e) { e.printStackTrace(); continue; } } quoteEntities.put(key, quoteEntity); } } /** * date: 6/16/17 * author: chenli * description: 刷新登录信息 */ public void refreshTradeBean(JSONObject accountBeanObject) { try { JSONArray dataArray = accountBeanObject.getJSONArray(PARSE_TRADE_KEY_DATA); for (int i = 0; i < dataArray.length(); i++) { if (dataArray.isNull(i)) continue; JSONObject dataObject = dataArray.getJSONObject(i); Iterator<String> iterator = dataObject.keys(); while (iterator.hasNext()) { String key = iterator.next(); if (dataObject.isNull(key)) continue; JSONObject data = dataObject.getJSONObject(key); switch (key) { case PARSE_TRADE_KEY_NOTIFY: parseNotify(data); break; case PARSE_TRADE_KEY_TRADE: parseTrade(data); break; default: break; } } } } catch (JSONException e) { e.printStackTrace(); } } private void parseNotify(JSONObject data){ try { Iterator<String> notifyIterator = data.keys(); while (notifyIterator.hasNext()) { String notifyKey = notifyIterator.next(); if (data.isNull(notifyKey)) continue; JSONObject notify = data.getJSONObject(notifyKey); final String content = notify.optString(PARSE_TRADE_KEY_CONTENT); String level = notify.optString(PARSE_TRADE_KEY_LEVEL); int code = notify.optInt(PARSE_TRADE_KEY_CODE); //warning通知上报 if ("WARNING".equals(level)){ JSONObject jsonObject1 = new JSONObject(); try { jsonObject1.put(AMP_EVENT_NOTIFY_CONTENT, content); } catch (JSONException e) { e.printStackTrace(); } Amplitude.getInstance().logEventWrap(AMP_NOTIFY, jsonObject1); } //条件单已被服务器拒绝 if (code >= CODE_CONDITION_FAIL_LEFT && code <= CODE_CONDITION_FAIL_RIGHT){ Amplitude.getInstance().logEventWrap(AMP_CONDITION_FAILED, new JSONObject()); } //条件单下单成功 if (code == CODE_CONDITION_SUCCEED){ Amplitude.getInstance().logEventWrap(AMP_CONDITION_SUCCEED, new JSONObject()); } //修改密码成功通知 if (code == CODE_CHANGE_PASSWORD_SUCCEED) { sendMessage(TD_MESSAGE_CHANGE_SUCCESS, TD_BROADCAST); } //首次登录修改密码和弱密码提示 if ((code == CODE_CHANGE_PASSWORD_INIT) || (code == CODE_CHANGE_PASSWORD_WEAK)) { sendMessage(TD_MESSAGE_WEAK_PASSWORD, TD_BROADCAST); } //实盘登陆失败 if ((code >= CODE_LOGIN_FAIL_CTP_LEFT && code <= CODE_LOGIN_FAIL_CTP_RIGHT) || code == CODE_LOGIN_FAIL_SIMULATOR || code == CODE_LOGIN_PASSWORD_MISMATCH_CTP || code == CODE_LOGIN_PASSWORD_MISMATCH_SIMULATOR){ JSONObject jsonObject = new JSONObject(); try { jsonObject.put(AMP_EVENT_LOGIN_TYPE, LOGIN_TYPE); jsonObject.put(AMP_EVENT_LOGIN_FAIL_REASON, content); } catch (JSONException e) { e.printStackTrace(); } Amplitude.getInstance().logEventWrap(AMP_LOGIN_FAILED, jsonObject); sendMessage(TD_MESSAGE_LOGIN_FAIL, TD_BROADCAST); } //实盘登陆超时 if (code == CODE_LOGIN_TIMEOUT_CTP ){ sendMessage(TD_MESSAGE_LOGIN_TIMEOUT, TD_BROADCAST); } //游客模式和自动登录不弹出登陆成功提示 if ((CODE_LOGIN_SUCCEED_CTP == code || CODE_LOGIN_SUCCEED_SIMULATOR == code) && !LOGIN_TYPE.equals(AMP_EVENT_LOGIN_TYPE_VALUE_LOGIN)) continue; //实盘不提示"用户登录失败!",显示ctp给的提示 if (code >= CODE_LOGIN_FAIL_CTP_LEFT && code <= CODE_LOGIN_FAIL_CTP_RIGHT)continue; //CTP查询未就绪不显示 if (code == CODE_CHECK_UNREADY_CTP)continue; //结算单 if (code == CODE_SETTLEMENT) { BROKER.setSettlement(content); BROKER.setConfirmed(false); sendMessage(TD_MESSAGE_SETTLEMENT, TD_BROADCAST); continue; } new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { ToastUtils.showToast(BaseApplication.getContext(), content); } }); } } catch (JSONException e) { e.printStackTrace(); } } private void parseTrade(JSONObject data){ try { Map<String, UserEntity> userEntities = TRADE_DATA.getUsers(); Iterator<String> tradeIterator = data.keys(); while (tradeIterator.hasNext()) { String userKey = tradeIterator.next(); if (data.isNull(userKey)) continue; JSONObject user = data.getJSONObject(userKey); UserEntity userEntity = userEntities.get(userKey); if (userEntity == null) userEntity = new UserEntity(); Iterator<String> tradeDataIterator = user.keys(); while (tradeDataIterator.hasNext()) { String tradeDataKey = tradeDataIterator.next(); if (user.isNull(tradeDataKey)) continue; switch (tradeDataKey) { case PARSE_TRADE_KEY_ACCOUNTS: parseAccounts(user, userEntity); break; case PARSE_TRADE_KEY_ORDERS: parseOrders(user, userEntity); break; case PARSE_TRADE_KEY_POSITIONS: parsePositions(user, userEntity); break; case PARSE_TRADE_KEY_TRADES: parseTrades(user, userEntity); break; case PARSE_TRADE_KEY_BANKS: parseBanks(user, userEntity); break; case PARSE_TRADE_KEY_TRANSFERS: parseTransfers(user, userEntity); break; case PARSE_TRADE_KEY_SESSION: String userId = user.getJSONObject(PARSE_TRADE_KEY_SESSION). optString(PARSE_TRADE_KEY_USER_ID); if (USER_ID.equals(userId)) { userEntity.setUser_id(userId); Identify identify = new Identify() .setOnce(AMP_USER_ACCOUNT_ID_FIRST, USER_ID) .set(AMP_USER_ACCOUNT_ID_LAST, USER_ID) .setOnce(AMP_USER_BROKER_ID_FIRST, BROKER_ID) .set(AMP_USER_BROKER_ID_LAST, BROKER_ID); if (!(BROKER_ID_SIMULATION.equals(BROKER_ID) || BROKER_ID_SIMNOW.equals(BROKER_ID))) { long currentTime = System.currentTimeMillis(); long initTime = (long) SPUtils.get(BaseApplication.getContext(), CONFIG_INIT_TIME, currentTime); long loginTime = currentTime - initTime; identify.setOnce(AMP_USER_LOGIN_SUCCESS_TIME_FIRST, loginTime); } Amplitude.getInstance().identify(identify); JSONObject jsonObject = new JSONObject(); try { jsonObject.put(AMP_EVENT_LOGIN_TYPE, LOGIN_TYPE); } catch (JSONException e) { e.printStackTrace(); } Amplitude.getInstance().logEventWrap(AMP_LOGIN_SUCCEEDED, jsonObject); sendMessage(TD_MESSAGE_LOGIN_SUCCEED, TD_BROADCAST); } break; default: break; } } userEntities.put(userKey, userEntity); sendMessage(TD_MESSAGE, TD_BROADCAST); } }catch (JSONException e){ e.printStackTrace(); } } private void parseTransfers(JSONObject user, UserEntity userEntity) { try { JSONObject transferData = user.getJSONObject(PARSE_TRADE_KEY_TRANSFERS); Map<String, TransferEntity> transferEntities = userEntity.getTransfers(); Iterator<String> transferIterator = transferData.keys(); while (transferIterator.hasNext()) { String key = transferIterator.next(); if (transferData.isNull(key)) continue; JSONObject transferObject = transferData.getJSONObject(key); Iterator<String> iterator1 = transferObject.keys(); TransferEntity transferEntity = transferEntities.get(key); if (transferEntity == null) transferEntity = new TransferEntity(); Class clTransfer = transferEntity.getClass(); while (iterator1.hasNext()) { String key1 = iterator1.next(); if (transferObject.isNull(key1)) continue; try { Field f = clTransfer.getDeclaredField(key1); f.setAccessible(true); String data = transferObject.optString(key1); f.set(transferEntity, data); } catch (NoSuchFieldException e) { e.printStackTrace(); continue; } catch (IllegalAccessException e) { e.printStackTrace(); continue; } } transferEntity.setKey(key); transferEntities.put(key, transferEntity); } } catch (JSONException e) { e.printStackTrace(); } } private void parseBanks(JSONObject user, UserEntity userEntity) { try { JSONObject bankData = user.getJSONObject(PARSE_TRADE_KEY_BANKS); Map<String, BankEntity> bankEntities = userEntity.getBanks(); Iterator<String> bankIterator = bankData.keys(); while (bankIterator.hasNext()) { String key = bankIterator.next(); if (bankData.isNull(key)) continue; JSONObject bankObject = bankData.getJSONObject(key); Iterator<String> iterator1 = bankObject.keys(); BankEntity bankEntity = bankEntities.get(key); if (bankEntity == null) bankEntity = new BankEntity(); Class clBank = bankEntity.getClass(); while (iterator1.hasNext()) { String key1 = iterator1.next(); if (bankObject.isNull(key1)) continue; try { Field f = clBank.getDeclaredField(key1); f.setAccessible(true); String data = bankObject.optString(key1); f.set(bankEntity, data); } catch (NoSuchFieldException e) { e.printStackTrace(); continue; } catch (IllegalAccessException e) { e.printStackTrace(); continue; } } bankEntity.setKey(key); bankEntities.put(key, bankEntity); } } catch (JSONException e) { e.printStackTrace(); } } private void parseTrades(JSONObject user, UserEntity userEntity) { try { JSONObject tradeData = user.getJSONObject(PARSE_TRADE_KEY_TRADES); Map<String, TradeEntity> tradeEntities = userEntity.getTrades(); Iterator<String> tradeIterator = tradeData.keys(); while (tradeIterator.hasNext()) { String key = tradeIterator.next(); if (tradeData.isNull(key)) continue; JSONObject tradeObject = tradeData.getJSONObject(key); Iterator<String> iterator1 = tradeObject.keys(); TradeEntity tradeEntity = tradeEntities.get(key); if (tradeEntity == null) tradeEntity = new TradeEntity(); Class clTrade = tradeEntity.getClass(); while (iterator1.hasNext()) { String key1 = iterator1.next(); if (tradeObject.isNull(key1)) continue; try { Field f = clTrade.getDeclaredField(key1); f.setAccessible(true); String data = tradeObject.optString(key1); f.set(tradeEntity, data); } catch (NoSuchFieldException e) { e.printStackTrace(); continue; } catch (IllegalAccessException e) { e.printStackTrace(); continue; } } tradeEntity.setKey(key); tradeEntities.put(key, tradeEntity); } } catch (JSONException e) { e.printStackTrace(); } } private void parsePositions(JSONObject user, UserEntity userEntity) { try { JSONObject positionData = user.getJSONObject(PARSE_TRADE_KEY_POSITIONS); Map<String, PositionEntity> positionEntities = userEntity.getPositions(); Iterator<String> positionIterator = positionData.keys(); while (positionIterator.hasNext()) { String key = positionIterator.next(); if (positionData.isNull(key)) continue; JSONObject positionObject = positionData.getJSONObject(key); Iterator<String> iterator1 = positionObject.keys(); PositionEntity positionEntity = positionEntities.get(key); if (positionEntity == null) positionEntity = new PositionEntity(); Class clPosition = positionEntity.getClass(); while (iterator1.hasNext()) { String key1 = iterator1.next(); if (positionObject.isNull(key1)) continue; try { Field f = clPosition.getDeclaredField(key1); f.setAccessible(true); String data = positionObject.optString(key1); f.set(positionEntity, data); } catch (NoSuchFieldException e) { // e.printStackTrace(); continue; } catch (IllegalAccessException e) { // e.printStackTrace(); continue; } } positionEntity.setKey(key); positionEntities.put(key, positionEntity); } } catch (JSONException e) { e.printStackTrace(); } } private void parseOrders(JSONObject user, UserEntity userEntity) { try { JSONObject orderData = user.getJSONObject(PARSE_TRADE_KEY_ORDERS); final Map<String, OrderEntity> orderEntities = userEntity.getOrders(); Iterator<String> orderIterator = orderData.keys(); while (orderIterator.hasNext()) { String key = orderIterator.next(); if (orderData.isNull(key)) continue; JSONObject orderObject = orderData.getJSONObject(key); Iterator<String> iterator1 = orderObject.keys(); OrderEntity orderEntity = orderEntities.get(key); if (orderEntity == null) orderEntity = new OrderEntity(); Class clOrder = orderEntity.getClass(); while (iterator1.hasNext()) { String key1 = iterator1.next(); if (orderObject.isNull(key1)) continue; try { Field f = clOrder.getDeclaredField(key1); f.setAccessible(true); String data = orderObject.optString(key1); f.set(orderEntity, data); } catch (NoSuchFieldException e) { e.printStackTrace(); continue; } catch (IllegalAccessException e) { e.printStackTrace(); continue; } } orderEntity.setKey(key); orderEntities.put(key, orderEntity); } } catch (JSONException e) { e.printStackTrace(); } } private void parseAccounts(JSONObject user, UserEntity userEntity) { try { JSONObject accountData = user.getJSONObject(PARSE_TRADE_KEY_ACCOUNTS); Map<String, AccountEntity> accountEntities = userEntity.getAccounts(); Iterator<String> accountIterator = accountData.keys(); while (accountIterator.hasNext()) { String key = accountIterator.next(); if (accountData.isNull(key)) continue; JSONObject accountObject = accountData.getJSONObject(key); AccountEntity accountEntity = accountEntities.get(key); if (accountEntity == null) accountEntity = new AccountEntity(); Class clAccount = accountEntity.getClass(); Iterator<String> iterator1 = accountObject.keys(); while (iterator1.hasNext()) { String key1 = iterator1.next(); if (accountObject.isNull(key1)) continue; try { Field f = clAccount.getDeclaredField(key1); f.setAccessible(true); f.set(accountEntity, accountObject.optString(key1)); } catch (NoSuchFieldException e) { e.printStackTrace(); continue; } catch (IllegalAccessException e) { e.printStackTrace(); continue; } } accountEntity.setKey(key); accountEntities.put(key, accountEntity); } } catch (JSONException e) { e.printStackTrace(); } } /** * date: 2019/8/8 * author: chenli * description: 刷新条件单信息 */ public void refreshConditionOrderBean(JSONObject conditionOrderBeanObject, String aid) { try { JSONArray dataArray; String user_id = conditionOrderBeanObject.optString(PARSE_CONDITION_KEY_USER_ID); String trading_day = conditionOrderBeanObject.optString(PARSE_CONDITION_KEY_TRADING_DAY); ConditionUserEntity conditionUserEntity; if (aid.equals(PARSE_CONDITION_KEY_RTN_CONDITION_ORDERS)){ CONDITION_ORDER_DATA.setUser_id(user_id); CONDITION_ORDER_DATA.setTrading_day(trading_day); dataArray = conditionOrderBeanObject.getJSONArray(PARSE_CONDITION_KEY_CONDITION_ORDERS); conditionUserEntity = CONDITION_ORDER_DATA.getUsers().get(user_id); }else { CONDITION_ORDER_HIS_DATA.setUser_id(user_id); CONDITION_ORDER_HIS_DATA.setTrading_day(trading_day); dataArray = conditionOrderBeanObject.getJSONArray(PARSE_CONDITION_KEY_HIS_CONDITION_ORDERS); conditionUserEntity = CONDITION_ORDER_HIS_DATA.getUsers().get(user_id); } if (conditionUserEntity == null)conditionUserEntity = new ConditionUserEntity(); for (int i = 0; i < dataArray.length(); i++) { if (dataArray.isNull(i)) continue; JSONObject dataObject = dataArray.getJSONObject(i); String order_id = dataObject.optString(PARSE_CONDITION_KEY_ORDER_ID); ConditionOrderEntity conditionOrderEntity = conditionUserEntity.getCondition_orders().get(order_id); if (conditionOrderEntity == null) conditionOrderEntity = new ConditionOrderEntity(); Class clConditionOrder = conditionOrderEntity.getClass(); Iterator<String> iterator = dataObject.keys(); while (iterator.hasNext()) { String key = iterator.next(); if (dataObject.isNull(key)) continue; switch (key) { case PARSE_CONDITION_KEY_CONDITION_LIST: parseConditionList(conditionOrderEntity, dataObject, key); break; case PARSE_CONDITION_KEY_ORDER_LIST: parseOrderList(conditionOrderEntity, dataObject, key); break; default: try { Field f = clConditionOrder.getDeclaredField(key); f.setAccessible(true); f.set(conditionOrderEntity, dataObject.optString(key)); } catch (NoSuchFieldException e) { e.printStackTrace(); continue; } catch (IllegalAccessException e) { e.printStackTrace(); continue; } break; } } conditionUserEntity.getCondition_orders().put(order_id, conditionOrderEntity); } if (aid.equals(PARSE_CONDITION_KEY_RTN_CONDITION_ORDERS)){ CONDITION_ORDER_DATA.getUsers().put(user_id, conditionUserEntity); sendMessage(CO_MESSAGE, CO_BROADCAST); }else { CONDITION_ORDER_HIS_DATA.getUsers().put(user_id, conditionUserEntity); sendMessage(CO_HIS_MESSAGE, CO_BROADCAST); } } catch (JSONException e) { e.printStackTrace(); } } /** * date: 2019/8/8 * author: chenli * description: 解析条件 */ private void parseConditionList(ConditionOrderEntity conditionOrderEntity, JSONObject dataObject, String key){ try { JSONArray conditionArray = dataObject.optJSONArray(key); List<ConditionEntity> conditionList = new ArrayList<>(); for (int conditionIndex = 0; conditionIndex < conditionArray.length(); conditionIndex++) { if (conditionArray.isNull(conditionIndex)) continue; JSONObject conditionObject = conditionArray.getJSONObject(conditionIndex); ConditionEntity conditionEntity = new ConditionEntity(); Class clCondition = conditionEntity.getClass(); Iterator<String> iterator = conditionObject.keys(); while (iterator.hasNext()) { String key1 = iterator.next(); if (conditionObject.isNull(key1)) continue; try { Field f = clCondition.getDeclaredField(key1); f.setAccessible(true); f.set(conditionEntity, conditionObject.optString(key1)); } catch (NoSuchFieldException e) { e.printStackTrace(); continue; } catch (IllegalAccessException e) { e.printStackTrace(); continue; } } conditionList.add(conditionEntity); } conditionOrderEntity.setCondition_list(conditionList); }catch (Exception e){ e.printStackTrace(); } } /** * date: 2019/8/8 * author: chenli * description: 解析单子 */ private void parseOrderList(ConditionOrderEntity conditionOrderEntity, JSONObject dataObject, String key){ try { JSONArray orderArray = dataObject.optJSONArray(key); List<COrderEntity> orderList = new ArrayList<>(); for (int orderIndex = 0; orderIndex < orderArray.length(); orderIndex++) { if (orderArray.isNull(orderIndex)) continue; JSONObject orderObject = orderArray.getJSONObject(orderIndex); COrderEntity orderEntity = new COrderEntity(); Class clOrder = orderEntity.getClass(); Iterator<String> iterator = orderObject.keys(); while (iterator.hasNext()) { String key1 = iterator.next(); if (orderObject.isNull(key1)) continue; try { Field f = clOrder.getDeclaredField(key1); f.setAccessible(true); f.set(orderEntity, orderObject.optString(key1)); } catch (NoSuchFieldException e) { e.printStackTrace(); continue; } catch (IllegalAccessException e) { e.printStackTrace(); continue; } } orderList.add(orderEntity); } conditionOrderEntity.setOrder_list(orderList); }catch (Exception e){ e.printStackTrace(); } } }
shinnytech/shinny-futures-android
app/src/main/java/com/shinnytech/futures/model/engine/DataManager.java
66,336
package moe.protector.pe.game; import android.util.Log; import com.alibaba.fastjson.JSON; import java.util.ArrayList; import java.util.List; import moe.protector.pe.bean.challenge.DealtoBean; import moe.protector.pe.bean.challenge.GetChallengeListBean; import moe.protector.pe.bean.challenge.GetResultBean; import moe.protector.pe.bean.challenge.SpyBean; import moe.protector.pe.bean.common.FleetVo; import moe.protector.pe.bean.friend.FriendGetlistBean; import moe.protector.pe.bean.friend.FriendVisitorFriendBean; import moe.protector.pe.bean.task.TaskBean; import moe.protector.pe.exception.HmException; import moe.protector.pe.util.CommonUtil; public class GamePvp extends GameBattle { private static final String TAG = "GamePvp"; private int format; private int fleet; private boolean doNightWar; public GamePvp(TaskBean taskBean) { this.format = taskBean.pvpData.format; this.fleet = taskBean.pvpData.fleet; this.doNightWar = taskBean.pvpData.night; } public enum Finish { FINISH, ERROR } public Finish execute() { try { List<PvpUser> pvpList = new ArrayList<>(); // 获取演习列表 GetChallengeListBean getPvpList = this.getChallengeList(); for (GetChallengeListBean.UserList user : getPvpList.list) { if (user.resultLevel == 0) { pvpList.add(new PvpUser(user.uid, "pvp", user.username, user.fleetName)); } } // 获取好友列表 List<PvpUser> friendList = new ArrayList<>(); String friendData = netSender.friendGetlist(); FriendGetlistBean friendGetlistBean = JSON.parseObject(friendData, FriendGetlistBean.class); for (FriendGetlistBean.Friend friend : friendGetlistBean.list) { String data = netSender.friendVisitorFriend(friend.uid); FriendVisitorFriendBean visitorFriend = JSON.parseObject(data, FriendVisitorFriendBean.class); if (3 - visitorFriend.challengeNum - friendList.size() <= 0) { break; } if (visitorFriend.challengeScore == 0 && visitorFriend.friendFleet.size() > 0) { friendList.add(new PvpUser(friend.uid, "friend", friend.username, "驻防编队")); } } pvpList.addAll(friendList); while (pvpList.size() > 0) { PvpUser user = pvpList.get(0); UserData userData = UserData.getInstance(); FleetVo fleetVo = userData.getFleet().get(String.valueOf(this.fleet)); // 开始演习逻辑 head = user.type; // 演习索敌 SpyBean spyBean = this.pvpSpy(head, user.uid, this.fleet); // 获取索敌数据 UIUpdate.detailLog(TAG, "[演习] " + (user.type.equals("pvp") ? "对手" : "好友") + ": " + user.username + "-" + user.fleetName); CommonUtil.delay(2000); // 开始战斗 DealtoBean dealtoBean = this.pvpChallenge(head, user.uid, this.fleet, this.format); int randomInt = CommonUtil.randomInt(10, 20); UIUpdate.detailLog(TAG, "[演习] 开始战斗, 等待" + randomInt + "s"); CommonUtil.delay(randomInt * 1000); // 准备夜战 GetResultBean resultBean = this.challengeGetWarResult(head, dealtoBean.warReport.canDoNightWar == 1 && this.doNightWar); if (dealtoBean.warReport.canDoNightWar == 1) { randomInt = CommonUtil.randomInt(10, 15); UIUpdate.detailLog(TAG, "[演习] 夜战中, 等待" + randomInt + "s"); CommonUtil.delay(randomInt * 1000); } // 战斗结束 String[] assess = {"-", "SS", "S", "A", "B", "C", "D"}; String resultLevel = assess[resultBean.warResult.resultLevel]; // 获取mvp String mvp = "-"; for (int i = 0; i < fleetVo.ships.size(); i++) { GetResultBean.ShipResult result = resultBean.warResult.selfShipResults.get(i); if (result.isMvp == 1) { mvp = userData.getShipName(fleetVo.ships.get(i)); } } // 更新任务 if (resultBean.updateTaskVo != null) { userData.updateTaskVo(resultBean.updateTaskVo); } UIUpdate.log(TAG, String.format("[演习] %s 评价:%s mvp:<%s>", user.username, resultLevel, mvp)); CommonUtil.delay(5000); pvpList.remove(0); } return Finish.FINISH; } catch (HmException e) { Log.e(TAG, "演习出错:" + e.getCode() + e.getMessage()); } return Finish.ERROR; } } class PvpUser { String uid; String type; String username; String fleetName; PvpUser(String uid, String type, String username, String fleetName) { this.uid = uid; this.type = type; this.username = username; this.fleetName = fleetName; } }
ProtectorMoe/pe-protector-moe
app/src/main/java/moe/protector/pe/game/GamePvp.java
66,337
package com.fivechess.view; import com.fivechess.model.*; import com.fivechess.net.*; import javax.management.MBeanAttributeInfo; import javax.swing.*; import org.apache.log4j.Logger; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.util.ArrayList; /** * 人人对战页面 * 接收信息线程 * @author admin */ public class PPMainBoard extends MainBoard { private PPChessBoard cb; private JButton startGame; private JButton exitGame; private JButton back;//悔棋按钮 private JButton send; //聊天发送按钮 private JLabel timecount;//计时器标签 //双方状态 private JLabel people1;//自己标签 private JLabel people2;//对手标签 private JLabel p1lv;//自己等级标签 private JLabel p2lv;//对手等级标签 private JLabel situation1;//自己状态标签 private JLabel situation2;//对手状态标签 private JLabel jLabel1; private JLabel jLabel2;// private JTextArea talkArea; private JTextField tf_ip; //输入IP框 private JTextField talkField; //聊天文本框 private String ip; private DatagramSocket socket; private String gameState; private String enemyGameState;//敌人状态 private Logger logger = Logger.getLogger("游戏"); public JButton getstart(){return startGame;} public String getIp() {return ip;} public JTextField getTf() {return tf_ip;} public DatagramSocket getSocket() {return socket;} public JLabel getLabel1(){return jLabel1;} public JLabel getLabel2(){return jLabel2;} public JLabel getSituation1(){return situation1;} public JLabel getSituation2(){return situation2;} public PPMainBoard() { init(); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } /** * 初始化页面 */ public void init() { gameState="NOT_START"; enemyGameState="NOT_START"; cb=new PPChessBoard(this); cb.setClickable(PPMainBoard.CAN_NOT_CLICK_INFO); cb.setBounds(210, 40, 570, 585); cb.setVisible(true); cb.setInfoBoard(talkArea); tf_ip=new JTextField("请输入对手IP地址"); tf_ip.setBounds(780, 75, 200, 30); tf_ip.addMouseListener(this); startGame=new JButton("准备游戏");//设置名称,下同 startGame.setBounds(780,130, 200, 50);//设置起始位置,宽度和高度,下同 startGame.setBackground(new Color(50,205,50));//设置颜色,下同 startGame.setFont(new Font("宋体", Font.BOLD, 20));//设置字体,下同 startGame.addActionListener(this); back=new JButton("悔 棋"); back.setBounds(780, 185, 200, 50); back.setBackground(new Color(85,107,47)); back.setFont(new Font("宋体", Font.BOLD, 20)); back.addActionListener(this); send=new JButton("发送"); send.setBounds(840, 550, 60, 30); send.setBackground(new Color(50,205,50)); send.addActionListener(this); talkField=new JTextField("聊天"); talkField.setBounds(780, 510, 200, 30); talkField.addMouseListener(this); exitGame=new JButton("返 回"); exitGame.setBackground(new Color(218,165,32)); exitGame.setBounds(780,240,200,50); exitGame.setFont(new Font("宋体", Font.BOLD, 20));//设置字体,下同 exitGame.addActionListener(this); people1=new JLabel(" 我:"); people1.setOpaque(true); people1.setBackground(new Color(82,109,165)); people1.setBounds(10,410,200,50); people1.setFont(new Font("宋体", Font.BOLD, 20)); people2=new JLabel(" 对手:"); people2.setOpaque(true); people2.setBackground(new Color(82,109,165)); people2.setBounds(10,75,200,50); people2.setFont(new Font("宋体", Font.BOLD, 20)); timecount=new JLabel(" 计时器:"); timecount.setBounds(320,1,200,50); timecount.setFont(new Font("宋体", Font.BOLD, 30)); p1lv=new JLabel(" 等 级:LV.1"); p1lv.setOpaque(true); p1lv.setBackground(new Color(82,109,165)); p1lv.setBounds(10,130,200,50); p1lv.setFont(new Font("宋体", Font.BOLD, 20)); p2lv=new JLabel(" 等 级:LV.1"); p2lv.setOpaque(true); p2lv.setBackground(new Color(82,109,165)); p2lv.setBounds(10,465,200,50); p2lv.setFont(new Font("宋体", Font.BOLD, 20)); situation1=new JLabel(" 状态:"); situation1.setOpaque(true); situation1.setBackground(new Color(82,109,165)); situation1.setBounds(10,185,200,50); situation1.setFont(new Font("宋体", Font.BOLD, 20)); situation2=new JLabel(" 状态:"); situation2.setOpaque(true); situation2.setBackground(new Color(82,109,165)); situation2.setBounds(10,520,200,50); situation2.setFont(new Font("宋体", Font.BOLD, 20)); jLabel1 = new JLabel(); add(jLabel1); jLabel1.setBounds(130,75,200,50); jLabel2 = new JLabel(); add(jLabel2); jLabel2.setBounds(130,410,200,50); timecount=new JLabel(" 计时器:"); timecount.setBounds(320,1,200,50); timecount.setFont(new Font("宋体", Font.BOLD, 30)); talkArea=new JTextArea(); //对弈信息 talkArea.setEnabled(false); talkArea.setBackground(Color.BLUE); //滑动条 JScrollPane p = new JScrollPane(talkArea); p.setBounds(780, 295, 200, 200); add(tf_ip); add(cb); add(startGame); add(back); add(exitGame); add(people1); add(people2); add(p1lv); add(p2lv); add(situation1); add(situation2); add(timecount); add(p); add(send); add(talkField); //加载线程 ReicThread(); repaint(); } /** * 接收信息放在线程中 */ public void ReicThread() { new Thread(new Runnable() { public void run() { try { byte buf[]=new byte[1024]; socket=new DatagramSocket(10086); DatagramPacket dp=new DatagramPacket(buf, buf.length); while(true) { socket.receive(dp); //0.接收到的发送端的主机名 InetAddress ia=dp.getAddress(); //enemyMsg.add(new String(ia.getHostName())); //对方端口 logger.info("对手IP:"+ia.getHostName()); //1.接收到的内容 String data=new String(dp.getData(),0,dp.getLength()); if(data.isEmpty()) { cb.setClickable(MainBoard.CAN_NOT_CLICK_INFO); } else { String[] msg = data.split(","); System.out.println(msg[0]+" "+msg[1]); //接收到对面准备信息并且自己点击了准备 if(msg[0].equals("ready")) { enemyGameState="ready"; System.out.println("对方已准备"); if(gameState.equals("ready")) { gameState="FIGHTING"; cb.setClickable(MainBoard.CAN_CLICK_INFO); startGame.setText("正在游戏"); situation1.setText(" 状态:等待..."); situation2.setText(" 状态:下棋..."); logger.info("等待对方消息"); timer=new TimeThread(label_timeCount); timer.start(); } } else if(msg[0].equals("POS")){ System.out.println("发送坐标"); //接受坐标以及角色 situation1.setText(" 状态:等待..."); situation2.setText(" 状态:下棋..."); //重新启动计时线程 timer=new TimeThread(label_timeCount); timer.start(); cb.setCoord(Integer.parseInt(msg[1]), Integer.parseInt(msg[2]), Integer.parseInt(msg[3])); } else if(msg[0].equals("enemy")) { talkArea.append("对手:"+msg[1]+"\n"); logger.info("对手发送的消息"+msg[1]); } else if(msg[0].equals("back")) { int n=JOptionPane.showConfirmDialog(cb, "是否同意对方悔棋", "选择",JOptionPane.YES_NO_OPTION); //点击确定按钮则可以悔棋 if(n==JOptionPane.YES_OPTION) { cb.backstep(); NetTool.sendUDPBroadCast(ia.getHostName(), "canBack"+", "); } else { NetTool.sendUDPBroadCast(ia.getHostName(), "noBack"+", "); } } //允许悔棋 else if(msg[0].equals("canBack")) { JOptionPane.showMessageDialog(cb, "对方允许您悔棋"); cb.backstep(); } //不允许悔棋 else if(msg[0].equals("noBack")) { JOptionPane.showMessageDialog(cb, "对方不允许您悔棋"); } } } } catch(Exception e) { e.printStackTrace(); } } }).start(); } @Override public void actionPerformed(ActionEvent e) { if(e.getSource()==startGame) { if(!tf_ip.getText().isEmpty()&& !tf_ip.getText().equals("不能为空")&& !tf_ip.getText().equals("请输入IP地址")&& !tf_ip.getText().equals("不能连接到此IP")) { ip=tf_ip.getText(); startGame.setEnabled(false); startGame.setText("等待对方准备"); tf_ip.setEditable(false); //发送准备好信息 NetTool.sendUDPBroadCast(ip,"ready, "); gameState="ready"; if(enemyGameState=="ready") { gameState="FIGHTING"; cb.setClickable(CAN_CLICK_INFO); startGame.setText("正在游戏"); situation1.setText(" 状态:等待..."); situation2.setText(" 状态:下棋..."); timer=new TimeThread(label_timeCount); timer.start(); } } else { tf_ip.setText("不能为空"); } } //点击悔棋后的操作 else if(e.getSource()==back) { //发送悔棋信息 NetTool.sendUDPBroadCast(ip,"back"+", "); logger.info("玩家选择悔棋"); } // 聊天发送按钮 else if(e.getSource()==send) { if(!talkField.getText().isEmpty()&&!talkField.getText().equals("不能为空")) { //获得输入的内容 String msg=talkField.getText(); talkArea.append("我:"+msg+"\n"); talkField.setText(""); ip=tf_ip.getText(); NetTool.sendUDPBroadCast(ip,"enemy"+","+msg); } else { talkField.setText("不能为空"); } } //退出游戏,加载主菜单 else if(e.getSource()==exitGame) { dispose(); new SelectMenu(); } } @Override public void mouseClicked(MouseEvent e) { if(e.getSource()==tf_ip) { tf_ip.setText(""); } else if(e.getSource()==talkField) { talkField.setText(""); } } }
kingdomrushing/FiveChess
src/com/fivechess/view/PPMainBoard.java
66,338
import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.ListIterator; import java.util.Random; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; enum State{ //翻牌前状态 翻牌 转牌 和牌 PRE_FLOP, FLOP, TURN, RIVER } class Position{ public static final int EARLY_POS = 0, // 靠前位置 MID_POS = 1, // 中间位置 LATE_POS = 2, //靠后位置 SBLIND_POS = 3, //小盲注位置 BLIND_POS = 4; //大盲注位置 } // 游戏风格 enum GameStyle{ // 宽松的 LOOSE_GAME, MODERATE_GAME, // 大家都很保守 TIGHT_GAME; } class Player implements MsgCallback{ // ThreadPoolExecutor threadPool = // new ThreadPoolExecutor(4, 16, 10, TimeUnit.MINUTES, new LinkedBlockingQueue<Runnable>()); private final int ALL_ROUND_NUM = 600; // 保存对手信息,key=ID private HashMap<String, Opponent> opponents = new HashMap<String, Opponent>(11); // 当前轮没有弃牌的对手 private HashSet<String> aliveOpp = new HashSet<String>(11); // 用来保存inquire或者Notify消息里面当前玩家的顺序 private LinkedList<InqNotifyMsg> curMsgList = new LinkedList<InqNotifyMsg>(); // 保存上一圈(轮)的msg消息 private LinkedList<InqNotifyMsg> preMsgList = new LinkedList<InqNotifyMsg>(); // 表示我当前的行为和赌注 private String myLastAction = "", myCurAction = ""; private int myPreBet = 0; // 表示当前是该round的第几圈,对于统计信息有用. private int circle = 0; // 我的游戏风格,一开始要稳健 private GameStyle myGameStyle = GameStyle.LOOSE_GAME; /* 使用base-incre 决策时,默认的probability_play * probability_play:在preflop不fold的玩家的百分比 */ private final double PLAY_ODDS_DEFAULT = 0.6f; // 上次计算的值 private double lastCacPlayOdds = PLAY_ODDS_DEFAULT; private double probability_play[] = new double[600]; private int probPlayIdx = 0; private int foldPreFlop = 0; // 在inquire消息里面,出现了多少个player private int playerCntInInquire = 0; // 筹码保护时的handStrength private final double JettonProtectHS = 0.70f; private final double HANDSTRENGTH_REDUCE = 0.15f; private final double STRENGTH_DRAW_INCREASE = 0.50f; /* 打法是不是紧的,false=松,大胆; true=紧,谨慎 * 如果金钱排名>=4,则采用紧的打法,否则采用松的打法 */ private boolean isTight = true; // 还有多少局剩余 private int remainTurn = ALL_ROUND_NUM; private int lastRound = 1; // 之前是第几局 // 牌值评估程序 private KRHandEvaluator handEval; // 当前到了哪个阶段 private State currentState = State.PRE_FLOP; // 统计轮到我行动时前面选手的行动 private int allinCnt, foldCnt, callCnt, raiseCnt, checkCnt, blindCnt; // 如果要跟住,需要下的最小注 private int minBet; // 当前已经下注的钱 private int myCurBet; private int bigBlindBet; // 我所有的钱和筹码 private int myAllMoney = 2000, myAllJetton = 2000; // 表示我总共的钱-敌人总共的钱 private int moneyGap; // 是否是顺子听筒(差一张顺子) private boolean isStraightDraw = false; // 是否是同花听筒 private boolean isFlushDraw = false; // 当前位置 private int myCurPos; // 与庄家的距离,SB=1, BB=2; private int awayFromBtn; // 记录自己每一轮加注了多少次 private int raisePreFlopCnt = 0, raiseFLopCnt = 0, raiseTurnCnt = 0, raiseRiverCnt = 0; // 至少要加注多少 private int leastRaise = 0; // semi-bluff ,turn和river用到 private boolean semiBluffFlag = false; // 当前底池总金额(本轮投注已累计) private int totalPot; // 两张底牌 private int rank1, suit1, rank2, suit2; // 公共牌 private int shareRank[] = new int[6]; private int shareSuit[] = new int[6]; // 在使用KRHandEval时用到 private int boardCardVal[] = new int[6]; private static int shareIdx; // 下标 private final String CALL = "call"; // 跟住 private final String CHECK = "check"; // 让牌 private final String RAISE = "raise"; // 加注 private final String ALL_IN = "all_in"; // 全压 private final String FOLD = "fold"; // 弃牌 private final String BLIND = "blind"; // 盲注 private final String DIAMONDS = "DIAMONDS"; // 方块 private final String SPADES = "SPADES"; // 黑桃 private final String CLUBS = "CLUBS"; // 梅花 private final String HEARTS = "HEARTS"; // 红桃 private String serverIp, localIp, ID, name; private int serverPort, localPort; private SocketThread thread; // 上次记录时,有多少个选手,用于每减少2个人,重置一次foldpreflop统计 private int preAllPlayerNums = 0; // 这场比赛有多少个选手 private int allPlayerNums = 0; // 当前这轮还有多少个选手(除去Fold的) private int curHandPlayerNums = 0; public Player() { name = "PokerFace"; } public Player(String sIp, int sPort, String lIp, int lPort, String id) { serverIp = sIp; serverPort = sPort; localIp = lIp; localPort = lPort; ID = id; name = "PokerFace"; } /** * 根据opponents保存的信息获取游戏风格(至少要玩40局才知道) * @return */ private GameStyle getGameStyle() { int round = ALL_ROUND_NUM - remainTurn; if(round < 40) { // 才玩40局不到 return GameStyle.TIGHT_GAME; } int players = opponents.size(); int tightCnt = 0; for(Opponent opp : opponents.values()) { Logger.Log("opp:"+opp); if(opp.isTight(round)) { tightCnt++; } } double p = (double)tightCnt / players; if(p >= 0.7f) { // 70%都是tight,也就是7个对手至少有5个是tight return GameStyle.TIGHT_GAME; }else{ return GameStyle.LOOSE_GAME; } } // 用来判断是否是顺子听筒 private int pokerCnt[] = new int[15]; // 公牌是否是听筒状态 private boolean isBoardStraightDraw() { for(int i = 0; i < 15; i++) pokerCnt[i] = 0; for(int i = 0; i < shareIdx; i++) { pokerCnt[shareRank[i]]++; } boolean flag = false; if(pokerCnt[Poker.A] == 1 && pokerCnt[2] == 1 && pokerCnt[3] == 1 && pokerCnt[4] == 1 ) { // 特殊的A,2,3,4,5也是顺子 return true; } // 在点数范围判断 int i = 2, j = i; // J以后就没有可能连成顺子了 while(i < Poker.J && !flag) { if(pokerCnt[i] != 0) { // i处值不为0,i处开始判断是否有连续4个不为0 for(j = i+1; j < i+4; j++) { if(pokerCnt[j] == 0) { // j处为0,i从j的下一个开始判断 i = j +1; break; } } if(j - i == 4){ // 能走完循环,说明是顺子 flag = true; } }else{ i++; } } return flag; } // 是否是顺子听筒 private boolean isStraightDraw() { for(int i = 0; i < 15; i++) pokerCnt[i] = 0; for(int i = 0; i < shareIdx; i++) { pokerCnt[shareRank[i]]++; } pokerCnt[rank1]++; pokerCnt[rank2]++; boolean flag = false; if(pokerCnt[Poker.A] == 1 && pokerCnt[2] == 1 && pokerCnt[3] == 1 && pokerCnt[4] == 1 && pokerCnt[5] == 1 ) { // 特殊的A,2,3,4,5也是顺子 return true; } // 在点数范围判断 int i = 2, j = i; // J以后就没有可能连成顺子了 while(i < Poker.J && !flag) { if(pokerCnt[i] != 0) { // i处值不为0,i处开始判断是否有连续4个不为0 for(j = i+1; j < i+4; j++) { if(pokerCnt[j] == 0) { // j处为0,i从j的下一个开始判断 i = j +1; break; } } if(j - i == 4){ // 能走完循环,说明是顺子 flag = true; } }else{ i++; } } return flag; } // 是否是同花听筒 private boolean isFlushDraw() { boolean flag = false; int scnt = 0, hcnt = 0, ccnt = 0, dcnt = 0; for(int i = 0; i < shareIdx; i++) { switch(shareSuit[i]){ case Poker.Clubs: ccnt++; break; case Poker.Diamonds: dcnt++; break; case Poker.Hearts: hcnt++; break; case Poker.Spades: scnt++; break; } } switch(suit1){ case Poker.Clubs: ccnt++; break; case Poker.Diamonds: dcnt++; break; case Poker.Hearts: hcnt++; break; case Poker.Spades: scnt++; break; } switch(suit2){ case Poker.Clubs: ccnt++; break; case Poker.Diamonds: dcnt++; break; case Poker.Hearts: hcnt++; break; case Poker.Spades: scnt++; break; } if(ccnt == 4 || dcnt == 4 || hcnt == 4 || scnt == 4) { flag = true; } return flag; } // 首先交换底牌1和2的点数,保证rank1>rank2 private void exchangePocket() { // 首先交换底牌1和2的点数,保证rank1>rank2 if(rank2 > rank1) { int tmp = rank2; rank2 = rank1; rank1 = tmp; // 交换花色 tmp = suit2; suit2 = suit1; suit1 = tmp; } } //volatile double calEhsRes[] = new double[2]; /** * 开线程计算,如果超时则返回false * @return */ private double[] calEHS() { double res[] = handEval.calEHS(); double ppot = res[0]; double strength = res[1]; if(aliveOpp.size() > 0) { strength = Math.pow(strength, aliveOpp.size()); } double ehs = strength + (1-strength)*ppot; res[1] = ehs; return res; // ExecutorService exs = Executors.newSingleThreadExecutor(); // exs.execute(new Runnable() { // // @Override // public void run() { // calEhsRes = handEval.calEHS(); // } // }); // exs.shutdown(); // try { // boolean done = exs.awaitTermination(350, TimeUnit.MILLISECONDS); // double ppot = calEhsRes[0]; // double strength = calEhsRes[1]; // if(aliveOpp.size() > 0) { // strength = Math.pow(strength, aliveOpp.size()); // } // double ehs = strength + (1-strength)*ppot; // Logger.Log("strength="+calEhsRes[1]+" afterStrength="+strength+" ppot="+ppot // +" ehs="+ehs); // calEhsRes[1] = ehs; // return done; // } catch (InterruptedException e) { // Logger.Log("InterruptedException:"+e.getMessage()); // } // return false; } // 当钱已经很多时,适当降低出手率 private double keepMoneyStrategy(double strength) { if(strength >= 0.90) { // 够牛逼了 上! return strength; } if (willWin()) { // 已经会赢啦,你们慢慢打 return 0.01f; } if (moneyGap > 0 && allPlayerNums > 2) { // 钱多,要悠着打 strength -= HANDSTRENGTH_REDUCE; } return strength; } /** * 计算回报率 * @return */ private double calRateOfReturn(double strength) { if(isJettonProtect(strength)) { // 需要金币保护 return 0; } strength = keepMoneyStrategy(strength); double potOdds = (double)(totalPot - myCurBet)/(totalPot + minBet); double RR = strength / potOdds; return RR; } /** * 返回可组成的最大牌的等级 * @return */ private int getHandRank() { return handEval.getMyHandType(); } // 根据现有的金钱判断是否一定会赢了 private boolean willWin() { // 如果我的钱比对手所有的加起来还多,那么基本上就赢定啦! if (moneyGap > 0) { int smallBet = bigBlindBet / 2; // 如果接下来一直fold会花多少钱 int foldMoney = 0; if (allPlayerNums == 2) { // 只有两个人时一直fold要花多少钱 foldMoney = ((remainTurn / 2) + 1) * smallBet; } else { foldMoney = ((remainTurn / allPlayerNums) + 1) * (smallBet + bigBlindBet); } if (moneyGap >= foldMoney * 2) { // 如果多出的钱比一直fold还多一倍,那就一直fold吧! return true; } } return false; } /** * 是否应该筹码保护 * @param strength * @return */ private boolean isJettonProtect(double strength) { int remainJetton = myAllJetton; // 剩余筹码已经不能进行5次盲注了 if ((remainJetton - myCurBet) < (bigBlindBet * 5) && (strength < JettonProtectHS) ) { return true; } return false; } // 现在的金钱,是否能撑到最后 private boolean canLiveTillEnd() { int smallBet = bigBlindBet / 2; // 如果接下来一直fold会花多少钱 int foldMoney = 0; if(allPlayerNums == 0) { allPlayerNums = 8; } if (allPlayerNums == 2) { // 只有两个人时一直fold要花多少钱 foldMoney = ((remainTurn / 2) + 1) * smallBet; } else { foldMoney = ((remainTurn / allPlayerNums) + 1) * (smallBet + bigBlindBet); } Logger.Log("allplayers="+allPlayerNums+" foldMoney:"+foldMoney); if(foldMoney > myAllJetton + myAllMoney) { // 撑不了 return false; } return true; } // 计算阈值 private int getThreshold(int group, int make, int tightness) { int res[] = PreflopData.getBaseIncrement(group, make, tightness); int base = res[0], incre = res[1]; // 表示还有多少个人没做出决策 int position = allPlayerNums -awayFromBtn; return base + incre * position; } /* * 计算进入flop的玩家的比率 * 每10局计算一次吧,不然耗时太大 */ private double getProbabilityPlay() { double probabilityPlay = lastCacPlayOdds; // 已经进行多少局 int roundNum = ALL_ROUND_NUM - remainTurn; if(probPlayIdx > 0 && roundNum > 1 && roundNum % 10 == 0) { double allProb = 0f; // 每10局,使用统计下来的play率 for(int i = 0; i < probPlayIdx; i++) { allProb += probability_play[i]; } if(probPlayIdx > 0) { probabilityPlay = allProb / probPlayIdx; } lastCacPlayOdds = probabilityPlay; } return probabilityPlay; } // preflop策略2,使用Income Rates表 private void makePreFlopAction() { String action = FOLD; if(!handEval.initOK()) { // 数据还没初始化完毕 if(rank1 == rank2 && (rank1 >= Poker.K)){ action = ALL_IN; }else{ action = FOLD; } Logger.Log("not init ok,action="+action); thread.sendMsg(action); return; } exchangePocket(); // 表示已经有多少人Put money in pot,包括自己 int num_guaranteed = awayFromBtn - foldCnt; if(awayFromBtn == 0 || playerCntInInquire == allPlayerNums) { // 当inquire里面出现所有玩家的action时,可以直接计算了 num_guaranteed = playerCntInInquire - foldCnt; } // still in pot int num_inpot = allPlayerNums; Logger.Log("playerCntInInquire:"+playerCntInInquire+" awayFromBtn:"+awayFromBtn+" numGua:"+num_guaranteed+" num_inpot:"+num_inpot); double probabilityPlay = getProbabilityPlay(); // 预期参与的玩家,最后加0.5是为了四舍五入 int expect_num_players = (int) (num_guaranteed + probabilityPlay * (num_inpot - num_guaranteed) + 0.5f); Logger.Log("probabilityPlay:"+probabilityPlay+" expect_num_players:"+expect_num_players); int group = 0; // 找到分组 if(expect_num_players <= 2) { group = PreflopData.TWO_PLAYER; }else if(expect_num_players < 5) { group = PreflopData.THREEORFOUR_PLAYER; }else{ group = PreflopData.FIVEPLUS_PLAYER; } // 计算threshhold int tightness = 0; if(myGameStyle == GameStyle.TIGHT_GAME) { tightness = PreflopData.BI_TIGHT; }else if(myGameStyle == GameStyle.MODERATE_GAME) { tightness = PreflopData.BI_MODERATE; }else{ tightness = PreflopData.BI_LOOSE; } Logger.Log("group:"+group+" tightness:"+tightness); int thresholdMake1 = getThreshold(group, PreflopData.Make1, tightness); int thresholdMake2 = getThreshold(group, PreflopData.Make2, tightness); int thresholdMake4 = getThreshold(group, PreflopData.Make4, tightness); // 接下来查表获得IncomeRate int ir = 0; if(group == PreflopData.TWO_PLAYER) { if(suit1 == suit2) { ir = PreflopData.IR2[rank1-2][rank2-2]; }else{ ir = PreflopData.IR2[rank2-2][rank1-2]; } }else if(group == PreflopData.THREEORFOUR_PLAYER) { if(suit1 == suit2) { ir = PreflopData.IR4[rank1-2][rank2-2]; }else{ ir = PreflopData.IR4[rank2-2][rank1-2]; } }else{ if(suit1 == suit2) { ir = PreflopData.IR7[rank1-2][rank2-2]; }else{ ir = PreflopData.IR7[rank2-2][rank1-2]; } } Logger.Log("ir:"+ir+" thresholdMake1:"+thresholdMake1+ " thresholdMake2:"+thresholdMake2+" thresholdMake4:"+thresholdMake4); if(ir >= thresholdMake4) { // make4 if(rank1 == rank2 && rank1 == Poker.A){ action = RAISE + (int)(Math.random()*100 + 9*bigBlindBet); }else if(raisePreFlopCnt >= 2) { // raise until raisecnt >= 2, otherwise call. action = CALL; }else { // 要跟的注小于3倍大盲注 if(minBet < 5 * bigBlindBet) { int mount = (int)(Math.random()*100 + 4*bigBlindBet); action = RAISE + mount; }else{ action = CALL; } } }else if(ir >= thresholdMake2) { // raise if less than two raises have been made this round, // otherwise call. // 要下注的倍数 int betTimes = (minBet / bigBlindBet); if(allinCnt > 0) { action = FOLD; }else if(raisePreFlopCnt >= 2 || raiseCnt >= 2) { action = CALL; }else{ int mount = (int)(Math.random()*100 + bigBlindBet); action = RAISE + mount; } }else if(ir >= thresholdMake1) { /* fold if it costs two or more bets to continue (and we have not already voluntarily put money in the pot this round), * otherwise check/call. */ if(raiseCnt > 1 || raisePreFlopCnt > 1) { action = FOLD; }else { action = CALL; // 试试bluff int roundNum = ALL_ROUND_NUM - remainTurn; if(roundNum >= 20 && raisePreFlopCnt < 1 && minBet <= 40){ // 局数太少,不bluff // 牌差,试试bluff if(myCurPos == Position.LATE_POS || myCurPos == Position.SBLIND_POS) { // 我的上家全部fold boolean allFold = true; // 弃牌的 我的上家的数量 int fold = 0, isNotBehindMe = 0; for(Opponent opp : opponents.values()) { if(!opp.isBehindMe && opp.curAction.equals(FOLD)){ fold++; } isNotBehindMe++; } float foldRate = fold / (float)isNotBehindMe; Logger.Log("我的上家是否all fold?"+allFold+" foldRate="+foldRate); if(foldRate > 0.6){ // 前面的人60%都fold了 // 看弃牌率 float foldF = 1f; for(String id : aliveOpp) { Opponent opp = opponents.get(id); float f = (float)opp.getFrequency(State.PRE_FLOP, 1, "fold", 0); if(f < foldF) { foldF = f; } } Logger.Log("preflop下家弃牌率:"+foldF); // 要的是最低的弃牌率 if(foldF > 0.6) { // 最小弃牌率都高于60%,bluff int mount = (int) (Math.random()*60); action = RAISE+mount; } } } } } }else{ // fold if it costs more than zero to continue playing, otherwise check. if(minBet > 0) { action = FOLD; }else { action = CALL; int roundNum = ALL_ROUND_NUM - remainTurn; if(roundNum >= 20){ // 局数太少,不bluff // 牌差,试试bluff if(myCurPos == Position.LATE_POS || myCurPos == Position.SBLIND_POS) { // 我的上家全部fold boolean allFold = true; for(Opponent opp : opponents.values()) { if(!opp.isBehindMe && !opp.curAction.equals(FOLD) && !opp.curAction.equals("blind")){ allFold = false; break; } } if(allFold){ // 前面的人都fold了 // 看弃牌率 float foldF = 1f; for(String id : aliveOpp) { Opponent opp = opponents.get(id); float f = (float)opp.getFrequency(State.PRE_FLOP, 1, "fold", 0); if(f < foldF) { foldF = f; } } Logger.Log("preflop下家弃牌率:"+foldF); // 要的是最低的弃牌率 if(foldF > 0.6) { // 最小弃牌率都高于60%,bluff int mount = (int) (Math.random()*60); action = RAISE+mount; } } } } } } // TODO:test if(minBet > 40 && !action.equals(FOLD)) { // 说明有人加注 Logger.Log("got raise in preflop"); int oppir = 0, v = 330; for(String id : aliveOpp){ Opponent opp = opponents.get(id); if(opp.curAction.equals("raise") || opp.curAction.equals("all_in")){ // 我的下家的话,是lastAction,我的上家,是curAction int raiseAmount = opp.curBet - opp.preBet; Logger.Log(opp.ID+" opp.round_Context:"+opp.round_Context+" opp.betToCall_Context:"+opp.betToCall_Context+" raiseAmount="+raiseAmount); float f = (float)opp.getFrequency(opp.round_Context, opp.betToCall_Context, opp.curAction, raiseAmount); Logger.Log("f="+f); float u = 1 - f; int idx = (int) (PreflopData.SortIR7.length * u); int tmir = PreflopData.SortIR7[idx]; if(tmir > oppir){ oppir = tmir; Logger.Log("tmir="+tmir); } } } int maxir = oppir + v, minir = ((oppir-v)< (-495)?(-495):(oppir-v)); if(ir < minir) { // 比对方的还小 action = FOLD; }else if(ir >= minir && ir < maxir) { if(minBet >= 300 && ir < oppir){ action = FOLD; }else{ action = CALL; } }else{ if(!action.contains(RAISE)){ // 如果之前没有RAISE if(minBet <= 80) { action = RAISE; }else{ action = CALL; } } } } // if(allinCnt > 0 && (minBet >= 800 || minBet >= (myAllJetton / 3))) { // // 有人all_in // if(rank1 == rank2 && rank1 == Poker.A) { // action = CALL; // }else{ // action = FOLD; // } // } int roundTurn = ALL_ROUND_NUM - remainTurn; if(roundTurn < 10) { // 局数太少,不轻易玩 if(ir < thresholdMake2) { action = FOLD; } } if(willWin()) { action = FOLD; } // 确保不会丢牌 if(action.equals(FOLD)) { if(minBet == 0) { action = CALL; } } if(action.contains(RAISE)) { raisePreFlopCnt++; } Logger.Log("preflop action="+action); thread.sendMsg(action); } /********** flop策略2 begin***********************/ /** * * @param bets_to_make the level of strength we want to make * @return */ private String make(int bets_to_make, int betAmound) { int bets_to_call = minBet / bigBlindBet; String action = FOLD; if(raiseCnt < bets_to_make) action = RAISE + betAmound; else if(minBet == 0 || bets_to_make >= 2 || raiseCnt <= bets_to_make) { action = CALL; }else{ action = FOLD; } return action; } /** * 控制加注,防止傻傻的加大注 * @param amount * @return =0时表示要改为跟住, -1表示要弃牌 */ private int controlRaiseAmoun(int amount, int handRank){ int finalRaise = 0; boolean isBoardStraight = isBoardStraightDraw(); int boardSuitedConn = handEval.getBoardSuitedNum(); boolean isBoardFlush = false; if(currentState == State.FLOP) { isBoardFlush = (boardSuitedConn == 3); }else{ isBoardFlush = (boardSuitedConn > 3); } Logger.Log("对方是否可能顺子:"+isBoardStraight+" 是否可能同花:"+isBoardFlush); if(isBoardStraight){ // 对方可能顺子听筒 if(handRank > HandType.Straight){ return amount; }else if(handRank == HandType.Straight){ // 我也是顺子,看大小 boolean bigger = true; for(int i = 0; i < shareIdx; i++){ if(rank1 < shareRank[i]){ // 我没拿高牌,弃了 bigger = false; break; } } if(bigger){ return amount; }else{ return 0; } }else{ return -1; } }else if(isBoardFlush){ // 对手可能同花,也就是四张公牌颜色一样 if(handRank > HandType.Flush){ return amount; }else if(handRank == HandType.Flush){ // 我也是同花,看大小 boolean bigger = true; for(int i = 0; i < shareIdx; i++){ if(rank1 < shareRank[i]){ // 我没拿高牌,弃了 bigger = false; break; } } if(bigger){ return amount; }else{ return 0; } }else{ return -1; } }else{ // 看公牌牌型 int boardType = handEval.getBoardCardType(); if(handRank == boardType) { // 我的最大牌型和公牌一样 // 包括三条都是公牌,两对都是公牌,一对都是公牌 // 看我有没有大牌 boolean bigger = true; for(int i = 0; i < shareIdx; i++){ if(rank1 < shareRank[i]){ // 我没拿大牌,弃了 bigger = false; break; } } if(bigger){ return amount; }else{ return 0; } }else if(handRank == HandType.Trips) { // 三条,但我手上的不是两条 if(rank1 != rank2){ // 说明牌桌上有一对 int sharedCard = rank1, leftCard = rank2; for(int i = 0; i < shareIdx; i++){ // 找到我手牌上的那一张 if(shareRank[i] == rank1){ sharedCard = rank1; leftCard = rank2; break; } if(shareRank[i] == rank2){ sharedCard = rank2; leftCard = rank1; break; } } boolean bigger = true; // 我的剩余那张牌是公牌里最大的 for(int i = 0; i < shareIdx; i++){ // 找到我手牌上的那一张 if(shareRank[i] != sharedCard && shareRank[i] > leftCard){ bigger = false; break; } } if(!bigger){ return 0; }else{ return amount; } } }else if(handRank == HandType.TwoPair){ // 两对,如果我的牌不是最大的 // 表示两张最大的公牌 int board1 = -1, board2 = -1; for(int i = 0; i < shareIdx; i++) { if(shareRank[i] > board1){ board1 = shareRank[i]; } } for(int i = 0; i < shareIdx; i++) { if(shareRank[i] == board1){ continue; } if(shareRank[i] > board2 ){ board2 = shareRank[i]; } } // 如果我的最大牌比board1小,弃牌 if(rank1 < board1){ return 0; }else if(rank1 == board1){ // 牌二不是次2大 if(rank2 < board2){ return 0; } } }else if(handRank == HandType.Pair){ // 只有一对,而且第一大底牌不是最大的 boolean bigger = true; for(int i = 0; i < shareIdx; i++) { if(shareRank[i] > rank1) { bigger = false; break; } } if(bigger){ // 看第二张底牌,如果不是最大的,也不要加注 for(int i = 0; i < shareIdx; i++){ if(shareRank[i] == rank1){ continue; } if(shareRank[i] > rank2) { bigger = false; break; } } } if(!bigger) { return 0; }else{ return amount; } } } return amount; } private void makeTurnAction() { int handRank = getHandRank(); if(rank1 == rank2 && rank1 == Poker.A) { // 对K,如果牌面上都是高牌而且不同色,all_in int boardType = handEval.getBoardCardType(); int suitNum = handEval.getBoardSuitedNum(); boolean bigger = true; if(boardType < 1 && suitNum < 3) { // 没有大于K的高牌 thread.sendMsg(ALL_IN); return; } } // if(rank1 == rank2 && rank1 == Poker.K){ // // 对K,如果牌面上都是高牌而且不同色,all_in // int boardType = handEval.getBoardCardType(); // int suitNum = handEval.getBoardSuitedNum(); // boolean bigger = true; // for(int i = 0; i < shareIdx; i++){ // if(shareRank[i] == Poker.A){ // bigger = false; // break; // } // } // if(bigger && boardType < 1 && suitNum < 3) { // // 没有大于K的高牌 // thread.sendMsg(ALL_IN); // return; // } // } String action = FOLD; switch(handRank){ case HandType.StraightFlush: case HandType.FourOfAKind: if(currentState == State.FLOP){ action = ALL_IN; thread.sendMsg(action); return; } break; } if(currentState == State.FLOP || minBet > 0) { semiBluffFlag = false; } int raisefactor = 2; if(myGameStyle == GameStyle.LOOSE_GAME) { raisefactor = 3; }else if(myGameStyle == GameStyle.TIGHT_GAME){ raisefactor = 1; } int raiseAmount = handRank * bigBlindBet*raisefactor; double ppot = 0; double ehs = 0; double strength = 0; long startTime = System.currentTimeMillis(); //获取结束时间 double calEhsRes[] = calEHS(); long endTime = System.currentTimeMillis(); //获取结束时间 Logger.Log("calEHS()运行时间: "+(endTime-startTime)+"ms"); // if(!done) { // // not done // Logger.Log("calEHS not done!"); // action = FOLD; // switch(handRank){ // case HandType.FullHouse: // if(currentState == State.FLOP){ // action = ALL_IN; // }else{ // action = RAISE; // } // break; // case HandType.Flush: // case HandType.Straight: // case HandType.Trips: // action = CALL; // break; // } // thread.sendMsg(action); // return; // } ppot = calEhsRes[0]; ehs = calEhsRes[1]; Logger.Log("ehs="+ehs+" ppot="+ppot); // 可以看做是阈值 double make1 = 0.5f, make2 = 0.85f; if(myGameStyle == GameStyle.LOOSE_GAME) { make1 = 0.4f; make2 = 0.8f; }else if(myGameStyle == GameStyle.TIGHT_GAME) { make1 = 0.6f; make2 = 0.9f; } if(ehs >= make2) { // 实际加注的是上家加的最小注+raiseAmount int totalRaise = minBet + (minBet > raiseAmount? minBet:raiseAmount); action = make(2, totalRaise); // 控制加注!! if(action.contains(RAISE) && totalRaise > 200){ Logger.Log("控制加注"); int r = controlRaiseAmoun(totalRaise, handRank); if(r == 0){ action = CALL; Logger.Log("修改为call"); }else if(r == -1){ Logger.Log("修改为fold!"); action = FOLD; } } }else if(ehs >= make1) { // 介于0.5~0.85之间 if(ehs <= 0.7){ raiseAmount = (int) (Math.random()*100); } action = make(1, raiseAmount); // TODO:控制加注 // 看竞争对手有一个raise时的弃牌率 float foldF = 1; for(String id : aliveOpp) { Opponent opp = opponents.get(id); float f = (float)opp.getFrequency(currentState, 1, "fold", 0); if(f < foldF) { foldF = f; } } if(foldF < 0.5) { // 对手弃牌的概率小于一半 action = CALL; } // 再加注就太大了 // if(minBet >= 240){ // // 对手弃牌的概率小于一半 // action = CALL; // } // // 0.6~0.8:(0,0.5,0.5) 也就是0.5会bluff // // 0.5~0.6:(0.1,0.8,0.1) 只有一成概率会bluff // int callThreshold = 50; // int raiseThreshold = 50; // int foldThreshold = 0; // if(ehs < 0.6) { // callThreshold = 80; // raiseThreshold = 10; // foldThreshold = 10; // } // int random = (int) Math.random()*100; // if(random <= foldThreshold) { // action = FOLD; // }else if(random <= callThreshold) { // action = CALL; // }else{ // if(minBet > 0) { // action = CALL; // }else{ // // 也就是bluff,要考虑弃牌率 // // 看竞争对手有一个raise时的弃牌率 // float foldF = 1; // for(String id : aliveOpp) { // Opponent opp = opponents.get(id); // float f = (float)opp.getFrequency(currentState, 1, "fold", 0); // Logger.Log(opp.ID+"when semi-bluff fold rate:"+f); // if(f < foldF) { // foldF = f; // } // } // Logger.Log("minfoldf="+foldF); // if(foldF <= 0.5){ // // 弃牌率不高,就不bluff了 // action = CHECK; // }else{ // int mount = (int)(Math.random()*100); // action = RAISE+mount; // } // } // } }else if(minBet == 0){ // 没人加注,考虑semi-bluff raiseAmount = (int)(Math.random()*80); double potOdds2 = 2*raiseAmount / (double)(totalPot + curHandPlayerNums*raiseAmount + 2*raiseAmount); Logger.Log("semi-bluff:ppot="+ppot+ " potOdds2:"+potOdds2); if((currentState != State.RIVER && ppot >= potOdds2)) { // 看竞争对手有一个raise时的弃牌率 float foldF = 1; for(String id : aliveOpp) { Opponent opp = opponents.get(id); float f = (float)opp.getFrequency(currentState, 1, "fold", 0); Logger.Log(opp.ID+"when semi-bluff fold rate:"+f); if(f < foldF) { foldF = f; } } Logger.Log("minfoldf="+foldF); if(foldF <= 0.6){ // 弃牌率不高,就不bluff了 action = CHECK; }else{ semiBluffFlag = true; action = RAISE+raiseAmount; } }else{ action = CHECK; } }else{ // check pot odds double potOdds = minBet / (double)(totalPot + minBet); if(currentState == State.TURN && ppot >= potOdds) { action = CALL; }else if(currentState == State.RIVER && ehs >= potOdds) { action = CALL; }else{ action = FOLD; } } // TODO:test if(minBet > 100 && !action.equals(FOLD)) { // 风险判断 // 说明有人加注 Logger.Log("got raise"); float oppu = 0, oppv = 0; for(String id : aliveOpp){ Opponent opp = opponents.get(id); if(opp.curAction.equals("raise") || opp.curAction.equals(ALL_IN)){ int oppRaiseNum = opp.curBet - opp.preBet; Logger.Log(opp.ID+" opp.round_Context:"+opp.round_Context+" opp.betToCall_Context:"+opp.betToCall_Context+" oppRaiseNum="+oppRaiseNum); float f = (float)opp.getFrequency(opp.round_Context, opp.betToCall_Context, opp.curAction, oppRaiseNum); float u = 1 - f; float v = 0.4f*(1-u); if(u > oppu) { // 看哪家的平均牌力最高 oppu = u; oppv = v; } Logger.Log("f="+f+"u="+u+" v="+v); } } float maxu = ((oppu+oppv) <= 1 ? (oppu+oppv):1), minu = ((oppu-oppv) > 0 ? (oppu-oppv) : (oppu)); Logger.Log("maxu="+maxu+" minu="+minu); if(ehs < minu) { // 比下限还小,就不跟了吧 if(minBet > 40) { action = FOLD; }else{ action = CALL; } }else if(ehs < maxu && ehs > minu) { if((minBet >= 400 && ehs < oppu)) { action = FOLD; }else{ // 照跟 action = CALL; } }else{ if(!action.contains(RAISE)){ // // 之前的决策不是raise,那照跟 action = CALL; // if(currentState == State.FLOP){ // // 唬我?虎回去! //// action = RAISE; // }else{ // action = CALL; // } } } } if(minBet >= 300 && !action.equals(FOLD) && currentState != State.FLOP){ // 到了turn, river阶段就不能靠统计数据来止损了,毕竟数据较少 // 首先看最常见的是不是同花,顺子听筒 boolean isBoardStraight = isBoardStraightDraw(); int boardSuitedConn = handEval.getBoardSuitedNum(); boolean isBoardFlush = false; if(currentState == State.FLOP) { isBoardFlush = (boardSuitedConn == 3); }else{ isBoardFlush = (boardSuitedConn > 3); } Logger.Log("对方是否可能顺子:"+isBoardStraight+" 是否可能同花:"+isBoardFlush); if(isBoardStraight){ // 对方可能顺子听筒 if(handRank > HandType.Straight){ action = RAISE; }else if(handRank == HandType.Straight){ // 我也是顺子,看大小 boolean bigger = true; for(int i = 0; i < shareIdx; i++){ if(rank1 < shareRank[i]){ // 我没拿高牌,弃了 bigger = false; break; } } if(bigger){ action = CALL; }else{ action = FOLD; } }else{ action = FOLD; } }else if(isBoardFlush){ // 对手可能同花,也就是四张公牌颜色一样 if(handRank > HandType.Flush){ action = RAISE; }else if(handRank == HandType.Flush){ // 我也是同花,看大小 boolean bigger = true; for(int i = 0; i < shareIdx; i++){ if(rank1 < shareRank[i]){ // 我没拿高牌,弃了 bigger = false; break; } } if(bigger){ action = CALL; }else{ action = FOLD; } }else{ action = FOLD; } }else{ // 看公牌牌型 int boardType = handEval.getBoardCardType(); if(handRank == boardType) { // 我的最大牌型和公牌一样 // 包括三条都是公牌,两对都是公牌,一对都是公牌 // 看我有没有大牌 boolean bigger = true; for(int i = 0; i < shareIdx; i++){ if(rank1 < shareRank[i]){ // 我没拿大牌,弃了 bigger = false; break; } } if(bigger){ action = CALL; }else{ action = FOLD; } }else if(handRank == HandType.Trips) { // 三条,但我手上的不是两条 if(rank1 != rank2){ // 说明牌桌上有一对 int sharedCard = rank1, leftCard = rank2; for(int i = 0; i < shareIdx; i++){ // 找到我手牌上的那一张 if(shareRank[i] == rank1){ sharedCard = rank1; leftCard = rank2; break; } if(shareRank[i] == rank2){ sharedCard = rank2; leftCard = rank1; break; } } boolean bigger = true; // 我的剩余那张牌是公牌里最大的 for(int i = 0; i < shareIdx; i++){ // 找到我手牌上的那一张 if(shareRank[i] != sharedCard && shareRank[i] > leftCard){ bigger = false; break; } } if(!bigger){ action = FOLD; }else{ action = CALL; } } }else if(handRank == HandType.TwoPair){ // 两对,如果我的牌不是最大的 // 表示两张最大的公牌 int board1 = -1, board2 = -1; for(int i = 0; i < shareIdx; i++) { if(shareRank[i] > board1){ board1 = shareRank[i]; } } for(int i = 0; i < shareIdx; i++) { if(shareRank[i] == board1){ continue; } if(shareRank[i] > board2 ){ board2 = shareRank[i]; } } // 如果我的最大牌比board1小,弃牌 if(rank1 < board1){ action = FOLD; }else if(rank1 == board1){ // 牌二不是次2大 if(rank2 < board2){ action = FOLD; } } }else if(handRank == HandType.Pair){ // 只有一对,而且不是最大的 boolean bigger = true; for(int i = 0; i < shareIdx; i++) { if(shareRank[i] > rank1) { bigger = false; break; } } if(!bigger) { action = FOLD; }else{ action = CALL; } } } } // if(action.equals(ALL_IN) || (action.equals(CALL) || action.contains(RAISE))) { // int factor = 3; // if(ehs >= make2){ // factor = 12; // }else if(ehs >= make1) { // factor = 6; // } // if(dangerRaise || (currentState == State.FLOP && raiseFLopCnt >= 2) // || (currentState == State.TURN && raiseTurnCnt >= 2) // || (currentState == State.RIVER && raiseRiverCnt >= 2) // || minBet >= factor * bigBlindBet) { // // 自己加了两次,说明自己加注之后对方还跟住! // // 风险控制 // boolean danger = false; // Logger.Log("in makeTurnAction2: aliveOppSize="+aliveOpp.size()); // for(String id : aliveOpp) { // if(danger) break; // Opponent aliveOpponet = opponents.get(id); // Logger.Log("in makeTurnAction2: opp curaction="+aliveOpponet.curAction); // if(aliveOpponet != null && // (aliveOpponet.curAction.contains(RAISE) // || aliveOpponet.curAction.equals(ALL_IN))) // { // int round = ALL_ROUND_NUM - remainTurn; // double foldPreFlopOdds = (double)aliveOpponet.foldBeforeFlop / round; // double af = (double)(aliveOpponet.raiseCnt + aliveOpponet.allinCnt*2) // / (aliveOpponet.callCnt + aliveOpponet.checkCnt); // Logger.Log("in makeTurnAction2: foldPreFlopOdds="+foldPreFlopOdds // +" af:" + af); // if(foldPreFlopOdds >= 0.65f || af <= 0.28) { // // 很少加注或者经常preflop弃牌 // danger = true; // }else{ // if(dangerRaise){ // if(ehs < make2) { // danger = true; // } // } // } // } // } // if(danger){ // action = FOLD; // } // } // } // // 一次加注1000 // if(minBet >= ((myAllJetton+myAllMoney)/2) || minBet >= 1000) { // // 一下子扔掉一半的钱 // action = FOLD; // switch(handRank){ // case HandType.StraightFlush: // case HandType.FourOfAKind: // action = ALL_IN; // break; // case HandType.FullHouse: // action = CALL; // break; // } // } if(((minBet >= (myAllJetton/2) && myAllJetton > 1000) || minBet >= 900) && !action.equals(FOLD)){ // 一次扔掉一半 if(handRank < HandType.Flush){ action = FOLD; } } if(action.contains(RAISE)) { if((currentState == State.FLOP && raiseFLopCnt >= 2 )|| (currentState == State.TURN && raiseTurnCnt >= 2) || (currentState == State.RIVER && raiseRiverCnt >= 2)) { action = CALL; }else{ if(currentState == State.FLOP){ raiseFLopCnt++; } if(currentState == State.TURN){ raiseTurnCnt++; } if(currentState == State.RIVER){ raiseRiverCnt++; } } } if(minBet == 0 && action.equals(FOLD)) { action = CALL; } if(willWin()) { action = FOLD; } Logger.Log("in turnaction="+action); thread.sendMsg(action); } private void doAction() { if(currentState == State.PRE_FLOP) { try{ makePreFlopAction(); }catch(Exception ex){ String msg = ""; StackTraceElement ele[] = ex.getStackTrace(); for(StackTraceElement e : ele){ msg += e.getMethodName()+" line:"+e.getLineNumber()+"\n"; } Logger.Log("err:"+ex.getMessage()+"\n"+msg); thread.sendMsg(FOLD); } }else{ makeTurnAction(); } } /** * 记录各玩家的frequency,并且更新权重表 */ private void recordAndReweight() { // 先将上一条消息的上家和下家拼起来,这样在处理当前消息的下家时才是完整的 LinkedList<InqNotifyMsg> mergeMsgList = new LinkedList<InqNotifyMsg>(); mergeMsgList.addAll(preMsgList); mergeMsgList.addAll(curMsgList); int countRaise = 0; for(InqNotifyMsg inqMsg : curMsgList) { if(inqMsg.isBehindMe) { if(inqMsg.action.contains("blind")){ continue; } if(!inqMsg.action.equals("check") && inqMsg.action.equals(inqMsg.preAction) && inqMsg.preBet == inqMsg.curBet) { // 如果行为没变,而且不是check(如果是check,则在不同round的 // 时候行为也可能相同) continue; } if(inqMsg.ID.equals(ID)){ // 我就不用继续执行下面的动作了 continue; } int tmpRaiseCnt = 0; // 从后往前遍历,从当前的下家的ID开始计数,遇到一个raise+1 // 直到再次遇到自己的ID或者遍历完毕 ListIterator<InqNotifyMsg> listIt = mergeMsgList.listIterator(mergeMsgList.size()); boolean beginFlag = false; while(listIt.hasPrevious()) { InqNotifyMsg tmpMsg = listIt.previous(); if(tmpMsg.ID.equals(inqMsg.ID)) { if(beginFlag) { // 已经遇到过一次ID,说明已经开始计算,再次遇到就应该break break; }else{ beginFlag = true; continue; } } if((tmpMsg.action.equals("raise") || tmpMsg.action.equals(ALL_IN)) && tmpMsg.preBet != tmpMsg.curBet) { // 算是一个加注 tmpRaiseCnt++; } } final Opponent opp = opponents.get(inqMsg.ID); if(opp != null) { // TODO 开始统计和reweight State rightState = currentState; if(circle == 1) { // 新一轮的第一圈,说明是上一轮的行为 if(currentState == State.FLOP) { rightState = State.PRE_FLOP; }else if(currentState == State.TURN) { rightState = State.FLOP; }else if(currentState == State.RIVER) { rightState = State.TURN; } } // TODO 先统计后reweight int raiseAmount = opp.curBet - opp.preBet; opp.round_Context = rightState; opp.betToCall_Context = tmpRaiseCnt; opp.handleAction(rightState, tmpRaiseCnt, inqMsg.action, raiseAmount); // if(circle == 1) { // // 新一轮的第一圈,说明是上一轮的行为 // if(currentState == State.FLOP) { // rightState = State.PRE_FLOP; // }else if(currentState == State.TURN) { // rightState = State.FLOP; // }else if(currentState == State.RIVER) { // rightState = State.TURN; // } // } // float u = 0, v = 0; // if(inqMsg.action.equals("call") || inqMsg.action.equals("check")){ // // call的话,要先计算加注的牌力和弃牌的牌力,平均才是跟住的牌力 // float raiseu = 1-((float) opp.getFrequency(rightState, tmpRaiseCnt, inqMsg.action)); // float foldu = (float) opp.getFrequency(rightState, tmpRaiseCnt, inqMsg.action); // u = (raiseu + foldu) / 2; // }else if(inqMsg.action.equals("raise")){ // u = 1 - (float)opp.getFrequency(rightState, tmpRaiseCnt, inqMsg.action); // }else{ // u = (float)opp.getFrequency(rightState, tmpRaiseCnt, inqMsg.action); // } // v = 0.4f*(1-u); // System.out.println("u="+u+" v="+v); // if(rightState != State.PRE_FLOP) { // handEval.postflopReweight(u, v, opp.weight, rightState); // } }else{ Logger.Log("in recordAndReweight(), opp=null!"); } }else{ // 是我的上家,直接记录 if(inqMsg.action.contains("blind")){ continue; } if(!inqMsg.action.equals("check") && inqMsg.action.equals(inqMsg.preAction) && inqMsg.preBet == inqMsg.curBet) { // 如果行为没变,而且不是check(如果是check,则在不同round的 // 时候行为也可能相同) continue; } if(circle > 1) { // 可能是river阶段补发的notify if(inqMsg.action.equals("check") && inqMsg.action.equals(inqMsg.preAction) && inqMsg.preBet == inqMsg.curBet) { // 如果行为没变,而且不是check(如果是check,则在不同round的 // 时候行为也可能相同) continue; } // 第二圈,说明有可能是当前的ID的选手的下家加注了,要遍历上一条msg int tmpRaiseCnt = 0; // 从后往前遍历,从当前的上家的ID开始计数,遇到一个raise+1 // 直到再次遇到自己的ID或者遍历完毕 ListIterator<InqNotifyMsg> listIt = mergeMsgList.listIterator(mergeMsgList.size()); boolean beginFlag = false; while(listIt.hasPrevious()) { InqNotifyMsg tmpMsg = listIt.previous(); if(tmpMsg.ID.equals(inqMsg.ID)) { if(beginFlag) { // 已经遇到过一次ID,说明已经开始计算,再次遇到就应该break break; }else{ beginFlag = true; continue; } } if((tmpMsg.action.equals("raise") || tmpMsg.action.equals(ALL_IN)) && tmpMsg.preBet != tmpMsg.curBet) { // 算是一个加注 tmpRaiseCnt++; } } Opponent opp = opponents.get(inqMsg.ID); if(opp != null) { // TODO 开始统计和reweight int raiseAmount = opp.curBet - opp.preBet; opp.round_Context = currentState; opp.betToCall_Context = tmpRaiseCnt; opp.handleAction(currentState, tmpRaiseCnt, inqMsg.action, raiseAmount); // float u = 1, v = 0.5f; // if(inqMsg.action.equals("call") || inqMsg.action.equals("check")){ // // call的话,要先计算加注的牌力和弃牌的牌力,平均才是跟住的牌力 // float raiseu = 1-((float) opp.getFrequency(currentState, tmpRaiseCnt, "raise")); // float foldu = (float) opp.getFrequency(currentState, tmpRaiseCnt, "fold"); // u = (raiseu + foldu) / 2; // }else if(inqMsg.action.equals("raise")){ // u = 1 - (float)opp.getFrequency(currentState, tmpRaiseCnt, inqMsg.action); // }else{ // u = (float)opp.getFrequency(currentState, tmpRaiseCnt, inqMsg.action); // } // v = 0.4f*(1-u); // System.out.println("u="+u+" v="+v); // if(currentState != State.PRE_FLOP) { // handEval.postflopReweight(u, v, opp.weight, currentState); // } }else{ Logger.Log("in recordAndReweight(), opp=null!"); } }else{ // circle = 1,只要看该玩家的上家就好了 Opponent opp = opponents.get(inqMsg.ID); if(opp != null) { // TODO 开始统计和reweight int raiseAmount = opp.curBet - opp.preBet; opp.round_Context = currentState; opp.betToCall_Context = countRaise; opp.handleAction(currentState, countRaise, inqMsg.action, raiseAmount); // float u = 0, v = 0; // if(inqMsg.action.equals("call")){ // // call的话,要先计算加注的牌力和弃牌的牌力,平均才是跟住的牌力 // float raiseu = 1-((float) opp.getFrequency(currentState, countRaise, inqMsg.action)); // float foldu = (float) opp.getFrequency(currentState, countRaise, inqMsg.action); // u = (raiseu + foldu) / 2; // }else if(inqMsg.action.equals("raise")){ // u = 1 - (float)opp.getFrequency(currentState, countRaise, inqMsg.action); // }else{ // u = (float)opp.getFrequency(currentState, countRaise, inqMsg.action); // } // v = 0.4f*(1-u); // if(currentState != State.PRE_FLOP) { // handEval.postflopReweight(u, v, opp.weight, currentState); // } }else{ Logger.Log("in recordAndReweight(), opp=null!"); } if((inqMsg.action.equals("raise")|| inqMsg.action.equals(ALL_IN)) && inqMsg.preBet != inqMsg.curBet) { // 算是一个加注 countRaise++; } } } } } /** * 将主方法分解,便于开线程计算 * @param mergeMsgList * @param inqMsg * @param needReweight 是否需要reweight */ private void subRecordReweight(final LinkedList<InqNotifyMsg> mergeMsgList, final InqNotifyMsg inqMsg, final boolean needReweight, final int countRaise) { if(inqMsg.isBehindMe) { int tmpRaiseCnt = 0; // 从后往前遍历,从当前的下家的ID开始计数,遇到一个raise+1 // 直到再次遇到自己的ID或者遍历完毕 ListIterator<InqNotifyMsg> listIt = mergeMsgList.listIterator(mergeMsgList.size()); boolean beginFlag = false; while(listIt.hasPrevious()) { InqNotifyMsg tmpMsg = listIt.previous(); if(tmpMsg.ID.equals(inqMsg.ID)) { if(beginFlag) { // 已经遇到过一次ID,说明已经开始计算,再次遇到就应该break break; }else{ beginFlag = true; continue; } } if(tmpMsg.action.equals("raise") && tmpMsg.preBet != tmpMsg.curBet) { // 算是一个加注 tmpRaiseCnt++; } } final Opponent opp = opponents.get(inqMsg.ID); if(opp != null) { // TODO 开始统计和reweight State rightState = currentState; if(circle == 1) { // 新一轮的第一圈,说明是上一轮的行为 if(currentState == State.FLOP) { rightState = State.PRE_FLOP; }else if(currentState == State.TURN) { rightState = State.FLOP; }else if(currentState == State.RIVER) { rightState = State.TURN; } } // 记录上下文 opp.round_Context = rightState; opp.betToCall_Context = tmpRaiseCnt; // TODO 先统计后reweight int raiseAmount = opp.curBet - opp.preBet; opp.handleAction(rightState, tmpRaiseCnt, inqMsg.action, raiseAmount); if(!needReweight) { return; } float u = 0, v = 0; if(inqMsg.action.equals("call") || inqMsg.action.equals("check")){ // call的话,要先计算加注的牌力和弃牌的牌力,平均才是跟住的牌力 float raiseu = 1-((float) opp.getFrequency(rightState, tmpRaiseCnt, inqMsg.action, -1)); float foldu = (float) opp.getFrequency(rightState, tmpRaiseCnt, inqMsg.action, 0); u = (raiseu + foldu) / 2; }else if(inqMsg.action.equals("raise") || inqMsg.action.equals(ALL_IN)){ u = 1 - (float)opp.getFrequency(rightState, tmpRaiseCnt, inqMsg.action, raiseAmount); }else{ u = (float)opp.getFrequency(rightState, tmpRaiseCnt, inqMsg.action, 0); } v = 0.4f*(1-u); Logger.Log("u="+u+" v="+v); if(rightState != State.PRE_FLOP) { handEval.fastPostflopReweight(u, v, opp.weight, rightState); } } }if(circle > 1) { // 可能是river阶段补发的notify if(inqMsg.action.equals("check") && inqMsg.action.equals(inqMsg.preAction) && inqMsg.preBet == inqMsg.curBet) { // 如果行为没变,而且不是check(如果是check,则在不同round的 // 时候行为也可能相同) return; } // 第二圈,说明有可能是当前的ID的选手的下家加注了,要遍历上一条msg int tmpRaiseCnt = 0; // 从后往前遍历,从当前的上家的ID开始计数,遇到一个raise+1 // 直到再次遇到自己的ID或者遍历完毕 ListIterator<InqNotifyMsg> listIt = mergeMsgList.listIterator(mergeMsgList.size()); boolean beginFlag = false; while(listIt.hasPrevious()) { InqNotifyMsg tmpMsg = listIt.previous(); if(tmpMsg.ID.equals(inqMsg.ID)) { if(beginFlag) { // 已经遇到过一次ID,说明已经开始计算,再次遇到就应该break break; }else{ beginFlag = true; continue; } } if(tmpMsg.action.equals("raise") && tmpMsg.preBet != tmpMsg.curBet) { // 算是一个加注 tmpRaiseCnt++; } } Opponent opp = opponents.get(inqMsg.ID); if(opp != null) { // TODO 开始统计和reweight // 记录上下文 opp.round_Context = currentState; opp.betToCall_Context = tmpRaiseCnt; int raiseAmount = opp.curBet - opp.preBet; opp.handleAction(currentState, tmpRaiseCnt, inqMsg.action, raiseAmount); if(!needReweight){ return; } float u = 1, v = 0.5f; if(inqMsg.action.equals("call") || inqMsg.action.equals("check")){ // call的话,要先计算加注的牌力和弃牌的牌力,平均才是跟住的牌力 float raiseu = 1-((float) opp.getFrequency(currentState, tmpRaiseCnt, RAISE, -1)); float foldu = (float) opp.getFrequency(currentState, tmpRaiseCnt, FOLD, 0); u = (raiseu + foldu) / 2; }else if(inqMsg.action.equals(RAISE) || inqMsg.action.equals(ALL_IN)){ u = 1 - (float)opp.getFrequency(currentState, tmpRaiseCnt, inqMsg.action, raiseAmount); }else{ u = (float)opp.getFrequency(currentState, tmpRaiseCnt, inqMsg.action, 0); } v = 0.4f*(1-u); Logger.Log("u="+u+" v="+v); if(currentState != State.PRE_FLOP) { handEval.fastPostflopReweight(u, v, opp.weight, currentState); } } }else{ // circle = 1,只要看该玩家的上家就好了 Opponent opp = opponents.get(inqMsg.ID); if(opp != null) { // TODO 开始统计和reweight opp.round_Context = currentState; opp.betToCall_Context = countRaise; int raiseAmount = opp.curBet - opp.preBet; opp.handleAction(currentState, countRaise, inqMsg.action, raiseAmount); if(!needReweight){ return; } float u = 0, v = 0; if(inqMsg.action.equals("call") || inqMsg.action.equals("check")){ // call的话,要先计算加注的牌力和弃牌的牌力,平均才是跟住的牌力 float raiseu = 1-((float) opp.getFrequency(currentState, countRaise, inqMsg.action, -1)); float foldu = (float) opp.getFrequency(currentState, countRaise, inqMsg.action, 0); u = (raiseu + foldu) / 2; }else if(inqMsg.action.equals(RAISE) || inqMsg.action.equals(ALL_IN)){ u = 1 - (float)opp.getFrequency(currentState, countRaise, inqMsg.action, raiseAmount); }else{ u = (float)opp.getFrequency(currentState, countRaise, inqMsg.action, 0); } v = 0.4f*(1-u); if(currentState != State.PRE_FLOP) { handEval.fastPostflopReweight(u, v, opp.weight, currentState); } } } } /** * 更新权重表会超时 */ // private boolean threadFlag = false; // private int threadCount = 0; // private void recordAndReweight() { // final CountDownLatch countDownLatch = new CountDownLatch(curMsgList.size());//初始化计数器 // // 先将上一条消息的上家和下家拼起来,这样在处理当前消息的下家时才是完整的 // final LinkedList<InqNotifyMsg> mergeMsgList = new LinkedList<InqNotifyMsg>(); // mergeMsgList.addAll(preMsgList); // mergeMsgList.addAll(curMsgList); // int countRaise = 0; // for(final InqNotifyMsg inqMsg : curMsgList) { // if(inqMsg.isBehindMe) { // if(!inqMsg.action.equals("check") // && inqMsg.action.equals(inqMsg.preAction) // && inqMsg.preBet == inqMsg.curBet) // { // // 如果行为没变,而且不是check(如果是check,则在不同round的 // // 时候行为也可能相同) // continue; // } // if(inqMsg.ID.equals(ID)){ // // 我就不用继续执行下面的动作了 // continue; // } // boolean needReweight = true; // if(myCurAction.equals(FOLD)){ // needReweight = false; // } // // 不要reweight了,太耗时了 // subRecordReweight(mergeMsgList, inqMsg, false, countRaise); //// threadFlag = needReweight; //// threadCount = countRaise; //// threadPool.execute(new Runnable() { //// //// @Override //// public void run() { //// long startTime=System.currentTimeMillis(); //获取开始时间 //// subRecordReweight(mergeMsgList, inqMsg, threadFlag, threadCount); //// countDownLatch.countDown(); //// long endTime=System.currentTimeMillis(); //获取结束时间 //// Logger.Log("subRecordReweight运行时间: "+(endTime-startTime)+"ms"); //// } //// }); // // }else{ // // 是我的上家,直接记录 // if(inqMsg.action.contains("blind")){ // continue; // } // if(!inqMsg.action.equals("check") // && inqMsg.action.equals(inqMsg.preAction) // && inqMsg.preBet == inqMsg.curBet) // { // // 如果行为没变,而且不是check(如果是check,则在不同round的 // // 时候行为也可能相同) // continue; // } // boolean needReweight = true; // if(myCurAction.equals(FOLD)){ // needReweight = false; // } // // 不要reweight了,太耗时了 // subRecordReweight(mergeMsgList, inqMsg, false, countRaise); //// threadFlag = needReweight; //// threadCount = countRaise; //// threadPool.execute(new Runnable() { //// //// @Override //// public void run() { //// long startTime=System.currentTimeMillis(); //获取开始时间 //// subRecordReweight(mergeMsgList, inqMsg, threadFlag, threadCount); //// countDownLatch.countDown(); //// long endTime=System.currentTimeMillis(); //获取结束时间 //// Logger.Log("subRecordReweight运行时间: "+(endTime-startTime)+"ms"); //// } //// }); // if(inqMsg.action.equals("raise") && inqMsg.preBet != inqMsg.curBet) { // // 算是一个加注 // countRaise++; // } // } // // } //// try { //// countDownLatch.await(213, TimeUnit.MILLISECONDS); //// } catch (InterruptedException e) { //// // TODO 自动生成的 catch 块 //// e.printStackTrace(); //// Logger.Log(e.getMessage()); //// } //// exs.shutdown(); //// try { //// boolean done = exs.awaitTermination(200, TimeUnit.MILLISECONDS); //// Logger.Log("reweight done?"+done); //// } catch (InterruptedException e) { //// Logger.Log("InterruptedException:"+e.getMessage()); //// } // } private void handleNotify(String content) { // 圈数加一 circle++; preMsgList.clear(); preMsgList.addAll(curMsgList); curMsgList.clear(); String[] lines = content.split("\\n"); if(lines == null) { return; } // 从第1行开始,下注的数目要除去最后一行的total pot: // int nums = lines.length - 2; // pid jetton money bet action String regex = "(\\d+)\\s(\\d+)\\s(\\d+)\\s(\\d+)\\s(\\w+)"; Pattern pattern = Pattern.compile(regex); for(int i = 1; i < lines.length-1; i++) { Matcher m = pattern.matcher(lines[i]); if(m.find()) { final String pid = m.group(1); final String action = m.group(5); final String bet = m.group(4); if(pid.equals(ID)) { myLastAction = myCurAction; myCurAction = action; try{ // 记录当前信息 myPreBet = myCurBet; myCurBet = Integer.parseInt(m.group(4)); myAllJetton = Integer.parseInt(m.group(2)); myAllMoney = Integer.parseInt(m.group(3)); }catch(NumberFormatException ex) { Logger.Log(ex.getMessage()); } curMsgList.addFirst(new InqNotifyMsg(pid, true, action, myLastAction, myPreBet, myCurBet)); }else{ if(aliveOpp.contains(pid) == false) { continue; } Opponent opp = null; if(opponents.containsKey(pid)) { opp = opponents.get(pid); }else{ // 不应该存在这种情况 Logger.Log("Notify:"+pid+"不存在!"); opp = new Opponent(); } opp.ID = pid; opp.lastAction = opp.curAction; opp.curAction = action; try{ opp.jetton = Integer.parseInt(m.group(2)); opp.money = Integer.parseInt(m.group(3)); int curbet = Integer.parseInt(m.group(4)); opp.preBet = opp.curBet; opp.curBet = curbet; }catch(NumberFormatException ex) { Logger.Log(ex.getMessage()); } // 不包括自己! if(action.equals("all_in") && (opp.preBet != opp.curBet)) { opp.allinCnt++; }else if(action.equals("blind")){ }else if(action.equals("call")&& (opp.preBet != opp.curBet)){ opp.callCnt++; }else if(action.equals("fold")){ opp.foldCnt++; if(currentState == State.PRE_FLOP) { // 翻牌前弃牌 opp.foldBeforeFlop++; foldPreFlop++; } aliveOpp.remove(pid); }else if(action.equals("check")){ opp.checkCnt++; }else if(action.equals("raise")&& (opp.preBet != opp.curBet)) { int oppRaise = opp.curBet - opp.preBet; // 计算平均值 opp.averageRaise = (opp.averageRaise*opp.raiseCnt + oppRaise) /(opp.raiseCnt+1); opp.raiseCnt++; if(currentState == State.PRE_FLOP) { // 翻牌前加注 opp.raisePreFlop++; } } opponents.put(pid, opp); curMsgList.addFirst(new InqNotifyMsg(pid, opp.isBehindMe, action , opp.lastAction, opp.preBet, opp.curBet)); } } } long startTime=System.currentTimeMillis(); //获取开始时间 // 记录和更新权重 recordAndReweight(); long endTime=System.currentTimeMillis(); //获取结束时间 Logger.Log("recordAndReweight运行时间: "+(endTime-startTime)+"ms"); } // 前面有没有人的加注额比平均值大两倍,如果有,=true private boolean dangerRaise = false; /** * 处理询问消息 * @param content */ private void handleInquire(String content) { // 圈数加一 circle++; preMsgList.clear(); preMsgList.addAll(curMsgList); curMsgList.clear(); dangerRaise = false; Logger.Log("currentInquire, allive opp nums:"+aliveOpp.size()); playerCntInInquire = allPlayerNums; // 至少需要加大盲注的钱 leastRaise = bigBlindBet; // 所有对手加起来的钱 int allEnemyMoney = 0; minBet = myCurBet = 0; int bigBet = 0; allinCnt = foldCnt = callCnt = raiseCnt = checkCnt = blindCnt = 0; totalPot = 0; String[] lines = content.split("\\n"); if(lines == null) { thread.sendMsg(FOLD); return; } // 从第1行开始,下注的数目要除去最后一行的total pot: playerCntInInquire = lines.length - 2; // pid jetton money bet action String regex = "(\\d+)\\s(\\d+)\\s(\\d+)\\s(\\d+)\\s(\\w+)"; Pattern pattern = Pattern.compile(regex); int linesLength = lines.length-1; for(int i = 1; i < linesLength; i++) { Matcher m = pattern.matcher(lines[i]); if(m.find()) { // System.out.println("pid="+m.group(1)+" jetton="+m.group(2) // +" money="+m.group(3)+" bet="+m.group(4)+" action="+m.group(5)); final String pid = m.group(1); final String action = m.group(5); if(pid.equals(ID)) { try{ // 记录当前信息 myPreBet = myCurBet; myCurBet = Integer.parseInt(m.group(4)); myAllJetton = Integer.parseInt(m.group(2)); myAllMoney = Integer.parseInt(m.group(3)); }catch(NumberFormatException ex) { Logger.Log(ex.getMessage()); } myLastAction = myCurAction; myCurAction = action; curMsgList.addFirst(new InqNotifyMsg(pid, true, action, myLastAction, myPreBet, myCurBet)); }else{ Opponent opp = null; if(opponents.containsKey(pid)) { opp = opponents.get(pid); }else{ // 不应该存在这种情况 Logger.Log("Inquire:"+pid+"不存在!"); opp = new Opponent(); } opp.ID = pid; opp.lastAction = opp.curAction; opp.curAction = action; boolean stillAlive = aliveOpp.contains(pid); try{ int bet = Integer.parseInt(m.group(4)); opp.preBet = opp.curBet; opp.curBet = bet; if(!action.equals("fold")){ if(bet > bigBet){ bigBet = bet; } } opp.jetton = Integer.parseInt(m.group(2)); opp.money = Integer.parseInt(m.group(3)); allEnemyMoney = allEnemyMoney + opp.jetton + opp.money; }catch(NumberFormatException ex) { Logger.Log(ex.getMessage()); } // 不包括自己! if(action.equals("all_in")) { if(stillAlive && (opp.preBet != opp.curBet)){ opp.allinCnt++; allinCnt++; // opp.lastAction = opp.curAction; // opp.curAction = ALL_IN; } }else if(action.equals("blind")){ blindCnt++; }else if(action.equals("call")){ if(stillAlive && (opp.preBet != opp.curBet)){ opp.callCnt++; callCnt++; // opp.lastAction = opp.curAction; // opp.curAction = CALL; } }else if(action.equals("fold")){ if(stillAlive){ foldCnt++; opp.foldCnt++; if(currentState == State.PRE_FLOP) { // 翻牌前弃牌 opp.foldBeforeFlop++; foldPreFlop++; } // opp.lastAction = opp.curAction; // opp.curAction = FOLD; // 弃牌了,去掉 boolean flag = aliveOpp.remove(pid); Logger.Log("remove pid:"+pid+" flag="+flag); } }else if(action.equals("check")){ checkCnt++; if(stillAlive){ opp.checkCnt++; } }else if(action.equals("raise")) { if(stillAlive && (opp.preBet != opp.curBet)){ raiseCnt++; int oppRaise = opp.curBet - opp.preBet; if(oppRaise > leastRaise) { leastRaise = opp.curBet - opp.preBet; } if(oppRaise >= 2*opp.averageRaise) { // 大于两倍 dangerRaise = true; } // 计算平均值 opp.averageRaise = (opp.averageRaise*opp.raiseCnt + oppRaise) /(opp.raiseCnt+1); opp.raiseCnt++; if(currentState == State.PRE_FLOP) { // 翻牌前加注 opp.raisePreFlop++; } // opp.lastAction = opp.curAction; // opp.curAction = RAISE; } } //opponents.remove(pid); opponents.put(pid, opp); curMsgList.addFirst(new InqNotifyMsg(pid, opp.isBehindMe, action, opp.lastAction, opp.preBet, opp.curBet)); } } } // 当前金钱差距 moneyGap = myAllJetton + myAllMoney - allEnemyMoney; // 计算这轮要下的最小注 minBet = ((bigBet - myCurBet) > 0 ? (bigBet - myCurBet) : 0); Logger.Log("myAllJetton:"+myAllJetton+" allMoney:"+myAllMoney); Logger.Log("bigbet="+bigBet+" myCurBet="+myCurBet+" minBet="+minBet); if (myAllJetton < minBet) { minBet = myAllJetton; } curHandPlayerNums = allPlayerNums - foldCnt -1; Logger.Log("allPlayerNums:"+allPlayerNums+" foldCnt:"+foldCnt+" curHandPlayerNums:"+curHandPlayerNums); regex = "total pot: (\\d+)"; pattern = Pattern.compile(regex); Matcher m = pattern.matcher(lines[lines.length-1]); if(m.find()) { // System.out.println("total pot:"+m.group(1)); try{ totalPot = Integer.parseInt(m.group(1)); }catch(NumberFormatException ex) { Logger.Log(ex.getMessage()); } } long startTime=System.currentTimeMillis(); //获取开始时间 // 记录和更新权重 recordAndReweight(); long endTime=System.currentTimeMillis(); //获取结束时间 Logger.Log("recordAndReweight运行时间: "+(endTime-startTime)+"ms"); try{ doAction(); }catch(Exception ex) { Logger.Log("doAction err:"+ex.getMessage()); } } /** * 根据字符串返回相应的枚举变量 * @param str * @return */ private int getPokerValFromStr(final String str) { if(str == null || str.length() == 0) { return Poker.NONE; } if(str.equals(DIAMONDS)){ return Poker.Diamonds; }else if(str.equals(SPADES)){ return Poker.Spades; }else if(str.equals(CLUBS)){ return Poker.Clubs; }else if(str.equals(HEARTS)){ return Poker.Hearts; }else if(str.equals("J")){ return Poker.J; }else if(str.equals("Q")){ return Poker.Q; }else if(str.equals("K")){ return Poker.K; }else if(str.equals("A")){ return Poker.A; }else{ try{ int val = Integer.parseInt(str); return val; }catch(NumberFormatException ex) { Logger.Log(ex.getMessage()); return Poker.NONE; } } } /** * 解析扑克点数和花色并保存 * @param content */ private void parsePoker(String content) { String regex = "([A-Z]+?)\\s(\\d{1,2}|[JQKA])"; Pattern pattern = Pattern.compile(regex); Matcher m = pattern.matcher(content); int suit; int rank; while(m.find()) { //System.out.println(m.group(1)+":"+m.group(2)); // group(1)花色 group(2)点数 suit = getPokerValFromStr(m.group(1)); rank = getPokerValFromStr(m.group(2)); shareRank[shareIdx] = rank; shareSuit[shareIdx] = suit; boardCardVal[shareIdx] = (rank-2) + (suit * 13); shareIdx++; } handEval.parseBoardCard(boardCardVal, shareIdx); } /** * 处理手牌信息 * @param content */ private void handleHold(String content) { currentState = State.PRE_FLOP; String regex = "([A-Z]+?)\\s(\\d{1,2}|[JQKA])"; Pattern pattern = Pattern.compile(regex); Matcher m = pattern.matcher(content); int suit; int rank; int idx = 0; while(m.find()) { //System.out.println(m.group(1)+":"+m.group(2)); // group(1)花色 group(2)点数 suit = getPokerValFromStr(m.group(1)); rank = getPokerValFromStr(m.group(2)); if(idx == 0) { suit1 = suit; rank1 = rank; }else{ suit2 = suit; rank2 = rank; } idx++; } handEval.parsePocketCard(((rank1-2)+suit1*13), ((rank2-2)+suit2*13)); } private void handleFlop(String content) { // 每进一轮,circle=0 circle = 0; shareIdx = 0; parsePoker(content); currentState = State.FLOP; } private void handleTurn(String content) { // 每进一轮,circle=0 circle = 0; parsePoker(content); currentState = State.TURN; } private void handleRiver(String content) { // 每进一轮,circle=0 circle = 0; parsePoker(content); currentState = State.RIVER; } private void handleSeat(String content) { // TODO:log opp // for(Opponent tmpopp : opponents.values()) { // Logger.Log(tmpopp.toString()); // } circle = 0; preMsgList.clear(); curMsgList.clear(); if(allPlayerNums > 0) { // 计算上一局foldpreflop的百分比 double prob = (double)foldPreFlop / allPlayerNums; probability_play[probPlayIdx++] = 1 - prob; } if(preAllPlayerNums > 0 && allPlayerNums > 0) { if(preAllPlayerNums - allPlayerNums >= 2) { // 至少减少至少2个对手以上才重置一次 preAllPlayerNums = allPlayerNums; probPlayIdx = 0; } } // if(!canLiveTillEnd()) { // myGameStyle = GameStyle.TIGHT_GAME; // } /* 切换风格 double playOdds = getProbabilityPlay(); if(playOdds <= 0.45) { // 进入flop的玩家的比例少,说明赛场是tight风格 myGameStyle = GameStyle.LOOSE_GAME; }else if(playOdds > 0.6) { myGameStyle = GameStyle.TIGHT_GAME; }else{ myGameStyle = GameStyle.MODERATE_GAME; } if(myGameStyle == GameStyle.LOOSE_GAME && !canLiveTillEnd()) { myGameStyle = GameStyle.MODERATE_GAME; } Logger.Log("mygameStyle="+myGameStyle); */ // 每一局开始时先清空之前的统计 raisePreFlopCnt = raiseFLopCnt = raiseTurnCnt = raiseRiverCnt = 0; foldPreFlop = 0; awayFromBtn = -1; allPlayerNums = 0; aliveOpp.clear(); // 一开始采用紧的打法 isTight = true; myPreBet = myCurBet = 0; myLastAction = myCurAction = ""; // 当前排名 int curRoundRank = 0; // 保存对手总的钱数,用来判断排名 int otherGold[] = new int[7]; int otherIdx = 0; if(content == null) return; // pid jetton money String regex = "(button:\\s|small blind:\\s||big blind:\\s)?(\\d+)\\s(\\d+)\\s(\\d+)"; Pattern pattern = Pattern.compile(regex); Matcher m = pattern.matcher(content); int playerCnt = 0, myPos = 0; boolean foundMyPos = false; boolean buttonOrBlind = false; while(m.find()){ if(m.group().contains("button") || m.group().contains("blind")){ //Logger.Log("type="+m.group(1)+" pid="+m.group(2)+" jetton="+m.group(3)+" money="+m.group(4)); String type = m.group(1); String pidStr = m.group(2), jettonStr = m.group(3), moneyStr = m.group(4); if(pidStr != null && pidStr.equals(ID)) { if(type.contains("button")) { awayFromBtn = 0; myCurPos = Position.LATE_POS; Logger.Log("I am button!awayFromBtn="+awayFromBtn); }else if(type.contains("small blind")) { awayFromBtn = 1; myCurPos = Position.SBLIND_POS; }else if(type.contains("big blind")) { awayFromBtn = 2; myCurPos = Position.BLIND_POS; } try{ myAllJetton = Integer.parseInt(jettonStr); myAllMoney = Integer.parseInt(moneyStr); }catch(NumberFormatException ex) { Logger.Log(ex.getMessage()); } foundMyPos = true; buttonOrBlind = true; }else{ // 对手 Opponent opp = null; if(opponents.containsKey(pidStr)) { opp = opponents.get(pidStr); }else{ opp = new Opponent(); opponents.put(pidStr, opp); } opp.ID = pidStr; aliveOpp.add(opp.ID); if(!foundMyPos) { myPos++; // 还没找到我,或者我是庄家,说明其他人是我的上家 opp.isBehindMe = false; }else{ // 找到我了,说明是我的下家 opp.isBehindMe = true; } if(awayFromBtn == 0) { opp.isBehindMe = false;; } try{ int otherJetton = Integer.parseInt(jettonStr); int otherMoney = Integer.parseInt(moneyStr); opp.jetton = otherJetton; opp.money = otherMoney; otherGold[otherIdx++] = otherJetton + otherMoney; }catch(NumberFormatException ex) { Logger.Log(ex.getMessage()); } opp.pos = playerCnt; // 清空之前的信息 Arrays.fill(opp.weight, 1f);; opp.lastAction = opp.curAction = ""; opp.curBet = 0; if(type.contains("button")) { // 庄家是我的下家 opp.isBehindMe = true; } } }else{ //Logger.Log("pid="+m.group(2)+" jetton="+m.group(3)+" money="+m.group(4)); String pidStr = m.group(2), jettonStr = m.group(3), moneyStr = m.group(4); if(pidStr != null && pidStr.equals(ID)) { try{ myAllJetton = Integer.parseInt(jettonStr); myAllMoney = Integer.parseInt(moneyStr); }catch(NumberFormatException ex) { Logger.Log(ex.getMessage()); } foundMyPos = true; }else{ Opponent opp = null; if(opponents.containsKey(pidStr)) { opp = opponents.get(pidStr); }else{ opp = new Opponent(); opponents.put(pidStr, opp); } opp.ID = pidStr; aliveOpp.add(opp.ID); if(!foundMyPos) { myPos++; // 还没找到我,说明是我的上家 opp.isBehindMe = false; }else{ // 找到我了,说明是我的下家 opp.isBehindMe = true; } if(awayFromBtn == 0) { opp.isBehindMe = false;; } try{ int otherJetton = Integer.parseInt(jettonStr); int otherMoney = Integer.parseInt(moneyStr); opp.jetton = otherJetton; opp.money = otherMoney; otherGold[otherIdx++] = otherJetton + otherMoney; }catch(NumberFormatException ex) { Logger.Log(ex.getMessage()); } // 清空之前的信息 //opp.weight.clear(); Arrays.fill(opp.weight, 1f); opp.lastAction = opp.curAction = ""; opp.curBet = 0; } } playerCnt++; } // for(int i = 0; i < otherIdx; i++) { // if(otherGold[i] > myAllJetton + myAllMoney) { // curRoundRank++; // 表示名次降1 // } // } // Logger.Log("curRoundRank="+curRoundRank); // int round = ALL_ROUND_NUM - remainTurn; // if(round <= 40) { // myGameStyle = GameStyle.MODERATE_GAME; // }else{ // GameStyle style = getGameStyle(); // Logger.Log("round:"+round+"gameStyle="+style); // if(style == GameStyle.LOOSE_GAME) { // // 整个赛场是loose的,我变tight // myGameStyle = GameStyle.TIGHT_GAME; // }else{ // myGameStyle = GameStyle.LOOSE_GAME; // } // } // if(curRoundRank <= 4) { // // 前4名,变保守 // isTight = true; // }else{ // // 跌到第四以后,反正都输了,激进一点 // isTight = false; // } // if(canLiveTillEnd() == false) { // isTight = true; // } Logger.Log("isTight="+isTight); remainTurn--; // 局数 -- allPlayerNums = playerCnt; Logger.Log("myjetton="+myAllJetton+" myMoney="+myAllMoney); Logger.Log("allPlayerNums="+allPlayerNums+" myPos="+myPos+" myCurPos="+myCurPos); if(preAllPlayerNums == 0) { preAllPlayerNums = allPlayerNums; } if(buttonOrBlind) { return; } awayFromBtn = myPos; // 判断玩家位置 if (allPlayerNums == 8) { if ((myPos == 3) || (myPos == 4)) { myCurPos = Position.EARLY_POS; } else if ((myPos == 5) || (myPos == 6)) { myCurPos = Position.MID_POS; } else { myCurPos = Position.LATE_POS; } }else if (allPlayerNums == 7) { if (myPos == 3 || (myPos == 4)) { myCurPos = Position.EARLY_POS; } else if ((myPos == 5)){ myCurPos = Position.MID_POS; } else { myCurPos = Position.LATE_POS; } }else if (allPlayerNums == 6) { if ((myPos == 3)) { myCurPos = Position.EARLY_POS; } else if ((myPos == 4)) { myCurPos = Position.MID_POS; } else { myCurPos = Position.LATE_POS; } }else if (allPlayerNums == 5) { if ((myPos == 3)) { myCurPos = Position.EARLY_POS; } else { myCurPos = Position.MID_POS; } }else if (allPlayerNums == 4) { myCurPos = Position.EARLY_POS; }else{ myCurPos = Position.LATE_POS; } } private void handleBlind(String content) { bigBlindBet = 0; String regex = "(\\d+):\\s(\\d+)"; Pattern pattern = Pattern.compile(regex); Matcher m = pattern.matcher(content); while(m.find()) { String bet = m.group(2); try{ int num = Integer.parseInt(bet); if(num > bigBlindBet) { bigBlindBet = num; } }catch(NumberFormatException ex) { Logger.Log(ex.getMessage()); } } } /** * 预处理消息 * @param msg */ private void preHandleMsg(String type, String body) { // Logger.Log("type:"+type+" body:"+body); if(type == null) return; type = type.trim(); if(type.equals("notify")){ long startTime = System.currentTimeMillis(); //获取结束时间 handleNotify(body); long endTime = System.currentTimeMillis(); //获取结束时间 Logger.Log("handleNotify运行时间: "+(endTime-startTime)+"ms"); }else if(type.equals("seat")) { // 座次信息 handleSeat(body); }else if(type.equals("blind")){ // 盲注消息 handleBlind(body); }else if(type.equals("hold")){ // 手牌消息 handleHold(body); }else if(type.equals("inquire")){ long startTime = System.currentTimeMillis(); //获取结束时间 // 询问消息 handleInquire(body); long endTime = System.currentTimeMillis(); //获取结束时间 Logger.Log("handleInquire运行时间: "+(endTime-startTime)+"ms"); }else if(type.equals("flop")){ // 三张公牌消息 handleFlop(body); }else if(type.equals("turn")){ // 一张转牌消息 handleTurn(body); }else if(type.equals("river")){ // 最后一张河牌消息 handleRiver(body); }else if(type.equals("showdown")){ // 摊牌消息 }else if(type.equals("pot-win")){ // 彩池分配消息消息 }else if(type.equals("game-over")){ // threadPool.shutdownNow(); } } public void play() { Logger.Log("begin to play"); thread = new SocketThread(serverIp, serverPort, localIp, localPort, ID); thread.setCallBack(this); thread.setPriority(Thread.NORM_PRIORITY+1); thread.start(); handEval = new KRHandEvaluator(); handEval.initData(); } @Override public void receiveMsg(String type, String body) { preHandleMsg(type, body); } }
whutjs/TexasHoldemAI
source/Player.java
66,339
package com.enjoyshop.activity; import android.content.Intent; import android.text.TextUtils; import android.view.View; import android.widget.TextView; import com.enjoyshop.R; import com.enjoyshop.data.DataManager; import com.enjoyshop.data.dao.User; import com.enjoyshop.utils.StringUtils; import com.enjoyshop.utils.ToastUtils; import com.enjoyshop.widget.ClearEditText; import com.enjoyshop.widget.EnjoyshopToolBar; import java.util.List; import butterknife.BindView; /** * Created by 高勤 * Time 2017/8/12 * Describe: 注册activity */ public class RegActivity extends BaseActivity { @BindView(R.id.toolbar) EnjoyshopToolBar mToolBar; @BindView(R.id.txtCountry) TextView mTxtCountry; @BindView(R.id.edittxt_phone) ClearEditText mEtxtPhone; @BindView(R.id.edittxt_pwd) ClearEditText mEtxtPwd; private String phone; private String pwd; @Override protected int getContentResourseId() { return R.layout.activity_reg; } @Override protected void init() { initToolBar(); } private void initToolBar() { mToolBar.setRightButtonOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { getCode(); } }); } /** * 获取手机号 密码等信息 */ private void getCode() { phone = mEtxtPhone.getText().toString().trim().replaceAll("\\s*", ""); pwd = mEtxtPwd.getText().toString().trim(); checkPhoneNum(); } /** * 对手机号进行验证 * 是否合法 是否已经注册 */ private void checkPhoneNum() { if (TextUtils.isEmpty(phone)) { ToastUtils.showSafeToast(RegActivity.this, "请输入手机号码"); return; } if (TextUtils.isEmpty(pwd)) { ToastUtils.showSafeToast(RegActivity.this, "请设置密码"); return; } if (!StringUtils.isMobileNum(phone)) { ToastUtils.showSafeToast(RegActivity.this, "请核对手机号码"); return; } if (!StringUtils.isPwdStrong(pwd)) { ToastUtils.showSafeToast(RegActivity.this, "密码太短,请重新设置"); return; } queryUserData(); } /** * 查询手机号是否已经注册了 * <p> * 注意注意: 在商业项目中,这里只需要请求注册接口即可.手机号是否存在由后台岗位同事判断 */ private void queryUserData() { List<User> mUserDataList = DataManager.queryUser(phone); if (mUserDataList != null && mUserDataList.size() > 0) { ToastUtils.showSafeToast(RegActivity.this, "手机号已被注册"); } else { jumpRegSecondUi(); } } /** * 跳转到注册界面二 */ private void jumpRegSecondUi() { Intent intent = new Intent(this, RegSecondActivity.class); intent.putExtra("phone", phone); intent.putExtra("pwd", pwd); startActivity(intent); finish(); } }
gaolhjy/enjoyshop
app/src/main/java/com/enjoyshop/activity/RegActivity.java
66,340
package Controller; import FiveChess.ChessMenu; import FiveChess.Login; import FiveChess.Regist; import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.sql.SQLException; public class ControlOp { private ControlOp controlOp; //本类 public Login loginView; //注册界面 public Regist registView; //登陆界面 public ChessMenu chessMenu; //下棋界面 private String userID; //用户ID private String userName; //用户名 private String opponentID; //对手ID private String opponentName; //对手名字 private Client client; //客户端 /** * 初始化ID和名字 * * @param i 用户/对手 * @param ID ID * @param name 昵称 */ public void setInfo(int i, String ID, String name) { if (i == 0) { userID = ID; userName = name; } else { opponentID = ID; opponentName = name; } } /** * 初始化 */ public ControlOp() { loginView = new Login(); registView = new Regist(); chessMenu = new ChessMenu(this); controlOp = this; login(); } /** * 登陆、注册 */ public void login() { /** * 点击登陆事件 */ ActionListener loginButtonLs = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String admin = loginView.adminText.getText(); String password = loginView.pwdText.getText(); try { System.out.println("登陆...用户名: " + admin + " 密码: " + password); String userID = ConnPool.login(admin, password); if (userID == null) { //登陆失败 System.out.println("登陆失败"); JOptionPane.showMessageDialog(null, "密码错误或者用户不存在"); } else { //登陆成功 loginView.loginFrame.setVisible(false); System.out.println("ID为" + userID + "的用户登陆成功"); setInfo(0, userID, admin); printInfo(); chessMenu.chessMenu.setVisible(true); chessMenu.messagePanel.setBlackText(userName); chessMenu.messagePanel.setWhiteText(userName); controlOp.chessMenu.messagePanel.addMsg(userName + ",欢迎登陆!\n", 1); System.out.println(userID + "客户端开启"); client = new Client(userID, controlOp); } } catch (SQLException ex) { ex.printStackTrace(); } } }; /** * 点击注册事件 */ ActionListener registButtion = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { loginView.loginFrame.setVisible(false); registView.registFrame.setVisible(true); } }; loginView.loginButton.addActionListener(loginButtonLs); loginView.registButton.addActionListener(registButtion); /** * 点击注册事件 */ ActionListener registButtonLs = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String admin = registView.getAdmin(); String password = registView.getPassword(); if (ConnPool.userExist(admin)) { System.out.println("注册...用户名已存在"); JOptionPane.showMessageDialog(null, "用户名已存在"); } else { if (ConnPool.regist(admin, password)) { System.out.println("注册成功"); JOptionPane.showMessageDialog(null, "注册成功"); registView.registFrame.setVisible(false); loginView.loginFrame.setVisible(true); } else { System.out.println("注册失败"); JOptionPane.showMessageDialog(null, "注册失败"); } } } }; /** * 点击返回事件 */ ActionListener returnButtonLs = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { registView.registFrame.setVisible(false); loginView.loginFrame.setVisible(true); } }; registView.registButton.addActionListener(registButtonLs); registView.returnButton.addActionListener(returnButtonLs); } /** * 打印成员变量信息,用于调试 */ private void printInfo() { System.out.println("info:"); System.out.println(userID); System.out.println(userName); System.out.println(opponentID); System.out.println(opponentName); } /** * 退出登陆 */ public void loginOut() { //未结束对战 if (chessMenu.gamePanel.isNetworkPK && !chessMenu.gamePanel.gameOver) { JOptionPane.showMessageDialog(null, "请先结束对战!"); return; } //用户注销 ConnPool.loginOut(userID); System.out.println("注销...ID为" + userID + "的用户注销"); //棋盘不可见 chessMenu.chessMenu.setVisible(false); //登陆画面可见 loginView.loginFrame.setVisible(true); } /** * 请求双人对战 * * @throws SQLException 数据库异常 */ public void beiginPlay() throws SQLException { String i = ConnPool.findOpponent(userID); //查找不到对手 if (i == null) { JOptionPane.showMessageDialog(null, "无匹配对手"); return; } //根据查找到对手,根据反馈信息解析对手ID和昵称 String[] rs = i.split(":"); opponentID = rs[0]; opponentName = rs[1]; System.out.println("请求对战...找到的对手的ID为" + opponentID); client.setOppentID(opponentID); //发送类别为3内容为#的信息 client.sendMsg("#", 3); } public void sendMsg(String msg, int type) { client.sendMsg(msg, type); } /** * 获得用户名字 * * @return 用户名 */ public String getUserName() { return userName; } /** * 获得对手名字 * * @return 对手名 */ public String getOpponentName() { return opponentName; } /** * 获得ID * * @return ID */ public String getUserID() { return userID; } }
seehunter/FiveChess
FiveChess/src/Controller/ControlOp.java
66,341
package com.qx.pvp; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import com.qx.persistent.DBHash; @Entity @Table(name = "pvp_bean") public class PvpBean implements DBHash{ @Id public long junZhuId; /*当日已经参加百战的次数*/ public int usedTimes; /*当日剩余参加百战的次数*/ public int remain; /*军衔等级,对应baizhan.xml的jibie字段*/ public int junXianLevel = -1; // @Column(nullable = false, columnDefinition = "int default -1") // public int zuheId; //防守技能 @Column(nullable = false, columnDefinition = "int default -1") public int gongJiZuHeId; //攻击技能 public int highestRank;//当前最高排名 public int lastHighestRank; // 上一次最高排名 public int winToday; @Column(columnDefinition = "INT default 0") public int allWin; /*今日已经购买百战的回数*/ public int buyCount; /* 今日已购买 清除百战CD的次数 */ public int cdCount; /*战斗记录是否被玩家查看: true :表示被查看,false 表示没有 */ @Column(nullable = false, columnDefinition = "boolean default true") public boolean isLook; /*上次百战的时间*/ public Date lastDate; /*上次查看百战信息的时间*/ public Date lastShowTime; /*上次发送每日奖励的时间*/ public Date lastAwardTime; // 当日刷新对手列表的次数 @Column(columnDefinition = "INT default 0") public int todayRefEnemyTimes; // 显示的威望值 public int showWeiWang; // 结算的威望值 public int lastWeiWang; // 总共参加百战的次数 public int allBattleTimes; // 主动战斗历史次数 /* * 对手 */ public int rank1; public int rank2; public int rank3; public int rank4; public int rank5; public int rank6; public int rank7; public int rank8; public int rank9; public int rank10; @Column(columnDefinition = "DATETIME default '2014-12-01 00:00:00'") public Date initPvpTime; public Date lastGetAward; // 上次计算领取生产奖励的时间 public Date lastCalculateAward; // 上次计算生产奖励的时间 public int leiJiWeiWang; //生产奖励累计威望值 public int getProduceWeiWangTimes = 0; // 累计领取威望奖励的次数 // public int dailyaward; public int rankAward; // 累计的最高排名奖励 @Override public long hash() { return junZhuId; } }
10people/7x_Server
src/com/qx/pvp/PvpBean.java
66,342
package com.demo1.client.model; import com.demo1.client.comman.GradeRecord; import javax.swing.table.AbstractTableModel; import java.util.List; import java.util.Vector; public class GradeRModel extends AbstractTableModel { private Vector<String> columns; private Vector<Vector> rows; private GradeRDAO grDAO; public GradeRModel() { columns = new Vector<String>(); columns.add("对手"); columns.add("胜负情况"); columns.add("回合数"); columns.add("对方等级"); columns.add("我方等级"); columns.add("游戏模式"); columns.add("时间"); rows = new Vector<Vector>(); } private void addRows(List<GradeRecord> list) { for (GradeRecord gr : list) { Vector temp = new Vector(); temp.add(gr.getRivalName()); temp.add(gr.getWin()); temp.add(gr.getRounds()); temp.add(gr.getRivalLevel()); temp.add(gr.getUserLevel()); temp.add(gr.getModel()); temp.add(gr.getTime()); //把temp数据添加到rows rows.add(temp); } } public void updateRows(List<GradeRecord> list) { this.addRows(list); } @Override public String getColumnName(int column) { return this.columns.get(column).toString(); } @Override public int getRowCount() { return this.rows.size(); } @Override public int getColumnCount() { return this.columns.size(); } @Override public Object getValueAt(int rowIndex, int columnIndex) { return ((Vector) rows.get(rowIndex)).get(columnIndex); } }
MSJeinlong/Gobang_Net
src/com/demo1/client/model/GradeRModel.java
66,343
package bean; import View.Room; import util.MSUtil; import javax.swing.*; import java.awt.*; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.io.IOException; public class MyJPanel extends JPanel implements MouseListener { public static int num; public static Room room; // public static JButton b1 = new JButton("准备"); // public static JButton b2 = new JButton("认输"); // public static JButton b3 = new JButton("悔棋"); // public static JButton b4 = new JButton("关于本游戏"); // public static JButton b5 = new JButton("退出"); public static JLabel b1 = new JLabel(" 准备"); public static JLabel b2 = new JLabel(" 认输"); public static JLabel b3 = new JLabel(" 悔棋"); public static JLabel b4 = new JLabel("关于本游戏"); public static JLabel b5 = new JLabel(" 退出"); public static Game game = new Game(); public static JLabel l1 = new JLabel(); public static JLabel l2 = new JLabel(); public static JLabel l3 = new JLabel(); public static JLabel l4 = new JLabel(); public static JLabel l5 = new JLabel(""); public static JLabel l6 = new JLabel(""); public static JLabel l7 = new JLabel(""+num); public static JLabel l8 = new JLabel("房间名"); public static JLabel l9 = new JLabel("我"); public static JLabel l10 = new JLabel("对手"); public static Boolean maker; public static Boolean flag = false; public JLabel getL4() { return l4; } public void setL4(JLabel l4) { this.l4 = l4; } public int x; public int y; public int chessX; public int chessY; public MyJPanel(Room room) { super(); setLayout(null); this.room = room; this.addMouseListener(this); Font font1 = new Font("微软雅黑",Font.BOLD,20); b1.setFont(font1); b2.setFont(font1); b3.setFont(font1); b4.setFont(font1); b5.setFont(font1); b1.setBounds(0,0,100,50); b2.setBounds(200,0,100,50); b3.setBounds(400,0,100,50); b4.setBounds(600,0,100,50); b5.setBounds(800,0,100,50); l9.setBounds(0,350,100,50); l10.setBounds(900,350,100,50); l3.setBounds(0,400,100,50); l4.setBounds(900,400,100,50); l5.setBounds(0,500,100,50); l6.setBounds(900,500,100,50); l7.setBounds(0,200,100,50); l8.setBounds(0,150,100,50); // b1.addActionListener(new ActionListener() { // @Override // public void actionPerformed(ActionEvent e) { // if (l4.getText().equals("")){ // JOptionPane.showMessageDialog(form1,"还没有对手进入!"); // }else { // l5.setText("已准备!"); // try { // MSUtil.oos.writeUTF("ready"); // MSUtil.oos.flush(); // MSUtil.oos.writeObject(l4.getText()); // MSUtil.oos.flush(); // } catch (IOException ioException) { // ioException.printStackTrace(); // } // if (l6.getText().equals("已准备!")){ // JOptionPane.showMessageDialog(form1,"游戏开始,房主先手!"); // l5.setText(""); // l6.setText(""); // if (maker){ // flag = true; // }else { // flag = false; // } // } // } // } // }); // b2.addActionListener(new ActionListener() { // @Override // public void actionPerformed(ActionEvent e) { // int result = JOptionPane.showConfirmDialog(form1,"您确定要认输吗?","认输",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE); // if (result==0){ // try { // MSUtil.oos.writeUTF("defeat"); // MSUtil.oos.flush(); // MSUtil.oos.writeObject(l4.getText()); // MSUtil.oos.flush(); // } catch (IOException ioException) { // ioException.printStackTrace(); // } // game.Clean(); // form1.repaint(); // game.Rush(); // JOptionPane.showMessageDialog(form1,"您已经认输!"); // l5.setText("未准备"); // l6.setText("未准备"); // } // } // }); // b3.addActionListener(new ActionListener() { // @Override // public void actionPerformed(ActionEvent e) { // if (flag==false){ // JOptionPane.showMessageDialog(form1,"等待对方同意悔棋"); // try { // MSUtil.oos.writeUTF("regret"); // MSUtil.oos.flush(); // MSUtil.oos.writeObject(l4.getText()); // MSUtil.oos.flush(); // int[] chess = new int[]{x,y}; // MSUtil.oos.writeObject(chess); // MSUtil.oos.flush(); // } catch (IOException ioException) { // ioException.printStackTrace(); // } // }else { // JOptionPane.showMessageDialog(form1,"现在是您的回合,不能悔棋"); // } // } // }); // b4.addActionListener(new ActionListener() { // @Override // public void actionPerformed(ActionEvent e) { // JOptionPane.showMessageDialog(form1,"本游戏为五子棋游戏,黑方和白方依次落子,若有一方凑齐5个棋子连在一起,则其获胜"); // } // }); // b5.addActionListener(new ActionListener() { // @Override // public void actionPerformed(ActionEvent e) { // int result = JOptionPane.showConfirmDialog(form1,"您确定要退出吗?","退出",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE); // if (result==0){ // if (!l4.getText().equals("")){ // try { // MSUtil.oos.writeUTF("out"); // MSUtil.oos.flush(); // MSUtil.oos.writeObject(l4.getText()); // MSUtil.oos.flush(); // } catch (IOException ioException) { // ioException.printStackTrace(); // } // } // open = false; // MSUtil.out(); // Hall hall1 = new Hall(form1.username1); // form1.dispose(); // hall1.setVisible(true); // } // } // }); add(b1); add(b2); add(b3); add(b4); add(b5); add(l1); add(l2); add(l3); add(l4); add(l5); add(l6); add(l7); add(l8); add(l9); add(l10); } public void paint(Graphics g) { super.paint(g); game.Paint(g); } @Override public void mousePressed(MouseEvent e) { x = e.getX(); y = e.getY(); if (x>=100 && x<=900 && y>=100 && y<=900) { chessX = (x - 100) / 50; chessY = (y - 100) / 50; if (flag){ makeChess(chessX,chessY); int[] chess = new int[]{chessX,chessY}; try { MSUtil.oos.writeUTF("down"); MSUtil.oos.flush(); MSUtil.oos.writeObject(l4.getText()); MSUtil.oos.flush(); MSUtil.oos.writeObject(chess); MSUtil.oos.flush(); } catch (IOException ioException) { ioException.printStackTrace(); } flag = false; } // b1.setBounds(0,0,100,50); // b2.setBounds(200,0,100,50); // b3.setBounds(400,0,100,50); // b4.setBounds(600,0,100,50); // b5.setBounds(800,0,100,50); }else if (x>=0 && x<=100 && y>=0 && y<=50){ if (l4.getText().equals("")){ JOptionPane.showMessageDialog(room,"还没有对手进入!"); }else { l5.setText("已准备!"); try { MSUtil.oos.writeUTF("ready"); MSUtil.oos.flush(); MSUtil.oos.writeObject(l4.getText()); MSUtil.oos.flush(); } catch (IOException ioException) { ioException.printStackTrace(); } if (l6.getText().equals("已准备!")){ JOptionPane.showMessageDialog(room,"游戏开始,房主先手!"); l5.setText(""); l6.setText(""); if (maker){ flag = true; }else { flag = false; } } } }else if (x>=200 && x<=300 && y>=0 && y<=50){ int result = JOptionPane.showConfirmDialog(room,"您确定要认输吗?","认输",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE); if (result==0){ try { MSUtil.oos.writeUTF("defeat"); MSUtil.oos.flush(); MSUtil.oos.writeObject(l4.getText()); MSUtil.oos.flush(); } catch (IOException ioException) { ioException.printStackTrace(); } game.Clean(); room.repaint(); game.Rush(); JOptionPane.showMessageDialog(room,"您已经认输!"); l5.setText("未准备"); l6.setText("未准备"); } }else if (x>=400 && x<=500 && y>=0 && y<=50){ if (flag==false){ JOptionPane.showMessageDialog(room,"等待对方同意悔棋"); try { MSUtil.oos.writeUTF("regret"); MSUtil.oos.flush(); MSUtil.oos.writeObject(l4.getText()); MSUtil.oos.flush(); int[] chess = new int[]{chessX,chessY}; MSUtil.oos.writeObject(chess); MSUtil.oos.flush(); } catch (IOException ioException) { ioException.printStackTrace(); } }else { JOptionPane.showMessageDialog(room,"现在是您的回合,不能悔棋"); } }else if (x>=600 && x<=700 && y>=0 && y<=50){ JOptionPane.showMessageDialog(room,"本游戏为五子棋游戏,黑方和白方依次落子,若有一方凑齐5个棋子连在一起,则其获胜"); }else if (x>=800 && x<=900 && y>=0 && y<=50){ int result = JOptionPane.showConfirmDialog(room,"您确定要退出吗?","退出",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE); if (result==0){ if (!l4.getText().equals("")){ try { MSUtil.oos.writeUTF("out"); MSUtil.oos.flush(); MSUtil.oos.writeObject(l4.getText()); MSUtil.oos.flush(); } catch (IOException ioException) { ioException.printStackTrace(); } } game.Clean(); game.Rush(); MSUtil.out(); MSUtil.hall.setVisible(true); room.dispose(); } } } @Override public void mouseClicked(MouseEvent arg0) { } @Override public void mouseEntered(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseExited(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseReleased(MouseEvent e) { // TODO Auto-generated method stub } public void makeChess(int x,int y){ int[] B = game.Judge(x, y); this.repaint(); int b = game.P(); if (b == 1) { JOptionPane.showMessageDialog(this,"游戏结束,黑棋获胜"); game.Clean(); game.Rush(); flag = false; l5.setText("未准备"); l6.setText("未准备"); } else if (b == 2) { JOptionPane.showMessageDialog(this,"游戏结束,白棋获胜"); game.Clean(); game.Rush(); flag = false; l5.setText("未准备"); l6.setText("未准备"); } Boolean Pe = game.Peace(); if (Pe == true) { JOptionPane.showMessageDialog(this,"游戏结束,双方和棋"); game.Clean(); game.Rush(); flag = false; l5.setText("未准备"); l6.setText("未准备"); } this.repaint(); } public void Regret(int x,int y){ int answer = game.Regret(x,y); room.repaint(); if(answer ==1) { JOptionPane.showMessageDialog(room,"黑方悔棋"); } else if(answer ==2) { JOptionPane.showMessageDialog(room,"白方悔棋"); } else if(answer ==0) { JOptionPane.showMessageDialog(room,"棋局还未开始"); } } }
Glinkky/FiveChess
Client/src/bean/MyJPanel.java
66,344
package top.mcpbs.games.rush; import cn.nukkit.Player; import cn.nukkit.Server; import cn.nukkit.entity.weather.EntityLightning; import cn.nukkit.item.Item; import cn.nukkit.plugin.Plugin; import cn.nukkit.scheduler.PluginTask; import top.mcpbs.games.Main; import top.mcpbs.games.room.Room; import top.mcpbs.games.util.DateUtil; import java.util.ArrayList; public class RushTask extends PluginTask { public RushTask(Plugin owner) { super(owner); } @Override public void onRun(int i) { for (RushRoom room : RushRoom.RushRooms.values()){ if (room.isPlaying == false && room.waiting.size() == 2 && room.isStartChemical == false){ Server.getInstance().getScheduler().scheduleRepeatingTask(new GameStartTask(Main.plugin,room),20 * 1); room.isStartChemical = true; } if (room.isPlaying == false){ for (Player player : room.waiting){ if (room.waiting.size() == 1) { player.sendActionBar("§a等待其他玩家加入..."); } player.setHealth(player.getMaxHealth()); player.getFoodData().setLevel(20); ArrayList l = new ArrayList(); l.clear(); l.add("§7#" + DateUtil.getDate("yyyy/MM/dd")); l.add(" "); l.add("地图名称"); l.add("§a" + Room.awaiting.get(player).mapname); l.add(" "); l.add("等待游戏开始..."); l.add(" "); l.add("§eplay.mcpbs.top"); Main.s.showScoreboard(player, "§l§6战桥", l); if (player.getY() < 90) { player.teleport(room.pos1); } } } if (room.isPlaying) { for (Player player : room.playing) { if (player.isOnline()) { player.setHealth(player.getMaxHealth()); player.getFoodData().setLevel(20); if (player.getY() < 90) { EntityLightning l = new EntityLightning(player.getChunk(), EntityLightning.getDefaultNBT(player.getLocation())); l.setEffect(false); l.spawnToAll(); player.teleport(room.pos.get(player)); player.sendTitle("", "§c你掉进了虚空"); } if (!player.getInventory().contains(Item.get(24))) { player.getInventory().addItem(Item.get(24, 0, 256)); } } if (room.isend == false) { ArrayList l = new ArrayList(); l.clear(); l.add("§7#" + DateUtil.getDate("yyyy/MM/dd")); l.add(" "); l.add("地图名称"); l.add("§a" + Room.aplaying.get(player).mapname); l.add(" "); l.add("你的得分"); l.add("§a" + ((RushRoom) Room.aplaying.get(player)).scores.get(player)); l.add(" "); ArrayList<Player> tmp = (ArrayList) Room.aplaying.get(player).playing.clone(); tmp.remove(player); l.add("对手"); l.add("§a" + tmp.get(0).getName()); l.add("对手得分"); l.add("§a" + ((RushRoom) Room.aplaying.get(player)).scores.get(tmp.get(0)) + " "); l.add(" "); l.add("§eplay.mcpbs.top"); Main.s.showScoreboard(player, "§l§e战桥", l); } } } } } }
smartcmd/pbsgames
src/main/java/top/mcpbs/games/rush/RushTask.java
66,345
package com.txxia.game.fivechess.game; import java.util.Deque; import java.util.LinkedList; import android.os.Handler; import android.os.Message; /** * 处理游戏逻辑 * @author cuiqing */ public class Game { public static final int SCALE_SMALL = 11; public static final int SCALE_MEDIUM = 15; public static final int SCALE_LARGE = 19; // 自己 Player me; // 对手 Player challenger; private int mMode = 0; // 默认黑子先出 private int mActive = 1; int mGameWidth = 0; int mGameHeight = 0; int[][] mGameMap = null; Deque<Coordinate> mActions ; public static final int BLACK = 1; public static final int WHITE = 2; private Handler mNotify; public Game(Handler h, Player me, Player challenger){ this(h, me, challenger, SCALE_MEDIUM, SCALE_MEDIUM); } public Game(Handler h, Player me, Player challenger, int width, int height){ mNotify = h; this.me = me; this.challenger = challenger; mGameWidth = width; mGameHeight = height; mGameMap = new int[mGameWidth][mGameHeight]; mActions = new LinkedList<Coordinate>(); } public void setMode(int mode){ this.mMode = mode; } public int getMode(){ return mMode; } /** * 悔棋一子 * @return 是否可以悔棋 */ public boolean rollback(){ Coordinate c = mActions.pollLast(); if (c != null){ mGameMap[c.x][c.y] = 0; changeActive(); return true; } return false; } /** * 游戏宽度 * @return 棋盘的列数 */ public int getWidth(){ return mGameWidth; } /** * 游戏高度 * @return 棋盘横数 */ public int getHeight(){ return mGameHeight; } /** * 落子 * @param x 横向下标 * @param y 纵向下标 * @return 当前位置是否可以下子 */ public boolean addChess(int x, int y){ if (mMode == GameConstants.MODE_FIGHT){ if(mGameMap[x][y] == 0){ int type ; if (mActive == BLACK){ mGameMap[x][y] = BLACK; type = Game.BLACK; } else { mGameMap[x][y] = WHITE; type = Game.WHITE; } if(!isGameEnd(x, y, type)){ changeActive(); sendAddChess(x, y); mActions.add(new Coordinate(x, y)); } return true; } } else if(mMode == GameConstants.MODE_NET) { if(mActive == me.type && mGameMap[x][y] == 0){ mGameMap[x][y] = me.type; mActive = challenger.type; if(!isGameEnd(x, y, me.type)){ mActions.add(new Coordinate(x, y)); } sendAddChess(x, y); return true; } } else if(mMode == GameConstants.MODE_SINGLE){ if(mActive == me.type && mGameMap[x][y] == 0){ mGameMap[x][y] = me.type; mActive = challenger.type; if(!isGameEnd(x, y, me.type)){ sendAddChess(x, y); mActions.add(new Coordinate(x, y)); } return true; } } return false; } /** * 落子 * @param x 横向下标 * @param y 纵向下标 * @param player 游戏选手 */ public void addChess(int x, int y, Player player){ if(mGameMap[x][y] == 0){ mGameMap[x][y] = player.type; mActions.add(new Coordinate(x, y)); boolean isEnd = isGameEnd(x, y, player.type); mActive = me.type; if(!isEnd){ mNotify.sendEmptyMessage(GameConstants.ACTIVE_CHANGE); } } } /** * 落子 * @param c 下子位置 * @param player 游戏选手 */ public void addChess(Coordinate c, Player player){ addChess(c.x, c.y, player); } public static int getFighter(int type){ if (type == BLACK){ return WHITE; } else { return BLACK; } } /** * 返回当前落子方 * @return mActive */ public int getActive(){ return mActive; } /** * 获取棋盘 * @return 棋盘数据 */ public int[][] getChessMap(){ return mGameMap; } /** * 获取棋盘历史 * @return mActions */ public Deque<Coordinate> getActions(){ return mActions; } /** * 重置游戏 */ public void reset(){ mGameMap = new int[mGameWidth][mGameHeight]; mActive = BLACK; mActions.clear(); } /** * 不需要更新落子方,谁输谁先手 */ public void resetNet(){ mGameMap = new int[mGameWidth][mGameHeight]; mActions.clear(); } private void changeActive(){ if(mActive == BLACK){ mActive = WHITE; } else { mActive = BLACK; } } private void sendAddChess(int x, int y){ Message msg = new Message(); msg.what = GameConstants.ADD_CHESS; msg.arg1 = x; msg.arg2 = y; mNotify.sendMessage(msg); } // 判断是否五子连珠 private boolean isGameEnd(int x, int y, int type){ int leftX = x-4 > 0? x-4 : 0; int rightX = x+4 < mGameWidth-1 ? x+4: mGameWidth-1; int topY = y-4 > 0? y-4 : 0; int bottomY = y + 4< mGameHeight-1 ? y+4: mGameHeight-1; int horizontal = 1; // 横向向左 for (int i = x - 1; i >= leftX ; --i){ if (mGameMap[i][y] != type){ break; } ++horizontal; } // 横向向右 for (int i = x + 1; i <= rightX ; ++i){ if (mGameMap[i][y] != type){ break; } ++horizontal; } if (horizontal>=5) { sendGameResult(type); return true; } int vertical = 1; // 纵向向上 for (int j = y - 1; j >= topY ; --j){ if (mGameMap[x][j] != type){ break; } ++vertical; } // 纵向向下 for (int j = y + 1; j <= bottomY ; ++j){ if (mGameMap[x][j] != type){ break; } ++vertical; } if (vertical >= 5) { sendGameResult(type); return true; } int leftOblique = 1; // 左斜向上 for (int i = x + 1,j = y - 1; i <= rightX && j >= topY ; ++i, --j){ if (mGameMap[i][j] != type){ break; } ++leftOblique; } // 左斜向下 for (int i = x - 1,j = y + 1; i >= leftX && j <= bottomY ; --i, ++j){ if (mGameMap[i][j] != type){ break; } ++leftOblique; } if (leftOblique >= 5) { sendGameResult(type); return true; } int rightOblique = 1; // 右斜向上 for (int i = x - 1,j = y - 1; i >= leftX && j >= topY ; --i, --j){ if (mGameMap[i][j] != type){ break; } ++rightOblique; } // 右斜向下 for (int i = x + 1,j = y + 1; i <= rightX && j <= bottomY ; ++i, ++j){ if (mGameMap[i][j] != type){ break; } ++rightOblique; } if (rightOblique >= 5) { sendGameResult(type); return true; } return false; } private void sendGameResult(int player){ Message msg = Message.obtain(); msg.what = GameConstants.GAME_OVER; msg.arg1 = player; mNotify.sendMessage(msg); } }
cuiqingandroid/FiveChess
app/src/main/java/com/txxia/game/fivechess/game/Game.java
66,346
package chess.panels; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.io.*; import java.net.Socket; import chess.pieces.Chess; import chess.recorder.Record; import chess.shop.MoneyShop; import chess.shop.ShengwangShop; import chess.shop.Shop; import chess.style.Style; import chess.threads.OpponentEmoThread; import chess.threads.YourEmoThread; import chess.util.Constants; import chess.util.ImagePath; import chess.web.ChessChannel; import chess.web.Receiver; import chess.web.Sender; public class WebPanel extends PanelBase implements MouseListener, ActionListener, KeyListener { public final static String SIGN_SPLIT = "&", LINE_SPLIT = "#"; public final static char SIGN_SPLIT_CHAR = '&', LINE_SPLIT_CHAR = '#'; public static final char INVITE_CONNECT = 'a', NO_PERSON_FOUND = 'b', REGIST = 'c', PREPARE = 'd', APPLY_ACCOUNT = 'e', POSITION = 'f', ACCEPT_CONNECT = 'g', ERROR = 'h', APPLY_REGRET = 'i', ACCEPT_REGRET = 'j', REJECT_REGRET = 'k', SET_NAME = 'l', RESET_PASSWARD = 'm', SUCCESS_SET_PASSWARD = 'n', SYSTEM_WINDOWS = 'o', REJECT_CONNECT = 'p', FIND_ONLINE = 'q', SURREND = 'r', GET_ID = 's', SEND_MESSAGE = 't', APPLY_PEACE = 'u', AGREE_PEACE = 'v', REJECT_PEACE = 'w', DISCONNECT = 'x', PLAYER_INFO = 'y', WRONG_PASSWARD = 'z', APPLY_SWAP = 'A', AGREE_SWAP = 'B', REJECT_SWAP ='C', SERVER_CLOSE = 'D', CHANGE_HEAD = 'E', CHANGE_NAME ='F', EMO_MES ='G', SHENGBIAN = 'H', LONG_CHANGE = 'I', TO_SHENGWANG ='J', GET_MONEY = 'K'; public static final String DEFAULT_NAME = "default", COLOR_BUTTON = "Cl", DISCONNECT_BUTTON = "Db", DEFAULT_HEAD = "default.png"; private String opponentName = DEFAULT_NAME, opponentID, yourName = DEFAULT_NAME, yourID, yourHead = DEFAULT_HEAD, opponentHead = DEFAULT_HEAD, yourEmo, opponentEmo; private StringBuilder messageBuilder = new StringBuilder(); private boolean isConnect, isYouPrepare, isOpponentPrepare, isYou; private int yourColor, oOX,oOY,oNX, oNY; private JButton confirmButton, applyButton, forgetButton, emoButton, setSignButton, prepareButton, clorButton, disconnectBut; public JDialog registerDialog = new JDialog(); private JTextField account = new JTextField("10001"), passward = new JTextField("123456"); private Sender sender; private Receiver receiver; private Socket client; private YourEmoThread yourEmoThread; private OpponentEmoThread opponentEmoThread; public Shop shengwangShop, moneyShop; JTextArea textArea = new JTextArea("系统消息:\n"); JScrollPane scrollPane; private void setRegisterDialog(){ registerDialog.setLocationRelativeTo(null); registerDialog.setLayout(new GridLayout(4,2)); confirmButton = setButton("确定", Constants.CONFIRM_BUTTON); applyButton = setButton("注册", Constants.APPLY_BUTTON); forgetButton = setButton("找密码",Constants.FORGET_BUTTON); setSignButton = setButton("换签名", Constants.SIGN_BUTTON); registerDialog.setSize(159,150); registerDialog.add(new JLabel("账号")); registerDialog.add(account); registerDialog.add(new JLabel("密码")); registerDialog.add(passward); registerDialog.add(confirmButton); registerDialog.add(applyButton); registerDialog.add(forgetButton); registerDialog.add(setSignButton); } @Override public int reverseX(int x){ return 7-x; } public WebPanel(JLabel hint, String IP, int port){ shengwangShop = new ShengwangShop(this); moneyShop = new MoneyShop(this); type = PanelType.Web; textArea.setFont(Constants.LITTLE_BLACK); scrollPane = new JScrollPane(textArea); disconnectBut = setButtons("断开连接", DISCONNECT_BUTTON); this.playerHint = hint; init(); this.setFocusable(true); this.addMouseListener(this);//自行在构造器中添加! try { client = new Socket(IP, port); } catch (IOException e) { System.out.println("webPanel_Constructure_ck: 没有连接到服务器"); JOptionPane.showMessageDialog(null, "没有连接到服务器", "错误", JOptionPane.ERROR_MESSAGE); } sender = new Sender(client); receiver = new Receiver(client, this); yourEmoThread = new YourEmoThread(this); opponentEmoThread = new OpponentEmoThread(this); new Thread(yourEmoThread).start(); new Thread(opponentEmoThread).start(); new Thread(sender).start(); new Thread(receiver).start(); prepareButton = setButtons("准备", Constants.PREPARE_BUTTON); clorButton = setButtons("交换先后手", COLOR_BUTTON); this.emoButton = setButtons("发表情", Constants.YOUR_EMO); setBounds(0,0,Constants.PANEL_WEIGHT, Constants.FRAME_HEIGHT); textArea.setColumns(15); repaint(); setRegisterDialog(); } public WebPanel(JLabel hint) { this(hint, Constants.HOST, Constants.PORT); } @Override public void paint(Graphics g) { super.paint(g);//clear scrollPane.setBounds(540,350,205,240); add(scrollPane); this.setBounds(0, 0, Constants.PANEL_WEIGHT, Constants.FRAME_HEIGHT); // g.drawImage(Toolkit.getDefaultToolkit().getImage(ImagePath.BACKGROUND), // 0, 0, BOARD_WEIGHT, BOARD_HEIGHT, this); g.drawImage(Toolkit.getDefaultToolkit().getImage(ImagePath.BACKGROUND), -42, -42, BOARD_WEIGHT+40, BOARD_HEIGHT+40, this); //你的头像 g.drawImage(Toolkit.getDefaultToolkit().getImage(Constants.HEAD_PATH + File.separator + yourHead), 545, 180, 58, 58, this); //对手头像 g.drawImage(Toolkit.getDefaultToolkit().getImage(Constants.HEAD_PATH + File.separator + opponentHead), 545, 240, 58, 58, this); prepareButton.setBounds(600,80,120,40); disconnectBut.setBounds(600,130,120,40); clorButton.setBounds(540,310,100,40); emoButton.setBounds(631, 310,100,40); drawChess(g); if (selectedChess != null) { selectedChess.drawSelectedChess(g); } textArea.setBackground(new Color(20,244,244)); this.add(prepareButton); add(disconnectBut); add(clorButton); add(emoButton); g.drawRect(Chess.MARGIN + Chess.SPACE * oOX,Chess.MARGIN + Chess.SPACE * oOY,Chess.SIZE,Chess.SIZE); g.drawRect(Chess.MARGIN + Chess.SPACE * oNX,Chess.MARGIN + Chess.SPACE * oNY,Chess.SIZE,Chess.SIZE); g.setFont(Constants.LITTLE_BLACK); g.drawString(yourID + "(你)", 606,205); g.drawString(yourName, 606,225); g.drawString(opponentID + "(对手)", 606,265); g.drawString(opponentName, 606,285); g.drawString("你的颜色:" + (yourColor == 1? "红":"黑"),580,65); g.setFont(Constants.LARGE_BLACK); g.drawString(currentPlayer == 1? "红":"黑", 580,40); if (isOver && isStart)//绘制结束图像 switch (judger) { case 1: g.drawString("red win!!", 100, 200); break; case -1: g.drawString("black win!!", 100, 200); break; case 2: g.drawString("和局", 100, 200); break; } if(yourEmo != null) g.drawImage(Toolkit.getDefaultToolkit().getImage(Constants.EMO_PATH + File.separator + yourEmo), 672, 165, 71, 71, this); if(opponentEmo != null)g.drawImage(Toolkit.getDefaultToolkit().getImage(Constants.EMO_PATH + File.separator + opponentEmo), 672, 225, 71,71, this); } @Override public void init() { isOpponentPrepare = false; isYouPrepare = false; oOY = -1; oOX = -1; oNX = -1; oNY = -1; super.init(); if(yourColor != currentPlayer) for (Chess chess : chessList) { chess.setPoint(reverseX(chess.getPoint().x), chess.getPoint().y); } System.out.println("weboanel_init_ck: finished"); } @Override public void actionPerformed(ActionEvent e) { String cmd = e.getActionCommand(); switch (cmd){ case Constants.CONFIRM_BUTTON: if(!isConnect) { send(ChessChannel.REGISTER + LINE_SPLIT + account.getText() + SIGN_SPLIT + passward.getText()); registerDialog.setVisible(false); }else JOptionPane.showMessageDialog(null,"请先与对手断开连接再尝试登陆。"); break; case Constants.APPLY_BUTTON: String question = (String)JOptionPane.showInputDialog(null, "请输入你的密保问题,不能包含”#““&”","密保问题"); if(question != null && !question.isEmpty() && !question.contains(LINE_SPLIT) && !question.contains(SIGN_SPLIT)){ String key = (String) JOptionPane.showInputDialog(null, "请输入密保答案", "设置密保答案,不能包含”#““&”", JOptionPane.INFORMATION_MESSAGE); if(key != null && !key.isEmpty() && !key.contains(LINE_SPLIT) && !key.contains(SIGN_SPLIT)){ send(ChessChannel.APPLY + LINE_SPLIT + question +SIGN_SPLIT_CHAR + key); } } break; case Constants.PREPARE_BUTTON: if(isConnect && !(isStart && !isOver)) { isYouPrepare = true; if (isOpponentPrepare) { init(); creatChess(yourColor); if(yourColor != 1) for (Chess chess : chessList) chess.setPoint(new Point(reverseX(chess.getPoint().x), chess.getPoint().y)); isYou = yourColor == 1; isStart = true; isOver = false; } send(PREPARE); System.out.println("webpanel_actionperform_ck actionPerform 你已准备"); textArea.append("你已准备\n"); repaint(); }else JOptionPane.showMessageDialog(null,"您还未结束当前游戏,无法准备。"); break; case COLOR_BUTTON: if((!isStart || (isStart && isOver)) && isConnect) send(APPLY_SWAP); System.out.println("webpanel_actionpetform ck: actionPerform 改颜色了!"); break; case DISCONNECT_BUTTON: if(isConnect) { JOptionPane.showMessageDialog(null, "您已断开连接", "提示", JOptionPane.WARNING_MESSAGE); send(DISCONNECT); disconnect(); repaint(); } break; case Constants.FORGET_BUTTON: String var = JOptionPane.showInputDialog(null,"请输入要找回密码的账号"); if(var != null && !var.isEmpty()) send(ChessChannel.FIND_PASSWARD + LINE_SPLIT + var); break; case Constants.SIGN_BUTTON: signature(12); break; case Constants.YOUR_EMO: String emoN = (String) JOptionPane.showInputDialog(null, "向对方发送一个表情", "发送表情", JOptionPane.QUESTION_MESSAGE, null, Constants.EMOS, Constants.EMOS[0]); if(emoN != null && !emoN.isEmpty())yourEmoThread.continuing(emoN); break; } } public void signature(int len){ if(isRegiserd()) { String var2 = null; // var2 = JOptionPane.showInputDialog(null, "请输入新的个性签名。\n不得包含#或&,长度不得超过"+len); // if(var2 != null && !var2.contains(SIGN_SPLIT) && !var2.contains(LINE_SPLIT) && var2.length()<=len) { // send(var2, Integer.toString(ChessChannel.SET_SIGN)); // textArea.append("签名设置成功!\n"); // } while(var2 == null){ var2 = JOptionPane.showInputDialog(null, "请输入新的个性签名。\n不得包含#或&,长度不得超过"+len); if(len < 13) break; } if(var2 != null) { send(var2, Integer.toString(ChessChannel.SET_SIGN)); textArea.append("签名设置成功!\n"); } } } @Override public void mouseClicked(MouseEvent e) { int xClick = e.getX(); int yClick = e.getY(); if(xClick > 550 && xClick < 730 && yClick > 180 && yClick < 300){ if(yClick > 258 && opponentID != null && opponentID.length()>4) send(opponentID,Integer.toString(ChessChannel.FIND_OPPONENT)); else if(yClick < 259 && yourID.length() > 4) send("",Integer.toString(ChessChannel.FIND_YOU)); } } @Override public void mousePressed(MouseEvent e) { if(isYou) { xOld = e.getX(); yOld = e.getY(); } } @Override public void mouseReleased(MouseEvent e) { if (Math.abs(e.getX() - xOld) < MOUSE_DISTANCE_LIMIT && Math.abs(e.getY() - yOld) < MOUSE_DISTANCE_LIMIT) { isPress = true; } mouseEvent(e, this); } @Override public void mouseEvent(MouseEvent e, PanelBase panel) { super.mouseEvent(e, panel); System.out.println("webpanel_mouseEvent ck: " + yourID +"的list:" + recordList); repaint(); } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } /** * 发送消息 * * @param message 信息 * @param targetID 目标ID */ void send(String message, String targetID) { send(targetID + LINE_SPLIT + message); } void send(Chess c1, Point p1, Chess c2, Point p2){ send(String.format("%c%d&%d%d&%d&%d%d",POSITION, c1.getID(), p1.x, p1.y, c2==null? 0:c2.getID(), p2==null? 9:p2.x, p2==null? 9:p2.y), opponentID); } /** * 最底层的发送消息,消息会被发送到服务器。 * * @param message 消息内容(String类型) */ public void send(String message) { sender.sendData(message); } public void send(char ch) { send(Character.toString(ch), opponentID); } /** * 发送坐标信息到对手的方法。 * * @param x * @param y * @param ID */ private void send(int x, int y, int ID) { x = reverseX(x); y = reverseY(y); send(String.format("%c%d%d%d",POSITION, x, y, ID), opponentID); } private void send(StringBuilder sb){ send(sb.toString(),opponentID); } /** * 将整数转化为编码字符,并组合成字符串。 * * @param info 需要转换为Character类型String的整数信息 * @return 由证书编码组合成的字符串 */ @Deprecated private String getStringFormat(int... info) { int len = info.length; char[] ches = new char[len]; for (int i = 0; i < len; i++) { ches[i] = (char) info[i]; } return new String(ches); } public void opponentAction(char beginner, String message) { System.out.println("webPanel_opponentAction_ck: web message" + message); beforeError(beginner, message); if (!isConnect) { switch (beginner) { case FIND_ONLINE: String[] options = message.split(SIGN_SPLIT); String str1 = (String) JOptionPane.showInputDialog(null, "当前在线:", "提示", JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (str1 != null && !str1.isEmpty()) { connect(str1.substring(0, str1.indexOf(LINE_SPLIT))); } break; case REJECT_CONNECT: JOptionPane.showMessageDialog(null, "对方拒绝了您的邀请,可能对方正在游戏。", "tips", JOptionPane.WARNING_MESSAGE); break; case ACCEPT_CONNECT://成功连接到对手 //格式:对手ID&对手名&头像名 int p = message.indexOf(SIGN_SPLIT_CHAR), p2 = message.indexOf(SIGN_SPLIT_CHAR, 1+p); this.opponentID = message.substring(0, p); this.opponentName = message.substring(++p, p2++); this.opponentHead = message.substring(p2); //todo //playerHint.setIcon(xxx); isConnect = true; isStart = false; isOver = false; send(ACCEPT_CONNECT + yourID + SIGN_SPLIT_CHAR + yourName + SIGN_SPLIT_CHAR + yourHead, opponentID); JOptionPane.showMessageDialog(null, "成功连接到【" + opponentName + "】\n(" + opponentID + ")"); break; case INVITE_CONNECT: String[] strs = message.split(SIGN_SPLIT); if (JOptionPane.showConfirmDialog(null, strs[1] + "(ID: " + strs[0] + ")想要与你建立连接,\n是否同意?", "test", JOptionPane.OK_CANCEL_OPTION, JOptionPane.INFORMATION_MESSAGE) == 0){ yourColor = -1; send(ACCEPT_CONNECT + yourID + SIGN_SPLIT + yourName + SIGN_SPLIT_CHAR+ yourHead, strs[0]); } break; case NO_PERSON_FOUND: JOptionPane.showMessageDialog(null, "账号输入错误。","error",0); break; case WRONG_PASSWARD: JOptionPane.showMessageDialog(null, "密码错误","Error",0); break; case REGIST: String strs2[] = message.split(LINE_SPLIT); yourID = strs2[0]; yourName = strs2[1]; yourHead = strs2[2]; JOptionPane.showMessageDialog(null,"欢迎" + yourName +"上线!","登陆成功",1); break; } } else { switch (beginner) { case POSITION://移动棋子或者吃棋子 position(message); System.out.println("接收成功!"); break; case SHENGBIAN: String[] sss = message.split(Character.toString(POSITION)); this.shengweiChessName = sss[0]; position(sss[1]); break; case LONG_CHANGE: Chess che2 = getChessFromPoint(new Point(7,0)), king2 = getChessFromPoint(new Point(3,0)); recordList.add(new Record(king2, che2, king2.getPoint(), che2.getPoint())); Point cheP2 = new Point(4,0), kingP2 = new Point(5,0); che2.setPoint(cheP2);//che king2.setPoint(kingP2);//wang this.swap(); oOX = cheP2.x;oOY = cheP2.y; oNX = kingP2.x; oNY = kingP2.y; break; case EMO_MES: opponentEmoThread.continuing(message); break; case APPLY_REGRET: //TODO int info = JOptionPane.showConfirmDialog(null, "对方请求悔棋,是否同意?", "悔棋请求", JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE); if(info == 0) { regret(); System.out.println("ck: 本方同意悔棋,要悔棋的棋子是:"); textArea.append("您同意了本次悔棋\n"); send(ACCEPT_REGRET); repaint(); } else send(REJECT_REGRET); break; case CHANGE_HEAD: opponentHead = message; break; case CHANGE_NAME: opponentName = message; break; case REJECT_REGRET: //TODO JOptionPane.showMessageDialog(null, "对方拒绝了您的悔棋申请。", "拒绝悔棋", JOptionPane.WARNING_MESSAGE); break; case INVITE_CONNECT: send(message + LINE_SPLIT + REJECT_CONNECT); break; case ACCEPT_REGRET: //todo regret(); textArea.append("对方同意了您的悔棋申请。\n"); repaint(); break; case SURREND: judger = yourColor; isOver = true; break; case PREPARE: isOpponentPrepare = true; if(isYouPrepare){ init(); creatChess(yourColor); if(yourColor != 1) for (Chess chess : chessList) chess.setPoint(new Point(reverseX(chess.getPoint().x), chess.getPoint().y)); isYou = yourColor == 1; isStart = true; isOver = false; }else JOptionPane.showMessageDialog(null, "对方已准备。\n点击准备按钮以开始游戏。", "提示", JOptionPane.INFORMATION_MESSAGE); break; case APPLY_PEACE: if(JOptionPane.showConfirmDialog(null, "对方申请求和,是否同意?", "求和申请", JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE)==0) { send(AGREE_PEACE); isOver = true; judger = 2; } else send(REJECT_PEACE); break; case AGREE_PEACE: JOptionPane.showMessageDialog(null, "求和成功。","求和", 1); isOver = true; judger = 2; // send("0");//发出和棋计算量 //todo break; case REJECT_PEACE: JOptionPane.showMessageDialog(null, "对方拒绝了您的求和申请。","求和", 1); break; case SEND_MESSAGE: textArea.append("【对手】: " + message + "\n"); break; case DISCONNECT: disconnect(); JOptionPane.showMessageDialog(null,"对方断开了连接","提示",2); break; case APPLY_SWAP: if(JOptionPane.showConfirmDialog(null, "对方申请交换颜色,是否同意?", "先后手交换申请", JOptionPane.YES_NO_OPTION, JOptionPane.INFORMATION_MESSAGE)==0) { send(AGREE_SWAP); yourColor = -yourColor; }else send(REJECT_SWAP); break; case AGREE_SWAP: JOptionPane.showMessageDialog(null,"对方同意了先后手交换申请。"); yourColor = -yourColor; break; case REJECT_SWAP: JOptionPane.showMessageDialog(null,"对方拒绝了您的先后手交换申请。"); break; } } repaint(); } private void disconnect(){ isConnect = false; opponentName = DEFAULT_NAME; opponentID = null; opponentHead = DEFAULT_HEAD; isYouPrepare = false; isOpponentPrepare = false; } private void beforeError(char beginner, String message) { switch (beginner) { case SUCCESS_SET_PASSWARD: JOptionPane.showMessageDialog(null, "成功修改了密码", "提示", JOptionPane.INFORMATION_MESSAGE); break; case SYSTEM_WINDOWS://系统提示 JOptionPane.showMessageDialog(null, printArray(message.split(SIGN_SPLIT)), "系统提示", JOptionPane.WARNING_MESSAGE); break; case SERVER_CLOSE: JOptionPane.showMessageDialog(null, "服务器即将关闭,请赶快退出!","警告", JOptionPane.WARNING_MESSAGE); break; case GET_ID: this.yourID = message; break; case ERROR: JOptionPane.showMessageDialog(null, "很抱歉,我们遇到了未知错误,\n请检查您的操作,或者重新启动游戏。", "错误", JOptionPane.ERROR_MESSAGE); break; case PLAYER_INFO: String[] strs = message.split(SIGN_SPLIT); StringBuilder var = new StringBuilder("ID: " + strs[0] + "\n昵称: " + strs[1]); for (int i = 2; i < strs.length; i++) { var.append("\n").append(strs[i]); } JOptionPane.showMessageDialog(null, var.toString(), "玩家信息", JOptionPane.INFORMATION_MESSAGE); break; case WebPanel.RESET_PASSWARD: String[] newPassward = message.split(SIGN_SPLIT); String ans = JOptionPane.showInputDialog(null, "回答你的密保问题:\n"+newPassward[0],"找回密码",1); if(ans != null){ if(ans.equals(newPassward[1])){ String newA = JOptionPane.showInputDialog(null,"请输入新密码。密码长度不能超过6,不得包含‘#’”&‘。","重设密码",1); if(newA != null && !newA.isEmpty()) send(newA, Integer.toString(ChessChannel.RESET_PASSWARD)); }else{ JOptionPane.showMessageDialog(null,"密保问题回答错误!","错误",2); } } break; case APPLY_ACCOUNT: JOptionPane.showMessageDialog(null,"成功申请到账号:" + message + "。\n初始密码为123456。请尽快登录。\n祝你好运。"); break; case GET_MONEY: moneyShop.showThis(Integer.parseInt(message)); break; case TO_SHENGWANG: shengwangShop.showThis(Integer.parseInt(message)); // JOptionPane.showOptionDialog(); break; } } public void resetStyle(Style style){ Chess.style = style; for(int i = 0; i < chessList.size();i++){ chessList.get(i).resetPath(); } System.out.println(Chess.style); // System.out.println(chessList.get(0).path); repaint(); } /** * 打印String类型数组的自定义方法。每个元素会提行,<b>但是结尾不会换行。</b> * * @param strs 要打印的String类型数组 * @return 字符串 * @throws IndexOutOfBoundsException String类型数组必须非空或者无长度 * @throws NullPointerException String类型数组没有分配地址。 */ private String printArray(String[] strs) { if (strs == null) throw new NullPointerException("数组不存在。"); if (strs.length < 1) throw new IndexOutOfBoundsException("数组长度不合法。"); String s = strs[0]; int len = strs.length; for (int i = 1; i < len; i++) { s = s + "\n" + strs[i];//2022/2/11/20:17,紧急。 } return s; } private void position(String message){ System.out.println("webPanel_opponentAction_ck: 移动开始"); oNX = message.charAt(0)-'0';oNY = message.charAt(1)-'0'; selectedChess = getChessFromID(Integer.parseInt(message.substring(2))); oOX = selectedChess.getPoint().x; oOY = selectedChess.getPoint().y; Point point = new Point(oNX,oNY); webProcessXY(point); if(judger == -yourColor) { try { Thread.sleep(25); } catch (InterruptedException e) { e.printStackTrace(); } send("-1"); } repaint(); } @Deprecated private void removeChess(Chess eatenChess) { // Chess chess = getChessFromPoint(new Point(x, y)); if ( eatenChess != null) { if(eatenChess.getID() == 9 || eatenChess.getID() == 10){ isOver = true; judger = -eatenChess.getColor(); } chessList.remove(eatenChess); } } public boolean isYou(){ return isYou; } public void setYourName(String name) { this.yourName = name; repaint(); send(10 + LINE_SPLIT + name); try { Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } if(isConnect) send(CHANGE_NAME + name, opponentID); } public void connect() { send("98");//查询有没有人,其实这个方法应该叫做“查询在线人数” } private void connect(String targetID) { opponentID = targetID; yourColor = 1; send(INVITE_CONNECT + yourID + SIGN_SPLIT_CHAR + yourName, targetID);//真实邀请进行连接 } @Deprecated public void rejectConnect(String message) { send(REJECT_CONNECT + "", message); } public void surrend() { if(isStart && !isOver) { send(SURREND); judger = -yourColor; isOver = true; repaint(); } } @Override protected void moveChess(Point point) { try { super.moveChess(point); }catch (NullPointerException e){ e.printStackTrace(); } messageBuilder.append(POSITION).append(reverseX(point.x)).append(reverseY(point.y)).append(selectedChess.getID()); send(messageBuilder); messageBuilder.setLength(0); // send(point.x, point.y, selectedChess.getID()); // flagEvent(point.x, point.y); swap();//交换对手 System.out.println("ck moveChess"); } @Override protected void shengweiMessage(){ while (shengweiChessName == null) { shengweiChessName = (String) JOptionPane.showInputDialog(null, "请选择升位棋子", "兵升变", JOptionPane.QUESTION_MESSAGE, null, shengweis, shengweis[0]); } recordList.get(recordList.size()-1).setShengweiInfo(shengweiChessName.equals(shengweis[0]) ? 0 : (shengweiChessName.equals(shengweis[1]) ? 1 : (shengweiChessName.equals(shengweis[2]) ? 2 : 3))); selectedChess.shengWei(shengweiChessName); System.out.println("升位检测-before:" + shengweiChessName); if(isYou) messageBuilder.append(SHENGBIAN).append(shengweiChessName); shengweiChessName = null; System.out.println("升位检测-after:" + shengweiChessName); } @Override protected void flagEvent(int x, int y){ System.out.println("start this method"); if(selectedChess == null) System.out.println("selectedChess is null!"); // if(point == null) System.out.println("the point is null"); if(!flag) { send(selectedChess, new Point(x,y), null, null); System.out.println("send successfully!!!"); } // else{ // Chess chess = recordList.get(recordList.size()-1).getCurrentChess(); // Chess eChess = recordList.get(recordList.size()-1).getEatenChess(); // chess.setPoint(aCurrentPoint); // if(eChess == null) { // recordList.get(recordList.size() - 1).setEatenChess(targetChess); // chessList.remove(targetChess); // } // this.flag = false; // send(String.format("%c%d&%d%d&%d&%d%d",EAT_PAWN,chess.getID(),chess.getPoint().x,chess.getPoint().y,targetChess.getID(),targetChess.getPoint().x, targetChess.getPoint().y), opponentID); // } System.out.println("OverThisMethod"); } private void webProcessXY(Point point){ Chess c = getChessFromPoint(point); if (c != null) super.eatChess(point, c); else super.moveChess(point); swap(); } @Override protected void eatChess(Point point, Chess eatenChess) { // send(point.x, point.y, selectedChess.getID()); super.eatChess(point, eatenChess); messageBuilder.append(POSITION).append(reverseX(point.x)).append(reverseY(point.y)).append(selectedChess.getID()); send(messageBuilder); messageBuilder.setLength(0); System.out.println("ck eatChess"); swap();//交换对手 } @Override public void swap() { System.out.println(this.yourID + "ck swap(): " + (currentPlayer == 1? "red":"black")); super.swap(); isYou = !isYou; } // @Override // public void keyTyped(KeyEvent e) { // // } // // @Override // public void keyPressed(KeyEvent e) { // //大招E和A技能 // } // // @Override // public void keyReleased(KeyEvent e) { // // } @Deprecated @Override public void shortExchange(Point point, Chess c){ Point cheP = new Point(4,7), kingP = new Point(6,7); if(selectedChess != null && selectedChess.canMove(point, this)){ //todo recordList.add(new Record(selectedChess, c, selectedChess.getPoint(), c.getPoint())); c.setPoint(cheP);//che selectedChess.setPoint(kingP);//wang swap(); send(SHENGBIAN); } } @Deprecated private void myShortChange(Point cp, Point kp, Chess c){ c.setPoint(cp);//che selectedChess.setPoint(kp);//wang swap(); } @Deprecated @Override public void longExchange(Point point, Chess c){ Point cheP = new Point(3,7), kingP = new Point(1,7); if(selectedChess != null && selectedChess.canMove(point, this)){ //todo recordList.add(new Record(selectedChess, c, selectedChess.getPoint(), c.getPoint())); c.setPoint(cheP);//che selectedChess.setPoint(kingP);//wang send(LONG_CHANGE); swap(); } } @Override public void keyTyped(KeyEvent e) { } @Override public void keyPressed(KeyEvent e) { } @Override public void keyReleased(KeyEvent e) { } private JButton setButtons(String name, String cmd){ JButton button = new JButton(name); button.addActionListener(this); button.setActionCommand(cmd); this.add(button); return button; } public boolean isRegiserd(){ return yourID.length() > 4; } public void setYourHead(String head){ this.yourHead = head; if(isConnect) send(CHANGE_HEAD + head, opponentID); try { Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } repaint(); } public void sendMessage(String mess){ send(SEND_MESSAGE + mess, opponentID); textArea.append("【你】: "+ mess + "\n"); } private JButton setButton(String name, String cmd){ JButton button = new JButton(name); button.addActionListener(this); button.setActionCommand(cmd); return button; } public void startDrawYourEmo(String var){ if(isConnect) send(EMO_MES + var, opponentID); yourEmo = var; repaint(); } public void startDrawOpponentEmo(String var){ opponentEmo = var; repaint(); } public void endDrawYourEmo(){ yourEmo = null; repaint(); } public void endDrawOpponentEmo(){ opponentEmo = null; repaint(); } @Override public void exchange(Point point, Chess c){ recordList.add(new Record(selectedChess, c, selectedChess.getPoint(), c.getPoint(), point.x, point.y)); c.setPoint(new Point((selectedChess.getPoint().x+point.x)/2, point.y)); // selectedChess.setPoint(point); } }
Ethylene9160/Chess
src/chess/panels/WebPanel.java
66,347
package mca_08_dp; public class Code05_CardsInLine { public static int getWinnerScore(int[] arr) { int xian = xian(arr, 0, arr.length - 1); int hou = hou(arr, 0, arr.length - 1); return Math.max(xian, hou); } // 目前,是在arr[L...R]这个范围上玩牌! // 返回,先手最终的最大得分 public static int xian(int[] arr, int L, int R) { if (L == R) { return arr[L]; } if (L == R - 1) { return Math.max(arr[L], arr[R]); } // L...R上,不止两张牌! // 可能性1:拿走L位置的牌 int p1 = arr[L] + hou(arr, L + 1, R); // 可能性2:拿走R位置的牌 int p2 = arr[R] + hou(arr, L, R - 1); return Math.max(p1, p2); } // 目前,是在arr[L...R]这个范围上玩牌! // 返回,后手最终的最大得分 public static int hou(int[] arr, int L, int R) { if (L == R) { return 0; } if (L == R - 1) { return Math.min(arr[L], arr[R]); } // L..R上,不止两张牌 // 后手! // 可能性1:对手,先手,拿走L位置的牌,接下来!你就可以在L+1..R上先手了! int p1 = xian(arr, L + 1, R); // 可能性2:对手,先手,拿走R位置的牌,接下来!你就可以在L..R-1上先手了! int p2 = xian(arr, L, R - 1); return Math.min(p1, p2); } public static int getWinnerScore2(int[] arr) { int n = arr.length; int[][] dpxian = new int[n][n]; int[][] dphou = new int[n][n]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { dpxian[i][j] = -1; dphou[i][j] = -1; } } int xian = xian2(arr, 0, arr.length - 1, dpxian, dphou); int hou = hou2(arr, 0, arr.length - 1, dpxian, dphou); return Math.max(xian, hou); } public static int xian2(int[] arr, int L, int R, int[][] dpxian, int[][] dphou) { if (dpxian[L][R] != -1) { return dpxian[L][R]; } int ans = 0; if (L == R) { ans = arr[L]; } else if (L == R - 1) { ans = Math.max(arr[L], arr[R]); } else { int p1 = arr[L] + hou2(arr, L + 1, R, dpxian, dphou); int p2 = arr[R] + hou2(arr, L, R - 1, dpxian, dphou); ans = Math.max(p1, p2); } dpxian[L][R] = ans; return ans; } public static int hou2(int[] arr, int L, int R, int[][] dpxian, int[][] dphou) { if (dphou[L][R] != -1) { return dphou[L][R]; } int ans = 0; if (L == R) { ans = 0; } else if (L == R - 1) { ans = Math.min(arr[L], arr[R]); } else { int p1 = xian2(arr, L + 1, R, dpxian, dphou); int p2 = xian2(arr, L, R - 1, dpxian, dphou); ans = Math.min(p1, p2); } dphou[L][R] = ans; return ans; } // // 根据规则,返回获胜者的分数 // public static int win1(int[] arr) { // if (arr == null || arr.length == 0) { // return 0; // } // int first = f1(arr, 0, arr.length - 1); // int second = g1(arr, 0, arr.length - 1); // return Math.max(first, second); // } // // // arr[L..R],先手获得的最好分数返回 // public static int f1(int[] arr, int L, int R) { // if (L == R) { // return arr[L]; // } // int p1 = arr[L] + g1(arr, L + 1, R); // int p2 = arr[R] + g1(arr, L, R - 1); // return Math.max(p1, p2); // } // // // // arr[L..R],后手获得的最好分数返回 // public static int g1(int[] arr, int L, int R) { // if (L == R) { // return 0; // } // int p1 = f1(arr, L + 1, R); // 对手拿走了L位置的数 // int p2 = f1(arr, L, R - 1); // 对手拿走了R位置的数 // return Math.min(p1, p2); // } // // public static int win2(int[] arr) { // if (arr == null || arr.length == 0) { // return 0; // } // int N = arr.length; // int[][] fmap = new int[N][N]; // int[][] gmap = new int[N][N]; // for (int i = 0; i < N; i++) { // for (int j = 0; j < N; j++) { // fmap[i][j] = -1; // gmap[i][j] = -1; // } // } // int first = f2(arr, 0, arr.length - 1, fmap, gmap); // int second = g2(arr, 0, arr.length - 1, fmap, gmap); // return Math.max(first, second); // } // // // arr[L..R],先手获得的最好分数返回 // public static int f2(int[] arr, int L, int R, int[][] fmap, int[][] gmap) { // if (fmap[L][R] != -1) { // return fmap[L][R]; // } // int ans = 0; // if (L == R) { // ans = arr[L]; // } else { // int p1 = arr[L] + g2(arr, L + 1, R, fmap, gmap); // int p2 = arr[R] + g2(arr, L, R - 1, fmap, gmap); // ans = Math.max(p1, p2); // } // fmap[L][R] = ans; // return ans; // } // // // // arr[L..R],后手获得的最好分数返回 // public static int g2(int[] arr, int L, int R, int[][] fmap, int[][] gmap) { // if (gmap[L][R] != -1) { // return gmap[L][R]; // } // int ans = 0; // if (L != R) { // int p1 = f2(arr, L + 1, R, fmap, gmap); // 对手拿走了L位置的数 // int p2 = f2(arr, L, R - 1, fmap, gmap); // 对手拿走了R位置的数 // ans = Math.min(p1, p2); // } // gmap[L][R] = ans; // return ans; // } // // public static int win3(int[] arr) { // if (arr == null || arr.length == 0) { // return 0; // } // int N = arr.length; // int[][] fmap = new int[N][N]; // int[][] gmap = new int[N][N]; // for (int i = 0; i < N; i++) { // fmap[i][i] = arr[i]; // } // for (int startCol = 1; startCol < N; startCol++) { // int L = 0; // int R = startCol; // while (R < N) { // fmap[L][R] = Math.max(arr[L] + gmap[L + 1][R], arr[R] + gmap[L][R - 1]); // gmap[L][R] = Math.min(fmap[L + 1][R], fmap[L][R - 1]); // L++; // R++; // } // } // return Math.max(fmap[0][N - 1], gmap[0][N - 1]); // } public static void main(String[] args) { int[] arr = { 5, 7, 4, 5, 8, 1, 6, 0, 3, 4, 6, 1, 7 }; System.out.println(getWinnerScore(arr)); System.out.println(getWinnerScore2(arr)); } }
algorithmzuo/mca-algorithm-problems
第01期/mca_08_dp/Code05_CardsInLine.java
66,348
package data.player; import java.util.Hashtable; import java.util.Set; import po.Player_AllScorePO; import po.Player_AverageScorePO; import po.Player_BasicInfoPO; /** * * @author wyt * @category 测试球员数据部分 * */ public class getPlayerData_Drive { public static void main(String args[]){ PlayerData pd=new PlayerData_Impl(); Hashtable<String,Player_AverageScorePO> vt=new Hashtable<String,Player_AverageScorePO>(); Hashtable<String,Player_BasicInfoPO> bt=new Hashtable<String,Player_BasicInfoPO>(); bt=pd.getPlayerBasic(); vt=pd.getPlayerAverage(); Hashtable<String,Player_AllScorePO> at=pd.getPlayerAll(); Set<String>keys1=at.keySet(); for(String key:keys1){ System.out.println(key); Player_AllScorePO playerAll=at.get(key); double nums[]=playerAll.getScoresAll(); double teamNums[]=playerAll.getTeamAll(); double competeNums[]=playerAll.getCompeteAll(); //输出球员的总数据 System.out.println("总参赛场数"+playerAll.getNumOfMatches()); System.out.println("总先发场数"+playerAll.getNumOfFirstMatches()); System.out.println("队伍"+playerAll.getTeam()); System.out.println("联盟"+playerAll.getTeamArea()); System.out.println("总上场时间"+playerAll.getTimeAll()); System.out.println("球队总时间"+playerAll.getTimeTeam()); System.out.println(); for(int i=0;i<15;i++){ System.out.println("个人"+nums[i]); } System.out.println(); for(int i=0;i<teamNums.length;i++){ System.out.println("球队"+teamNums[i]); } System.out.println(); for(int i=0;i<competeNums.length;i++){ System.out.println("对手"+competeNums[i]); } Player_BasicInfoPO pbip=bt.get(key); String strs[]=pbip.getBasicInfo(); for(int i=0;i<strs.length;i++){ System.out.println(strs[i]); //TODO //输出球员的基本信息 } Player_AverageScorePO playerAver=vt.get(key); double ss[]=playerAver.getScoresAverage(); //输出平均数据 String s=playerAver.getTimeAver(); System.out.println(s); for(int i=0;i<ss.length;i++){ System.out.println(ss[i]); } } } }
TestSENJU/shot
NJUSENBA/src/main/java/data/player/getPlayerData_Drive.java
66,349
package excel.struct; import com.teamtop.util.excel.ExcelJsonUtils; /** * K_767跨服试炼-战斗表.xlsx */ public class Struct_slzd_767 { /**id * 战斗层id*/ private int id; /**普通奖励试炼点*/ private int ptsld; /**普通奖励试炼券*/ private int[][] ptslq; /**困难奖励试炼点*/ private int knsld; /**困难奖励试炼券*/ private int[][] knslq; /**噩梦奖励试炼点*/ private int emsld; /**噩梦奖励试炼券*/ private int[][] emslq; /**普通战力区间 * [[a,b]],a,为十万分比 * 最后确定的战力区间为 * a*基础参数X<对手<b*基础参数X * * 基础参数读取系统常数表*/ private int[][] ptqj; /**困难战力区间 * [[a,b]],a,为十万分比 * 最后确定的战力区间为 * a*基础参数X<对手<b*基础参数X*/ private int[][] knqj; /**噩梦战力区间*/ private int[][] emqj; /**战斗地图*/ private int dt; /** * id * 战斗层id */ public int getId() { return id; } /** * 普通奖励试炼点 */ public int getPtsld() { return ptsld; } /** * 普通奖励试炼券 */ public int[][] getPtslq() { return ptslq; } /** * 困难奖励试炼点 */ public int getKnsld() { return knsld; } /** * 困难奖励试炼券 */ public int[][] getKnslq() { return knslq; } /** * 噩梦奖励试炼点 */ public int getEmsld() { return emsld; } /** * 噩梦奖励试炼券 */ public int[][] getEmslq() { return emslq; } /** * 普通战力区间 * [[a,b]],a,为十万分比 * 最后确定的战力区间为 * a*基础参数X<对手<b*基础参数X * * 基础参数读取系统常数表 */ public int[][] getPtqj() { return ptqj; } /** * 困难战力区间 * [[a,b]],a,为十万分比 * 最后确定的战力区间为 * a*基础参数X<对手<b*基础参数X */ public int[][] getKnqj() { return knqj; } /** * 噩梦战力区间 */ public int[][] getEmqj() { return emqj; } /** * 战斗地图 */ public int getDt() { return dt; } public Struct_slzd_767(int id,int ptsld,String ptslq,int knsld,String knslq,int emsld,String emslq,String ptqj,String knqj,String emqj,int dt) { this.id = id; this.ptsld = ptsld; this.ptslq = ExcelJsonUtils.toObj(ptslq,int[][].class); this.knsld = knsld; this.knslq = ExcelJsonUtils.toObj(knslq,int[][].class); this.emsld = emsld; this.emslq = ExcelJsonUtils.toObj(emslq,int[][].class); this.ptqj = ExcelJsonUtils.toObj(ptqj,int[][].class); this.knqj = ExcelJsonUtils.toObj(knqj,int[][].class); this.emqj = ExcelJsonUtils.toObj(emqj,int[][].class); this.dt = dt; } }
SunFjn/jjdzy
server/src/excel/struct/Struct_slzd_767.java
66,350
package 牛客网; import java.util.Arrays; import java.util.Scanner; /** * 游戏里面,队伍通过匹配实力相近的对手进行对战。但是如果匹配的队伍实力相差太大,对于双方游戏体验都不会太好。 * 给定n个队伍的实力值,对其进行两两实力匹配,两支队伍实例差距在允许的最大差距d内,则可以匹配。 * 要求在匹配队伍最多的情况下匹配出的各组实力差距的总和最小。 * 输入描述 * * 第一行,n,d。队伍个数n。允许的最大实力差距d。 * 2 <= n <= 50 * 0 <= d <= 100 * * 输出描述 * * 匹配后,各组对战的实力差值的总和。若没有队伍可以匹配,则输出-1。 * * 输入: * 6 30 * 81 87 47 59 81 18 * * 输出: * 57 */ public class 最佳对手 { public static void main(String[] args) { Scanner sc = new Scanner(System.in); /*队伍数*/ int n = sc.nextInt(); /*实力允许的最大差距*/ int d = sc.nextInt(); int[] arr = new int[n]; for (int i = 0; i < n; i++) { arr[i] = sc.nextInt(); } System.out.println(getResult(n, d, arr)); } public static int getResult(int n, int d, int[] arr) { /*排序*/ Arrays.sort(arr); int odd_count = 0; int odd_total = 0; int even_count = 0; int even_total = 0; boolean flag = true; for (int i = 1; i < n; i++) { int diff = arr[i] - arr[i - 1]; /*差距在范围内*/ if (diff <= d) { flag = false; /*分别统计偶数和奇数,分别求和*/ if (i % 2 == 0) { odd_count++; odd_total += diff; } else { even_count++; even_total += diff; } } } /*差距太大,无法匹配,返回-1*/ if (flag) { return -1; } /*在匹配队伍最多的情况下匹配出的各组实力差距的总和最小*/ if (odd_count > even_count) { return odd_total; } if (odd_count < even_count) { return even_total; } return Math.min(odd_total, even_total); } }
shenchunxing/data-structures-and-algorithms
src/牛客网/最佳对手.java
66,351
package pkserver; import com.alibaba.fastjson.JSONObject; import dao.UserDao; import dao.impl.UserDaoImpl; import enums.Difficulty; import enums.SocketMsgInf; import pkserver.threads.TimeLimitThread; import pojo.po.db.User; import pojo.po.pk.AnswerStatus; import pojo.po.pk.AnswersRecord; import pojo.po.pk.UserHp; import pojo.vo.MatchInf; import pojo.vo.SocketMessage; import tools.easydao.utils.Resources; import tools.utils.ResponseUtil; import tools.utils.StringUtil; import java.io.IOException; import java.io.InputStream; import java.util.*; /** * Pk房间 * 房间用于处理比赛信息 * 双方血量的记录 * 胜负的判断 * * @author yeyeye * @Date 2022/10/20 15:07 */ public class PkRoom { /** * 延迟秒数 */ private static final int DELAY = 4; private int playerNum; /** * 玩家一 */ private PkUser player01; /** * 玩家二 */ private PkUser player02; /** * 两个玩家的血条 */ private final Map<PkUser, Double> hpMap = new HashMap<>(); // /** // * 记录双方答题结果 // */ // private final Map<PkUser, AnswersRecord> answersRecords = new HashMap<>(); /** * 挖空数 */ private int blankNum; /** * 时长限制 */ private long timeLimits; /** * 即将关闭 */ boolean willClose = false; /** * 房间对外响应消息封装 */ private SocketMessage responseMessage; private final Thread timer = new Thread(new TimeLimitThread(this)); public void startTimer() { this.timer.start(); } public boolean isTimerAlive() { return timer.isAlive(); } private PkRoom() { } /** * 开房间 * * @param player01 玩家一 * @param player02 玩家二 */ public PkRoom(PkUser player01, PkUser player02) { this.player01 = player01; this.player02 = player02; playerNum = 2; //获取双方匹配信息 MatchInf p1Inf = player01.getMatchInf(); MatchInf p2Inf = player02.getMatchInf(); //初始化双方血量 hpMap.put(player01, 100.0); hpMap.put(player02, 100.0); //获取双方文章字数 int p1ModleNum = p1Inf.getModleNum(); System.out.println("p1模板字数:" + p1ModleNum); int p2ModleNum = p2Inf.getModleNum(); System.out.println("p2模板字数:" + p2ModleNum); //获取双方挖空数 //获取难度,因为匹配双方的难度都是一样的所以只用获取p1的就可以 double ratio = p1Inf.getDifficulty().getRatio(); int p1BlankNum = StringUtil.getBlankNumByContentLength(p1ModleNum, ratio); int p2BlankNum = StringUtil.getBlankNumByContentLength(p2ModleNum, ratio); //获取两人挖空数的最小值 //保存该房间挖空数 this.blankNum = Math.min(p1BlankNum, p2BlankNum); if (this.blankNum <= 0) { blankNum = 1; } System.out.println("房间:" + this + " 挖空数为:" + this.blankNum); // // <div> // String matchStr = "</div>"; // String content = p1Inf.getContent(); // this.blankNum = StringUtil.subStrCount(content, matchStr); //根据难度和挖空数记录总时长 //各个难度所对应每个空的时间不一样,先写死后续再优化!!!!!! //10s(easy),15s(normal),20s(hard) //根据难度获取每个空需要的时间 int blankTimeLimits = p1Inf.getDifficulty().getTimeLimits(); //设置该房间总时间限制 this.timeLimits = (long) this.blankNum * blankTimeLimits + DELAY; //初始化answers集合 //初始化玩家1战绩集合 AnswersRecord answersRecord01 = new AnswersRecord(); //设置ID answersRecord01.setUserId(getPlayer01().getMatchInf().getUserId()); //初始化玩家2战绩集合 AnswersRecord answersRecord02 = new AnswersRecord(); //设置ID answersRecord02.setUserId(getPlayer02().getMatchInf().getUserId()); // //添加进总记录集合 // answersRecords.put(this.player01, answersRecord01); // answersRecords.put(this.player02, answersRecord02); //输出日志 System.out.println(p1Inf.getUserId() + " and " + p2Inf.getUserId() + "create pk room"); } /** * 开始本房间比赛 */ public synchronized void excute(String json, PkUser curUser) { System.out.println(this + " pk room excute: " + json); //获取json数据 JSONObject jsonObject = JSONObject.parseObject(json); if (jsonObject != null) { //处理Json数据 //{"answerName":"1111","answerValue":true} if (player01.isAlive() && player02.isAlive()) { //如果是正常对局,两人都没有退出,就响应血量 boolean isRight = (Boolean) jsonObject.get("answerValue"); if (isRight) { //如果是对的则需要扣对手的血量 PkUser enemy = getEnemy(curUser); //获取敌人当前血量 double hp = getHp(enemy); //计算扣的血 hp -= Math.round(100.0 / this.blankNum); //设置血量 if (hp < 0) { hp = 0; } setHp(enemy, hp); } //检查双方输赢状态 boolean isContinue = true; if (getHp(curUser) <= 0 || getHp(getEnemy(curUser)) <= 0) { //有一边没血了 //并且比赛是正常进行的,没有一方退出游戏 //结束比赛 isContinue = false; } //将双方血量响应回去 SocketMessage msg = new SocketMessage(); List<UserHp> hpLists = new ArrayList<>(); hpLists.add(new UserHp(this.player01.getMatchInf().getToken(), getHp(this.player01))); hpLists.add(new UserHp(this.player02.getMatchInf().getToken(), getHp(this.player02))); msg.addData("hpInf", hpLists); roomBroadcast(msg); if (!isContinue) { //比赛结束 this.end(); } } } else { this.responseMessage = new SocketMessage(SocketMsgInf.JSON_ERROR); } } /** * 重复挖空 * * @param player 需要重复挖空的用户 * @return 挖好的内容 */ public synchronized SocketMessage againDig(PkUser player) { SocketMessage msg; if (player == player01 || player == player02) { //验证该用户是否合法 //为需要循环挖空的玩家挖空 String content = player.getMatchInf().getContent(); String handledContent = StringUtil.digBlank(content, this.blankNum); msg = new SocketMessage(SocketMsgInf.OPERATE_SUCCESS); msg.addData("digedContent", handledContent); } else { //用户不存在该房间内 //非法请求 msg = new SocketMessage(SocketMsgInf.SERVER_ERROR); } return msg; } /** * 结束本房间游戏 */ public synchronized void end() { System.out.println(this + " pk room closed "); //将输赢信息封装 roomBroadcast(new SocketMessage(SocketMsgInf.MATCH_END)); SocketMessage result = getWinner(); roomBroadcast(result); //结束游戏,并关闭房间 try { if (player01.isAlive()) { this.player01.getStatusPool().quitMatchedPool(player01); player01.getSession().close(); } if (player02.isAlive()) { this.player01.getStatusPool().quitMatchedPool(player02); player02.getSession().close(); } //移除池中相关信息 StatusPool.PK_ROOM_LIST.remove(this); } catch (IOException e) { e.printStackTrace(); } } // /** // * 保存用户答案记录 // * // * @param player 用户 // * @param answerStatus 封装的答案信息 // */ // private void saveRecord(PkUser player, AnswerStatus answerStatus) { // AnswersRecord answersRecord = answersRecords.get(player); // List<AnswerStatus> list = answersRecord.getAnswersRecord(); // list.add(answerStatus); // } /** * 房间广播 * * @param msg msg */ private void roomBroadcast(SocketMessage msg) { //给房间内两位玩家发送结果 try { if (player01.getSession().isOpen()) { ResponseUtil.send(player01.getSession(), msg); } if (player02.getSession().isOpen()) { ResponseUtil.send(player02.getSession(), msg); } } catch (IOException e) { e.printStackTrace(); } } /** * 获取赢家 */ private SocketMessage getWinner() { PkUser winner; PkUser loser; if (player01.isAlive() && player02.isAlive()) { double player01Hp = getHp(player01); double player02Hp = getHp(player02); //如果两位玩家都没有退 if (player01Hp < player02Hp) { //玩家2赢 winner = player02; loser = player01; } else if (player02Hp < player01Hp) { //玩家1赢 winner = player01; loser = player02; } else { //平局 winner = loser = null; } } else if (player01.isAlive() || player02.isAlive()) { //有一位玩家没退 //没退的始终获胜 winner = (player01.isAlive() ? player01 : player02); loser = (!player01.isAlive() ? player01 : player02); } else { //全退了 //平局 winner = loser = null; } if (winner != null && loser != null) { updateRank(winner.getMatchInf().getUserId(), true); updateRank(loser.getMatchInf().getUserId(), false); } SocketMessage msg = new SocketMessage(); //封装赢者数据 msg.addData("winnerId", (winner == null ? "-1" : winner.getMatchInf().getToken())); // //封装双方战绩 // List<AnswersRecord> answersRecordList = new ArrayList<>(); // answersRecordList.add(answersRecords.get(player01)); // answersRecordList.add(answersRecords.get(player02)); // msg.addData("records", answersRecordList); this.willClose = true; return msg; } /** * 获取段位信息 * 只会读取所以使用普通HashMap即可 */ private static final Map<String, Integer> RANK_INFOS = new HashMap<>(); static { InputStream input = Resources.getResourceAsStream("rankInfos.properties"); try { Properties properties = new Properties(); properties.load(input); String stars = (String) properties.get("stars"); String easyPoint = (String) properties.get("easyPoint"); String normalPoint = (String) properties.get("normalPoint"); String difficultPoint = (String) properties.get("difficultPoint"); String maxPoints = (String) properties.get("maxPoints"); RANK_INFOS.put("stars", Integer.parseInt(stars)); RANK_INFOS.put("easyPoint", Integer.parseInt(easyPoint)); RANK_INFOS.put("normalPoint", Integer.parseInt(normalPoint)); RANK_INFOS.put("difficultPoint", Integer.parseInt(difficultPoint)); RANK_INFOS.put("maxPoints", Integer.parseInt(maxPoints)); } catch (IOException e) { throw new RuntimeException("读取段位配置信息失败"); } } private final UserDao userDao = new UserDaoImpl(); /** * 更新段位 */ private void updateRank(int userId, boolean isWin) { User user = userDao.selectUserById(userId); int userStars = user.getStars(); Integer stars = RANK_INFOS.get("stars"); //首先处理积分 int userPoints = user.getPoints(); Difficulty difficulty = this.player01.getMatchInf().getDifficulty();//easy //根据难度获取不同的积分加成 Integer basicPoints; if (difficulty == Difficulty.EASY) { basicPoints = RANK_INFOS.get("easyPoint"); } else if (difficulty == Difficulty.NORMAL) { basicPoints = RANK_INFOS.get("normalPoint"); } else { basicPoints = RANK_INFOS.get("difficultPoint"); } //计算总积分积分 int totalPoints = (userPoints + basicPoints) * ((isWin ? 1 : 0) * 2); //计算根据积分需要额外增加的星星数量 Integer maxPoints = RANK_INFOS.get("maxPoints"); int extraStars = totalPoints / maxPoints; totalPoints -= extraStars * maxPoints; //计算当前可用星星数量 userStars += extraStars; int totalStars = 0; if (isWin) { //成功了 //增加星星数量和积分数量 //星星数量 = 初始星星数 + 获胜获得星星数 + 积分额外星星数 totalStars = userStars + stars; } else if (userStars - stars >= 0) { //失败了扣星星 //如果还有星星可以扣 totalStars = userStars - stars; } else { System.out.println("没有星星扣了"); } //更新用户星星和积分 int i = userDao.updateStarsByUserId(userId, totalStars); i = userDao.updatePointByUserId(userId, totalPoints); if (i > 0) { System.out.println("更新 " + userId + " 星星和积分数量成功"); } else { System.out.println("更新 " + userId + " 星星和积分数量失败"); } } /** * 判断该房间内是否存在该玩家 * * @param player 玩家 * @return bool值 */ private boolean containPlayer(PkUser player) { return player01 == player || player02 == player; } /** * 获取当前玩家的对手 * * @param player 当前玩家 * @return 对手 */ private PkUser getEnemy(PkUser player) { if (player.equals(player01)) { return player02; } else { return player01; } } private double getHp(PkUser player) { return hpMap.get(player); } /** * 设置用户血量 * * @param player 用户 */ private void setHp(PkUser player, double hp) { this.hpMap.put(player, hp); } /** * 加入房间 * * @param curPlayer 用户 */ public synchronized static void joinRoom(PkUser curPlayer) { //遍历房间列表房间里是否存在当前用户或他的对手 List<PkRoom> pkRoomList = StatusPool.PK_ROOM_LIST; boolean findSuccess = false; for (PkRoom pkRoom : pkRoomList) { if (pkRoom.containPlayer(curPlayer)) { //找到玩家所在房间 findSuccess = true; break; } } if (!findSuccess) { //没找到则创建房间,并把他们两个都扔进去 //获取对手对象 Map<PkUser, PkUser> matchedPool = StatusPool.MATCHED_POOL; PkUser enemy = matchedPool.get(curPlayer); if (enemy != null) { //将自己和对手创建房间并添加进房间列表中 PkRoom pkRoom = new PkRoom(curPlayer, enemy); pkRoomList.add(pkRoom); enemy.setPkRoom(pkRoom); curPlayer.setPkRoom(pkRoom); } else { throw new RuntimeException("创建房间失败"); } } } public PkUser getPlayer01() { return player01; } public PkUser getPlayer02() { return player02; } public int getBlankNum() { return blankNum; } public long getTimeLimits() { return timeLimits; } public int getPlayerNum() { return playerNum; } public void setPlayerNum(int playerNum) { this.playerNum = playerNum; } }
NopeDl/ReciteMemory
src/main/java/pkserver/PkRoom.java
66,353
package top.codecafe.activity; import android.app.Application; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.MenuItem; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.ActionBar; import com.google.android.material.appbar.CollapsingToolbarLayout; import com.kymjs.base.backactivity.BaseBackActivity; import top.codecafe.R; import top.codecafe.delegate.BlogDetailDelegate; import top.codecafe.utils.LinkDispatcher; import top.codecafe.utils.Tools; /** * 对手机页面做了适配的网站 * * @author kymjs (https://kymjs.com/) on 12/5/15. */ public class MobelBrowserActivity extends BaseBackActivity<BlogDetailDelegate> { public static final String KEY_BLOG_URL = "blog_url_key"; public static final String KEY_BLOG_TITLE = "blog_title_key"; private String title; @Override protected Class<BlogDetailDelegate> getDelegateClass() { return BlogDetailDelegate.class; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = getIntent(); String url = intent.getStringExtra(KEY_BLOG_URL); title = intent.getStringExtra(KEY_BLOG_TITLE); CollapsingToolbarLayout collapsingToolbar = viewDelegate.get(R.id.collapsing_toolbar); title = LinkDispatcher.getActionTitle(url, title); if (title != null) { collapsingToolbar.setTitle(title); } else { collapsingToolbar.setTitle(getString(R.string.app_name)); } viewDelegate.setContentUrl(url); } @Override protected void initToolbar() { super.initToolbar(); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); } } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { finish(); return true; } if (item.getItemId() == R.id.action_share && viewDelegate != null && viewDelegate.getWebView() != null) { Tools.shareUrl(this, title, viewDelegate.getWebView().getUrl()); return true; } return super.onOptionsItemSelected(item); } /** * 跳转到博客详情界面 * * @param url 传递要显示的博客的地址 * @param title 传递要显示的博客的标题 */ public static void goinActivity(Context cxt, @NonNull String url, @Nullable String title) { Intent intent = new Intent(cxt, MobelBrowserActivity.class); intent.putExtra(KEY_BLOG_URL, url); intent.putExtra(KEY_BLOG_TITLE, title); if (cxt instanceof Application) { intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); } cxt.startActivity(intent); } }
kymjs/CodeCafe
app/src/main/java/top/codecafe/activity/MobelBrowserActivity.java
66,355
package presentation.player; import java.awt.Color; import java.awt.Cursor; import java.awt.Dimension; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionListener; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Vector; import javax.swing.JCheckBox; import javax.swing.JTable; import javax.swing.UIManager; import javax.swing.UIManager.LookAndFeelInfo; import javax.swing.table.DefaultTableCellRenderer; import presentation.component.BgPanel; import presentation.component.StyleScrollPane; import presentation.component.StyleTable; import presentation.contenui.TurnController; import presentation.contenui.UIUtil; import presentation.mainui.StartUI; import bussinesslogic.match.MatchLogic; import data.po.MatchDataPO; import data.po.Match_PlayerPO; import data.po.PlayerDataPO; public class PlayerMatch extends BgPanel{ private static final long serialVersionUID = 1L; private PlayerDataPO po; private StyleTable basicTable, pgTable; private StyleScrollPane basicSP, pgSP; private JCheckBox checkBox1, checkBox2; private MatchLogic matchLogic = new MatchLogic(); private ArrayList<Match_PlayerPO> match_PlayerPOs = new ArrayList<Match_PlayerPO>(); private ArrayList<ArrayList<MatchDataPO>> matchDataPOs = new ArrayList<ArrayList<MatchDataPO>>(); private Rectangle rectangle; public PlayerMatch(PlayerDataPO po) { super(""); try { for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (Exception e) {} this.po = po; this.setBounds(26, 120, 948, 530); this.setLayout(null); this.setVisible(true); this.setBackground(UIUtil.bgWhite); init(); } private void init(){ rectangle = new Rectangle(14, 40, 920, 480); match_PlayerPOs = matchLogic.GetPlayerInfo(po.getName()); basicSetting(); pgSetting(); basicSP.setVisible(true); checkBox1 = new JCheckBox("总览"); checkBox1.setBounds(740, 5, 70, 30); checkBox1.setSelected(true); this.add(checkBox1); checkBox1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(checkBox1.isSelected()){ checkBox2.setSelected(false); pgSP.setVisible(false); basicSP.setVisible(true); }else{ checkBox1.setSelected(true); } } }); checkBox2 = new JCheckBox("详细"); checkBox2.setBounds(810, 5, 70, 30); this.add(checkBox2); checkBox2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(checkBox2.isSelected()){ checkBox1.setSelected(false); basicSP.setVisible(false); pgSP.setVisible(true); }else{ checkBox2.setSelected(true); } } }); } private double ShortDouble(double d){ DecimalFormat df = new DecimalFormat(".00"); return Double.parseDouble(df.format(d)); } private void basicSetting(){ final Vector<String> header = new Vector<String>(); header.addElement("日期");header.addElement("对手"); header.addElement("位置");header.addElement("在场时间");header.addElement("得分"); header.addElement("篮板");header.addElement("三分命中率");header.addElement("罚球命中率");header.addElement("助攻数");header.addElement("比赛链接"); final Vector<Vector<Object>> data = new Vector<Vector<Object>>(); for(int i=match_PlayerPOs.size()-1;i>=0;i--){ Vector<Object> vector = new Vector<Object>(); vector.addElement(match_PlayerPOs.get(i).getData()); vector.addElement(match_PlayerPOs.get(i).getOtherTeam()); if(match_PlayerPOs.get(i).getState().equals("")){ vector.addElement("非首发"); }else{ vector.addElement(match_PlayerPOs.get(i).getState()); } vector.addElement(match_PlayerPOs.get(i).getTime()); vector.addElement((int)match_PlayerPOs.get(i).getPoints()); vector.addElement((int)match_PlayerPOs.get(i).getBank()); vector.addElement(ShortDouble(match_PlayerPOs.get(i).getTPShootEff())); vector.addElement(ShortDouble(match_PlayerPOs.get(i).getFTShootEff())); vector.addElement((int)match_PlayerPOs.get(i).getAss()); vector.addElement("比赛链接"); data.addElement(vector); } basicTable = new StyleTable(); basicSP = new StyleScrollPane(basicTable); basicTable.tableSetting(basicTable, header, data, basicSP, rectangle); tableSetting(basicTable); basicTable.setSort(); basicSP.setVisible(false); this.add(basicSP); } private void pgSetting(){ final Vector<String> header = new Vector<String>(); header.addElement("日期");header.addElement("对手"); header.addElement("进攻篮板");header.addElement("防守篮板"); header.addElement("罚球");header.addElement("失误");header.addElement("投球"); header.addElement("投篮命中");header.addElement("投篮命中率");header.addElement("三分投篮"); header.addElement("三分命中");header.addElement("罚篮命中");header.addElement("抢断");header.addElement("盖帽"); header.addElement("犯规");header.addElement("比赛链接"); final Vector<Vector<Object>> data = new Vector<Vector<Object>>(); for(int i=match_PlayerPOs.size()-1;i>=0;i--){ Vector<Object> vector = new Vector<Object>(); vector.addElement(match_PlayerPOs.get(i).getData()); vector.addElement(match_PlayerPOs.get(i).getOtherTeam()); vector.addElement((int)match_PlayerPOs.get(i).getBankOff()); vector.addElement((int)match_PlayerPOs.get(i).getBankDef()); vector.addElement((int)match_PlayerPOs.get(i).getFT()); vector.addElement((int)match_PlayerPOs.get(i).getTo()); vector.addElement((int)match_PlayerPOs.get(i).getShoot()); vector.addElement((int)match_PlayerPOs.get(i).getShootEffNumber()); vector.addElement(ShortDouble(match_PlayerPOs.get(i).getShootEff())); vector.addElement((int)match_PlayerPOs.get(i).getTPShoot()); vector.addElement((int)match_PlayerPOs.get(i).getTPShootEffNumber()); vector.addElement((int)match_PlayerPOs.get(i).getFTShootEffNumber()); vector.addElement((int)match_PlayerPOs.get(i).getSteal()); vector.addElement((int)match_PlayerPOs.get(i).getRejection()); vector.addElement((int)match_PlayerPOs.get(i).getFoul()); vector.addElement("比赛链接"); data.addElement(vector); } pgTable = new StyleTable(); pgSP = new StyleScrollPane(pgTable); pgTable.tableSetting(pgTable, header, data, pgSP, rectangle); tableSetting(pgTable); pgTable.setSort(); pgSP.setVisible(false); this.add(pgSP); } private void tableSetting(final StyleTable table){ table.setPreferredScrollableViewportSize(new Dimension(920, 480));//设置大小 table.setBounds(14, 35, 920, 480); table.getTableHeader().setPreferredSize(new Dimension(920, 30));//设置表头大小 DefaultTableCellRenderer defaultTableCellRenderer = new DefaultTableCellRenderer(){ public java.awt.Component getTableCellRendererComponent(JTable t, Object value, boolean isSelected, boolean hasFocus, int row, int column) { if (row % 2 == 0) setBackground(new Color(235, 236, 231)); else setBackground(new Color(251, 251, 251)); setForeground(UIUtil.nbaBlue); return super.getTableCellRendererComponent(t, value, isSelected, hasFocus, row, column); } }; table.getColumnModel().getColumn(table.getColumnCount()-1).setCellRenderer(defaultTableCellRenderer); table.getColumnModel().getColumn(1).setCellRenderer(defaultTableCellRenderer); table.addMouseMotionListener(new MouseMotionListener() { public void mouseMoved(MouseEvent e) { int column = table.getColumnModel().getColumnIndexAtX(e.getX()); int row = e.getY()/table.getRowHeight(); if (row < table.getRowCount() && row >= 0 && column < table.getColumnCount() && column >= 0 && (column == table.getColumnCount()-1 || column == 1)) { table.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); }else{ table.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } } public void mouseDragged(MouseEvent e) { } }); MouseAdapter mouseAdapter = new MouseAdapter() { public void mousePressed(MouseEvent e) { int column = table.getColumnModel().getColumnIndexAtX(e.getX()); int row = e.getY()/table.getRowHeight(); TurnController turnController = new TurnController(); if (row < table.getRowCount() && row >= 0 && column < table.getColumnCount() && column >= 0 && (column == table.getColumnCount()-1)) { String date = table.getValueAt(row, 0).toString(); String team = table.getValueAt(row, 1).toString(); StartUI.startUI.turn(turnController.turnToMatchDetials(date, team)); }else{ if(row < table.getRowCount() && row >= 0 && column < table.getColumnCount() && column >= 0 && (column == 1)){ String team = table.getValueAt(row, 1).toString(); StartUI.startUI.turn(turnController.turnToTeamDetials(team)); } } } }; table.addMouseListener(mouseAdapter); } @Override public void refreshUI(){ if(this!=null){ this.removeAll(); this.init(); } } }
njuGenesis/njuGenesis2
NBA/src/main/java/presentation/player/PlayerMatch.java
66,356
package presentation.team; import java.awt.Color; import java.awt.Cursor; import java.awt.Dimension; import java.awt.Point; import java.awt.Rectangle; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionListener; import java.util.ArrayList; import java.util.Vector; import javax.swing.ImageIcon; import javax.swing.JTable; import javax.swing.UIManager; import javax.swing.UIManager.LookAndFeelInfo; import javax.swing.table.DefaultTableCellRenderer; import presentation.component.BgPanel; import presentation.component.DateLabel; import presentation.component.DatePanel; import presentation.component.GLabel; import presentation.component.StyleScrollPane; import presentation.component.StyleTable; import presentation.contenui.TurnController; import presentation.contenui.UIUtil; import presentation.mainui.StartUI; import bussinesslogic.match.MatchLogic; import data.po.MatchDataPO; import data.po.TeamDataPO; public class TeamMatch extends BgPanel{ private static final long serialVersionUID = 1L; private static String file = ""; private MatchLogic matchLogic; private DatePanel dateLabel1; private ArrayList<MatchDataPO> matchDataPOs; private TeamDataPO po; private StyleScrollPane scrollPane; private StyleTable table; private Rectangle rectangle; public TeamMatch(TeamDataPO po) { super(file); try { for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (Exception e) {} this.setBounds(26, 120, 948, 530); this.setLayout(null); this.setBackground(UIUtil.bgWhite); this.setVisible(true); this.po = po; init(); } private void init(){ GLabel message = new GLabel("*单击表头可排序", new Point(34, 5), new Point(120, 30), this, true, 0, 13); matchLogic = new MatchLogic(); this.po = po; matchDataPOs = matchLogic.GetInfo(po.getShortName()); rectangle = new Rectangle(14, 50, 920, 460); // dateLabel1 = new DatePanel(new Point(25, 9), this, Color.black, new ImageIcon("img/teamDetials/dateIcon.png")); // dateLabel1.setBackground(UIUtil.bgWhite); matchSetting(); repaint(); } private void matchSetting(){ final Vector<String> header = new Vector<String>(); header.addElement("日期");header.addElement("对手"); header.addElement("结果");header.addElement("比分");header.addElement("比赛链接"); final Vector<Vector<Object>> data = new Vector<Vector<Object>>(); for(int i=matchDataPOs.size()-1;i>=0;i--){ MatchDataPO m = matchDataPOs.get(i); Vector<Object> vector = new Vector<Object>(); vector.addElement(m.getDate()); if(m.getFirstteam().equals(po.getShortName())){ vector.addElement(m.getSecondteam()); }else{ vector.addElement(m.getFirstteam()); } if(m.getWinner().equals(po.getShortName())){ vector.addElement("胜"); }else{ vector.addElement("负"); } vector.addElement(m.getPoints()); vector.addElement("比赛链接"); data.addElement(vector); } table = new StyleTable(); scrollPane = new StyleScrollPane(table); table.tableSetting(table, header, data, scrollPane, rectangle); tableSetting(table); table.setSort(); this.add(scrollPane); } private void tableSetting(final JTable table){ table.setPreferredScrollableViewportSize(new Dimension(920, 480));//设置大小 table.setBounds(14, 35, 920, 480); table.getTableHeader().setPreferredSize(new Dimension(920, 30));//设置表头大小 DefaultTableCellRenderer defaultTableCellRenderer = new DefaultTableCellRenderer(){ public java.awt.Component getTableCellRendererComponent(JTable t, Object value, boolean isSelected, boolean hasFocus, int row, int column) { if (row % 2 == 0) setBackground(new Color(235, 236, 231)); else setBackground(new Color(251, 251, 251)); setForeground(UIUtil.nbaBlue); return super.getTableCellRendererComponent(t, value, isSelected, hasFocus, row, column); } }; table.getColumnModel().getColumn(1).setCellRenderer(defaultTableCellRenderer); table.getColumnModel().getColumn(4).setCellRenderer(defaultTableCellRenderer); table.addMouseMotionListener(new MouseMotionListener() { public void mouseMoved(MouseEvent e) { int column = table.getColumnModel().getColumnIndexAtX(e.getX()); int row = e.getY()/table.getRowHeight(); if (row < table.getRowCount() && row >= 0 && column < table.getColumnCount() && column >= 0 && (column == 1 || column ==4)) { table.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); }else{ table.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } } public void mouseDragged(MouseEvent e) { } }); MouseAdapter mouseAdapter = new MouseAdapter() { public void mousePressed(MouseEvent e) { int column = table.getColumnModel().getColumnIndexAtX(e.getX()); int row = e.getY()/table.getRowHeight(); TurnController turnController = new TurnController(); if (row < table.getRowCount() && row >= 0 && column < table.getColumnCount() && column >= 0 && (column == 1)) { String name = table.getValueAt(row, 1).toString(); StartUI.startUI.turn(turnController.turnToTeamDetials(name)); }else{ if (row < table.getRowCount() && row >= 0 && column < table.getColumnCount() && column >= 0 && (column == 4)) { String date = table.getValueAt(row, 0).toString(); String name = table.getValueAt(row, 1).toString(); StartUI.startUI.turn(turnController.turnToMatchDetials(date, name)); } } } }; table.addMouseListener(mouseAdapter); } @Override public void refreshUI(){ if(this!=null){ this.removeAll(); this.init(); } } }
njuGenesis/njuGenesis2
NBA/src/main/java/presentation/team/TeamMatch.java