JavaScript基础巩固之小游戏练习

news/2025/3/30 7:05:41/

文章目录

  • 一、前言
  • 二、练习

一、前言

加强巩固JavaScript基础语法,现记录一下JavaScript的练习过程。
需要的模块:npm install readline-sync 配置:node.js

二、练习

▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰猜拳游戏(简易版)▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰
前置知识:函数、条件判断
注意:readline-sync模块会有中文乱码问题,具体解决方案参考:https://codelove.tw/@hung/post/jaljmx
打开设置,选择区域
在这里插入图片描述
点击管理语言和设置:
在这里插入图片描述
勾选使用Unicode UTF-8提供全球语言支持,然后重启电脑。
在这里插入图片描述
代码如下:

javascript">const readline = require('readline-sync');function computerRound() {const random = Math.floor(Math.random() * 3);return ['剪刀', '石头', '布'][random];
}function playRound() {while (true) {console.log('请输入你的选择:剪刀、石头、布');let userInput = readline.question('input:');userInput = String(userInput).trim();if (['剪刀', '石头', '布'].includes(userInput)) {return userInput;}console.log('输入错误,请重新输入');}
}function checkGameOver(userScore, computerScore) {if (userScore >= 3 || computerScore >= 3) {const winner = userScore > computerScore ? '你' : '电脑';console.log(`游戏结束,${winner}获胜!`);return true;}return false;
}function startGame() {let userScore = 0;let computerScore = 0;while (true) {console.log(`当前比分:用户 ${userScore} : ${computerScore} 电脑`);const userInput = playRound();const computerInput = computerRound();console.log(`电脑选择:${computerInput}`);if (userInput === computerInput) {console.log('平局');} else if ((userInput === '剪刀' && computerInput === '布') ||(userInput === '石头' && computerInput === '剪刀') ||(userInput === '布' && computerInput === '石头')) {console.log('你赢了');userScore++;} else {console.log('你输了');computerScore++;}if (checkGameOver(userScore, computerScore)) break; // 检查游戏是否结束}
}startGame();

▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰五子棋(简易版)▰▰▰▰▰▰▰▰▰▰▰▰▰▰▰
初步实现电脑下棋逻辑,能够实现简单的防守策略。

javascript">// 五子棋const readlineSync = require('readline-sync');class Board {constructor() {this.board = new Array(9);for (let i = 0; i < this.board.length; i++) {this.board[i] = new Array(9);for (let j = 0; j < this.board.length; j++) {this.board[i][j] = "+";}}this.blackBoard = "O";this.whiteBoard = "X";this.enptyBoard = "+";}showBoard() {console.log("  0  1  2  3  4  5  6  7  8  9");for (let i = 0; i < this.board.length; i++) {let showData = "  " + String(i + 1) + "  ";for (let j = 0; j < this.board.length; j++) {showData += this.board[i][j] + "  ";}console.log(showData);}}isEmpty(x, y) {return this.board[x][y] === this.enptyBoard;}isBlack(x, y) {return this.board[x][y] === this.blackBoard;}isWhite(x, y) {return this.board[x][y] === this.whiteBoard;}setPiece(x, y, piece) {this.board[x][y] = piece;}
}class Game {constructor() {this.board = new Board();this.player = 1;this.playerRow = 1;this.playerCol = 1;this.cpuRow = 1;this.cpuCol = 1;}playLoop() {while (true) {this.board.showBoard();console.log("当前玩家为:" + (this.player === 1 ? "黑棋 (O)" : "白棋 (X)"));this.playRound();if (this.isWin(this.playerRow, this.playerCol)) {this.board.showBoard();console.log("恭喜玩家 " + (this.player === 1 ? "黑棋 (O)" : "白棋 (X)") + " 赢得了比赛!");break;}this.shiftRound();console.clear();}}playRound() {var row;var col;while (true) {if (this.player === 1) {console.log("黑棋下棋");console.log("请输入坐标(例如:12):")let answer = readlineSync.question("input:");row = Number(answer[0]) - 1;col = Number(answer[1]) - 1;this.playerRow = row;this.playerCol = col;} else {""console.log("白棋下棋");[row, col] = this.cpuRound(); // cpu下棋this.cpuRow = row;this.cpuCol = col;}if (this.isValidCoordinate(row, col) && this.board.isEmpty(row, col)) {this.board.setPiece(row, col, this.player === 1 ? this.board.blackBoard : this.board.whiteBoard);break;} else {console.log("输入无效,请重新输入。");}}}cpuRound() {// 查看横let finalRow;let finalCol;let toright = 1  //向右let toleft = -1  //向左let coherent = 1  //连贯let maxcoherent = 1  //最大连贯while (this.playerRow + toright < 9 && this.board.isBlack(this.playerRow, this.playerCol + toright)) {coherent++toright++}while (this.playerRow + toleft >= 0 && this.board.isBlack(this.playerRow, this.playerCol + toleft)) {coherent++toleft--}if (coherent >= maxcoherent) {let newCol = this.playerCol + toright;if (this.isValidCoordinate(this.playerRow, newCol) && this.board.isEmpty(this.playerRow, newCol)) {finalRow = this.playerRow;finalCol = newCol;maxcoherent = coherent;} else {newCol = this.playerCol + toleft;if (this.isValidCoordinate(this.playerRow, newCol) && this.board.isEmpty(this.playerRow, newCol)) {finalRow = this.playerRow;finalCol = newCol;maxcoherent = coherent;}}}//查看竖let toup = 1  //向上let todown = -1  //向下coherent = 1while (this.playerRow + toup < 9 && this.board.isBlack(this.playerRow + toup, this.playerCol)) {coherent++toup++}while (this.playerRow + todown >= 0 && this.board.isBlack(this.playerRow + todown, this.playerCol)) {coherent++todown--}if (coherent >= maxcoherent) {let newRow = this.playerRow + toup;if (this.isValidCoordinate(newRow, this.playerCol) && this.board.isEmpty(newRow, this.playerCol)) {finalRow = newRow;finalCol = this.playerCol;maxcoherent = coherent;} else {newRow = this.playerRow + todown;if (this.isValidCoordinate(newRow, this.playerCol) && this.board.isEmpty(newRow, this.playerCol)) {finalRow = newRow;finalCol = this.playerCol;maxcoherent = coherent;}}}//查看斜向右下let torightdown = 1  //向右下let toleftup = -1  //向左上coherent = 1while (this.playerRow + torightdown < 9 && this.playerCol + torightdown < 9 && this.board.isBlack(this.playerRow + torightdown, this.playerCol + torightdown)) {coherent++torightdown++}while (this.playerRow + toleftup >= 0 && this.playerCol + toleftup >= 0 && this.board.isBlack(this.playerRow + toleftup, this.playerCol + toleftup)) {coherent++toleftup--}if (coherent >= maxcoherent) {let newRow = this.playerRow + torightdown;let newCol = this.playerCol + torightdown;maxcoherent = coherent;if (this.isValidCoordinate(newRow, newCol) && this.board.isEmpty(newRow, newCol)) {finalRow = newRow;finalCol = newCol;} else {newRow = this.playerRow + toleftup;newCol = this.playerCol + toleftup;if (this.isValidCoordinate(newRow, newCol) && this.board.isEmpty(newRow, newCol)) {finalRow = newRow;finalCol = newCol;}}}//查看斜向左下let toleftdown = 1  //向左下let torightup = -1  //向右上coherent = 1while (this.playerRow + toleftdown < 9 && this.playerCol - toleftdown >= 0 && this.board.isBlack(this.playerRow + toleftdown, this.playerCol - toleftdown)) {coherent++toleftdown++}while (this.playerRow + torightup >= 0 && this.playerCol - torightup < 9 && this.board.isBlack(this.playerRow + torightup, this.playerCol - torightup)) {coherent++torightup--}if (coherent >= maxcoherent) {let newRow = this.playerRow + toleftdown;let newCol = this.playerCol + toleftdown;if (this.isValidCoordinate(newRow, newCol) && this.board.isEmpty(newRow, newCol)) {finalRow = newRow;finalCol = newCol;maxcoherent = coherent;} else {newRow = this.playerRow + torightup;newCol = this.playerCol + torightup;if (this.isValidCoordinate(newRow, newCol) && this.board.isEmpty(newRow, newCol)) {finalRow = newRow;finalCol = newCol;maxcoherent = coherent;}}}return [finalRow, finalCol]}shiftRound() {// 轮流下棋this.player = this.player === 1 ? 2 : 1;}isValidCoordinate(row, col) {// 判断坐标是否在棋盘范围内return row >= 0 && row < 9 && col >= 0 && col < 9;}isWin(row, col) {const directions = [{dx: 0, dy: 1},  // 水平{dx: 1, dy: 0},  // 垂直{dx: 1, dy: 1},  // 斜向右下{dx: 1, dy: -1}  // 斜向左下];const piece = this.player === 1 ? this.board.blackBoard : this.board.whiteBoard;for (let dir of directions) {let count = 1;let x = row + dir.dx;let y = col + dir.dy;while (this.isValidCoordinate(x, y) && this.board.board[x][y] === piece) {count++;x += dir.dx;y += dir.dy;}x = row - dir.dx;y = col - dir.dy;while (this.isValidCoordinate(x, y) && this.board.board[x][y] === piece) {count++;x -= dir.dx;y -= dir.dy;}if (count >= 5) {return true;}}return false;}
}let game = new Game();
game.playLoop();

http://www.ppmy.cn/news/1583420.html

相关文章

1.基于TCP的简单套接字服务器实现

目录 1. TCP通信流程 2. 服务器端的通信流程 2.1 创建用于监听的套接字 2.2 绑定本地IP地址和端口 2.3 设置监听 2.4 等待接受客户端的连接请求 2.5 与客户端进行通信 2.6 客户端连接服务器 3.代码实现 client.cpp server.cpp 运行方式 在本文中&#xff0c;我们将…

【开源宝藏】30天学会CSS - DAY9 第九课 牛顿摆动量守恒动画

以下是一份逐步拆解教程&#xff0c;带你从零理解并复刻这个牛顿摆&#xff08;Pendulum of Newton&#xff09;动画效果&#xff0c;这是一个经典的物理演示模型&#xff0c;现在通过纯 HTML 和 CSS 实现出来&#xff0c;视觉效果炫酷、结构简洁。 &#x1f3af; 动画效果说明…

wokwi arduino mega 2560 - 键盘与LCD显示

截图&#xff1a; 链接&#xff1a; https://wokwi.com/projects/414520193913760769 代码&#xff1a; //cslg lcd key #include <LiquidCrystal.h> // 引入LiquidCrystal库&#xff0c;用于LCD显示 #include <Keypad.h> // 引入Keypad库&#xff0c;用于键盘输…

SpringBoot通过Map实现天然的策略模式

&#x1f60a; 作者&#xff1a; 一恍过去 &#x1f496; 主页&#xff1a; https://blog.csdn.net/zhuocailing3390 &#x1f38a; 社区&#xff1a; Java技术栈交流 &#x1f389; 主题&#xff1a; SpringBoot通过Map实现天然的策略模式 ⏱️ 创作时间&#xff1a; 202…

夯实 kafka 系列|第三章:kafka 常用监控工具

文章目录 1.前言2.kafka 命令行工具3.kafka tools4.kafka-ui&#xff08;推荐&#xff09;5.实用功能5.1 消息查找5.1.1 kafka-ui5.1.2 kafka tools 5.2 手动添加 1.前言 本章主要是介绍一些工作中常用 kafka 的监控工具&#xff1b;原理上都是一样的&#xff0c;只是展现方式…

web爬虫笔记:js逆向案例十一 某数cookie(补环境流程)

web爬虫笔记:js逆向案例十一 某数cookie(补环境流程) 一、获取网页数据请求流程 二、目标网址、cookie生成(逐步分析) 1、目标网址:aHR0cHM6Ly9zdWdoLnN6dS5lZHUuY24vSHRtbC9OZXdzL0NvbHVtbnMvNy9JbmRleC5odG1s 2、快速定位入口方法 1、通过脚本监听、hook_cookie等操作可…

第一章:优化概述_《C++性能优化指南》notes

优化概述 第一章核心知识点详解1. 性能优化的必要性2. 编译器优化选项3. 减少内存分配总结 第一章重点内容回顾第一部分&#xff1a;多项选择题第二部分&#xff1a;程序设计题&#xff08;5题&#xff09;答案及详解多选题答案&#xff1a; 程序设计题答案示例1. 优化字符串类…

WordPress自动代码高亮插件Code Prettify插件

一、插件介绍 Code Prettify 是一款轻量级的 WordPress 代码高亮插件,由 Google 开发,专为在网页上美化代码显示而设计。它支持多种编程语言,能够自动检测代码并进行语法高亮,无需手动添加标签。 该插件适用于技术博客、开发者文档站点以及任何需要展示代码的 WordPress …