亚洲精品久久久中文字幕-亚洲精品久久片久久-亚洲精品久久青草-亚洲精品久久婷婷爱久久婷婷-亚洲精品久久午夜香蕉

您的位置:首頁技術文章
文章詳情頁

利用Java編寫24點小游戲的實例代碼

瀏覽:16日期:2022-08-18 16:11:24

話不多說直接給大家上代碼

package com.company;import java.util.*;/** * 24點小游戲 * 游戲規則:系統自動生成4個1-10的隨機整數,玩家通過加減乘除操作,得到結果為24,每個數字只能使用一次 */public class Game24Player { final String[] patterns = {'nnonnoo', 'nnonono', 'nnnoono', 'nnnonoo', 'nnnnooo'}; final String ops = '+-*/^';//存儲運算符 String solution;//解題答案 List<Integer> digits; public static void main(String[] args) { new Game24Player().play(); } void play() { digits = getSolvableDigits(); Scanner in = new Scanner(System.in); while (true) { System.out.println('24點小游戲:'); System.out.print('使用以下數字得出24點: '); System.out.println(digits); System.out.println('tips:輸入q退出游戲,輸入s打印解法以及出下一道題'); System.out.print('> '); String line = in.nextLine();//獲取控制臺下一行輸入的內容 if (line.equalsIgnoreCase('q')) { System.out.println('nThanks for playing'); return; } if (line.equalsIgnoreCase('s')) { System.out.println(solution); digits = getSolvableDigits(); continue; } char[] entry = line.replaceAll('[^*+-/)(d]', '').toCharArray(); try { validate(entry); if (evaluate(infixToPostfix(entry))) { System.out.println('n恭喜你,回答正確,請繼續下一輪 '); digits = getSolvableDigits(); } else { System.out.println('n答題錯誤,請重新答題'); } } catch (Exception e) { System.out.printf('%n%s 請重新輸入.%n', e.getMessage()); } } } //判斷玩家在控制臺輸入的內容是否正確 void validate(char[] input) throws Exception { int total1 = 0, parens = 0, opsCount = 0; for (char c : input) { if (Character.isDigit(c)) total1 += 1 << (c - ’0’) * 4; else if (c == ’(’) parens++; else if (c == ’)’) parens--; else if (ops.indexOf(c) != -1) opsCount++; if (parens < 0) throw new Exception('括號不匹配.'); } if (parens != 0) throw new Exception('括號不匹配.'); if (opsCount != 3) throw new Exception('錯誤輸入.'); int total2 = 0; for (int d : digits) total2 += 1 << d * 4; if (total1 != total2) throw new Exception('輸入有誤.'); } boolean evaluate(char[] line) throws Exception { Stack<Float> s = new Stack<>(); try { for (char c : line) { if (’0’ <= c && c <= ’9’) s.push((float) c - ’0’); else s.push(applyOperator(s.pop(), s.pop(), c)); } } catch (EmptyStackException e) { throw new Exception('輸入無效,請重新輸入.'); } return (Math.abs(24 - s.peek()) < 0.001F); } float applyOperator(float a, float b, char c) { switch (c) { case ’+’: return a + b; case ’-’: return b - a; case ’*’: return a * b; case ’/’: return b / a; default: return Float.NaN; } } //獲取一組隨機數 List<Integer> randomDigits() { Random r = new Random(); List<Integer> result = new ArrayList<>(4); for (int i = 0; i < 4; i++) result.add(r.nextInt(9) + 1);//添加4個1-10的隨機數 return result; } List<Integer> getSolvableDigits() { List<Integer> result; do { result = randomDigits(); } while (!isSolvable(result)); return result; } boolean isSolvable(List<Integer> digits) { Set<List<Integer>> dPerms = new HashSet<>(4 * 3 * 2); permute(digits, dPerms, 0); int total = 4 * 4 * 4; List<List<Integer>> oPerms = new ArrayList<>(total); permuteOperators(oPerms, 4, total); StringBuilder sb = new StringBuilder(4 + 3); for (String pattern : patterns) { char[] patternChars = pattern.toCharArray(); for (List<Integer> dig : dPerms) { for (List<Integer> opr : oPerms) { int i = 0, j = 0; for (char c : patternChars) { if (c == ’n’) sb.append(dig.get(i++)); else sb.append(ops.charAt(opr.get(j++))); } String candidate = sb.toString(); try { if (evaluate(candidate.toCharArray())) { solution = postfixToInfix(candidate); return true; } } catch (Exception ignored) { } sb.setLength(0); } } } return false; } String postfixToInfix(String postfix) { class Expression { String op, ex; int prec = 3; Expression(String e) { ex = e; } Expression(String e1, String e2, String o) { ex = String.format('%s %s %s', e1, o, e2); op = o; prec = ops.indexOf(o) / 2; } } Stack<Expression> expr = new Stack<>(); for (char c : postfix.toCharArray()) { int idx = ops.indexOf(c); if (idx != -1) { Expression r = expr.pop(); Expression l = expr.pop(); int opPrec = idx / 2; if (l.prec < opPrec) l.ex = ’(’ + l.ex + ’)’; if (r.prec <= opPrec) r.ex = ’(’ + r.ex + ’)’; expr.push(new Expression(l.ex, r.ex, '' + c)); } else { expr.push(new Expression('' + c)); } } return expr.peek().ex; } char[] infixToPostfix(char[] infix) throws Exception { StringBuilder sb = new StringBuilder(); Stack<Integer> s = new Stack<>(); try { for (char c : infix) { int idx = ops.indexOf(c); if (idx != -1) { if (s.isEmpty()) s.push(idx); else { while (!s.isEmpty()) { int prec2 = s.peek() / 2; int prec1 = idx / 2; if (prec2 >= prec1)sb.append(ops.charAt(s.pop())); elsebreak; } s.push(idx); } } else if (c == ’(’) { s.push(-2); } else if (c == ’)’) { while (s.peek() != -2) sb.append(ops.charAt(s.pop())); s.pop(); } else { sb.append(c); } } while (!s.isEmpty()) sb.append(ops.charAt(s.pop())); } catch (EmptyStackException e) { throw new Exception('Invalid entry.'); } return sb.toString().toCharArray(); } void permute(List<Integer> lst, Set<List<Integer>> res, int k) { for (int i = k; i < lst.size(); i++) { Collections.swap(lst, i, k); permute(lst, res, k + 1); Collections.swap(lst, k, i); } if (k == lst.size()) res.add(new ArrayList<>(lst)); } void permuteOperators(List<List<Integer>> res, int n, int total) { for (int i = 0, npow = n * n; i < total; i++) res.add(Arrays.asList((i / npow), (i % npow) / n, i % n)); }}

運行結果截圖

游戲題目

利用Java編寫24點小游戲的實例代碼

在控制臺輸入答案

利用Java編寫24點小游戲的實例代碼

輸入s是查看結果并開始下一次游戲。

利用Java編寫24點小游戲的實例代碼

輸入q是退出游戲。

利用Java編寫24點小游戲的實例代碼

總結

到此這篇關于利用Java編寫24點小游戲的文章就介紹到這了,更多相關Java編寫24點小游戲內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: Java
相關文章:
主站蜘蛛池模板: 国产精品亚洲精品日韩己满十八小 | 啪啪免费看视频 | 国内精品视频一区二区三区 | 欧美日韩在线观看区一二 | 亚洲视色 | 欧美精品一区二区三区四区 | pr社萌汁福利视频在线观看 | 成人免费毛片一区二区三区 | 欧美日韩在线视频 | 久久精品国产99国产精品 | 搞黄网站在线观看 | 伦理亚洲| 高清国产一区二区 | 色综色天天综合网 | 二色a v国产 | 欧美日韩高清观看一区二区 | 一级片黄色片 | 国产一级毛片亚洲久留木玲 | 婷婷啪啪 | 日本爽妇网 | 黄色片三级网站 | 男人在线网址 | 欧美日韩一区二区三区免费不卡 | 久久久青青草 | 三级福利视频 | 片在线观看免费观看视频 | 亚洲人成在线免费观看 | 国产三级a三级三级野外 | 欧美日韩综合在线视频免费看 | 亚洲一区二区视频在线观看 | xxxxxxx国产精品视频 | 欧美黄色免费网站 | 不卡精品国产_亚洲人成在线 | 精品一区二区三区自拍图片区 | 宅男在线永久免费观看99 | 在线播放亚洲美女视频网站 | 国产精品久久久久aaaa | 亚洲精品久久一区影院 | 免费黄色视屏 | 最新国产网站 | 中文字幕高清在线 |