文章目錄
- 前言
- 功能展示
- 新增模塊功能
- 搭建專案框架
- 配置React Router
- 配置React Store
- 配置i18n
- 配置主題色
- React影片
- React ColorPicker
- 打譜記錄
- 單元測驗
- 核心功能優化
- 落子音效
- dom解耦
- 小結
- 結語
前言
它終于來了,終于來了,在第一版的基礎上,歷時近兩個月終于完成react版本的中國象棋,這個版本使用的技術堆疊包括react hooks+ts+sass+antd(本來還準備使用redux,但是嫌麻煩,就沒用使用),這次主要是時間消耗是在hooks以及ts的使用上,畢竟從某種意義上來說,我也是ts和hooks的新手,所以這個專案也很適合新手來學習并使用hooks以及ts,
在正式開始講述之前,我建議大家可以先看看我上個使用原生js實作的版本,因為核心邏輯是幾乎是復用之前的代碼,原生js版本
同樣,想趕緊獲取原始碼跑起來試一試的朋友可以點擊此鏈接:原始碼地址
(創作不易,如果覺得還可以的話,那么就在github上留下一個Star)
功能展示
由于沒有部署在服務器上,就只能可以先給大家看幾張效果圖:




暫時就放這幾張圖,更多功能有待大家自己去體驗,
下面,我帶領大家具體從零開始去如何創建此專案,(講述主要流程)
新增模塊功能
搭建專案框架
我們需要創建基于ts的react專案,在這里我建議大家使用官方的腳手架進行創建:
npx create-react-app my-app --template typescript
創建完成之后,可以把一些默認的沒必要的檔案洗掉掉,
緊接著下一步就是配置路由,
配置React Router
這里我就不具體講解如何配置React Router,網上有很多學習資料,大家可以自行搜索學習,這里我給出一個當時我自己配置時參考的一個阮一峰老師的檔案:React Router使用檔案
在這里我們需要配置Home,Settings,Change以及About四個路由頁面,
在App組件主要是配置路由頁面的顯示:
const routes: Routers = [
["home", Home],
["settings", Settings],
["change", Change],
["about", About],
];
function App() {
return (
<Router>
<div className="App">
<AppMenu routers={routes} />
<div id="pageContainer" className="page-container">
<Switch>
{routes.map(([label, Component]) => (
<Route
key={label as string}
path={`/${label}`}
>
<Component />
</Route>
))}
<Route path="/" exact>
<Home />
</Route>
<Route path="*"><h1>Page not found.</h1></Route>
</Switch>
</div>
</div>
</Router>
);
}
在AppMenu組件中進行路由的切換:
export default function AppMenu(props: MenuProps) {
const { t } = useTranslation();
const [key, setKey] = useState('');
const { routers } = props;
const changeMenu = useCallback((e: any) => {
setKey(e.key);
}, []);
const setContent = () => (
<Menu onClick={changeMenu} selectedKeys={[key]}>
{routers.map(([label]) => <Menu.Item key={label.toString()}>
<Link to={`/${label}`}>{t(label.toString())}</Link>
</Menu.Item>)}
</Menu>
)
return (
<>
<Dropdown overlay={setContent} placement="bottomRight">
<Button className={'app-menu'} icon={<AppstoreOutlined />} />
</Dropdown>
</>
)
}
路由配置完成之后,我們就可以開始撰寫每個路由頁面的內容,
下面講述不區分步驟順序,
配置React Store
這個板塊更一般是情況下是使用redux,將store里面的資料交給redux進行管理,但是這里我選擇了自己管控(主要原因還是資料不多),有興趣的朋友可以基于此專案使用redux將其進一步升級,
setting.ts:(保存著Setting路由頁面里的資料狀態)
const settings = {
isShowPoint: true,
isUseSound: true,
pointColor: '#1198bc',
blackChessColor: '#000',
redChessColor: 'red',
isReverse: false,
themeKeys: themes[0],
language: languages.zh
};
home.ts:(保存著非Setting路由頁面但是需要使用的全域的資料狀態)
const home = {
isStart: false,
isEnd: true,
isShowPoint: false,
isShowPath: false,
version: 'v1.0.0'
};
配置i18n
這個板塊是為了使專案語言能夠多樣化,這里我也是參考網上的博客進行配置學習,資源鏈接:配置 i18n
index.ts:
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
// 層級嵌套如何處理
const resources = {
en: {
translation: {
'title': 'Chinese Chess',
'settings': 'Settings',
'start': 'START',
'surrender': 'SURRENDER',
'change': 'Change',
'home': 'Home',
'about': 'About',
'lang': 'Language',
'black chess color': 'Black Chess Color:',
'red chess color': 'Red Chess Color:',
'show point positions': 'Show Point Positions:',
'use sound':'Use Sound:',
'theme style': 'Theme Style:',
'default theme': 'Default Theme',
'dark theme': 'Dark Theme',
'point color': 'Point Color:',
'reverse board': 'Reverse Board:',
'reverse rule': 'This operation can only be used before the start of the game',
'chooseOffensiveTitle': 'Choose Offensive',
'chooseOffensiveBody': 'Who is to go on the offensive?',
'me': 'Me',
'computer': 'Computer',
'game start': 'Game Start',
'red win': 'Red Win',
'black win': 'Black Win',
'giveTitle': 'Give up?',
'giveBody': 'Are you sure to give up?',
'ok': 'OK',
'cancel': 'Cancel',
'show': 'Show',
'rounds': 'Rounds:'
}
},
zh: {
translation: {
'title': '中國象棋',
'settings': '設定',
'start': '開始',
'surrender': '認輸',
'change': '更新',
'home': '首頁',
'about': '關于',
'lang': '語言',
'black chess color': '黑方棋子顏色:',
'red chess color': '紅方棋子顏色:',
'show point positions': '顯示落子提示點:',
'use sound':'使用音效:',
'theme style': '主題樣式:',
'default theme': '默認主題',
'dark theme': '暗黑主題',
'point color': '提示點顏色:',
'reverse board': '交換棋盤位置:',
'reverse rule': '此操作僅限于開局前使用',
'chooseOffensiveTitle': '選擇先手',
'chooseOffensiveBody': '誰執紅方?',
'me': '我',
'computer': '電腦',
'game start': '游戲開始',
'red win': '紅方贏',
'black win': '黑方贏',
'giveTitle': '認輸?',
'giveBody': '你確定認輸嗎?',
'ok': '確認',
'cancel': '取消',
'show': '查看',
'rounds': '回合數:'
}
},
};
i18n.use(initReactI18next).init({
resources,
lng: 'zh', //設定當前語言
keySeparator: false, // we do not use keys in form messages.welcome
interpolation: {
escapeValue: false // react already safes from xss
}
});
export default i18n;
配置主題色
這里我是基于Sass進行主題色配置,至于如何使用Sass實作主題切換大家可以參看這篇文章:使用Sass實作主題切換
theme.scss:
$default-body-bg: #fff;
$default-board-opacity: 1;
$default-ui-bg: #fff;
$default-switch-bg: #00000040;
$default-select-dropdown-bg: #fff;
$default-select-item-bg: #e6f7ff;
$default-select-active-item-bg: #f5f5f5;
$default-body-color: #000000d9;
$default-text-color: rgba(0, 0, 0, 0.45);
$default-btn-hover-color: #3c9be8;
$default-btn-border-color: #d9d9d9;
$default-btn-hover-border-color: #3c9be8;
$default-title-color: #09bb07;
$default-divider-border-color: rgba(0, 0, 0, 0.06);
$default-select-border-color: #d9d9d9;
$default-select-arrow-color: #00000040;
$dark-body-bg: #000;
$dark-board-opacity: 0.8;
$dark-select-dropdown-bg: #1f1f1f;
$dark-select-item-bg: #111b26;
$dark-select-active-item-bg: rgba(255, 255, 255, 0.08);
$dark-ui-bg: rgba(255, 255, 255, 0.8);
$dark-switch-bg: rgba(255, 255, 255, 0.3);
$dark-body-color: rgba(255, 255, 255, 0.65);
$dark-text-color: rgba(255, 255, 255, 0.45);
$dark-btn-hover-color: #165996;
$dark-btn-border-color: #434343;
$dark-btn-hover-border-color: #165996;
$dark-title-color: #065705;
$dark-divider-border-color: #303030;
$dark-select-border-color: #434343;
$dark-select-arrow-color: rgba(255, 255, 255, 0.3);
$themes: (
default: (
body-bg: $default-body-bg,
board-opacity: $default-board-opacity,
ui-bg: $default-ui-bg,
switch-bg: $default-switch-bg,
select-dropdown-bg: $default-select-dropdown-bg,
select-item-bg: $default-select-item-bg,
select-active-item-bg: $default-select-active-item-bg,
body-color: $default-body-color,
btn-hover-color: $default-btn-hover-color,
btn-border-color: $default-btn-border-color,
btn-hover-border-color: $default-btn-hover-border-color,
title-color: $default-title-color,
divider-border-color: $default-divider-border-color,
select-border-color: $default-select-border-color,
select-arrow-color: $default-select-arrow-color,
),
dark: (
body-bg: $dark-body-bg,
board-opacity: $dark-board-opacity,
ui-bg: $dark-ui-bg,
switch-bg: $dark-switch-bg,
select-dropdown-bg: $dark-select-dropdown-bg,
select-item-bg: $dark-select-item-bg,
select-active-item-bg: $dark-select-active-item-bg,
body-color: $dark-body-color,
text-color: $dark-text-color,
btn-hover-color: $dark-btn-hover-color,
btn-border-color: $dark-btn-border-color,
btn-hover-border-color: $dark-btn-hover-border-color,
title-color: $dark-title-color,
divider-border-color: $dark-divider-border-color,
select-border-color: $dark-select-border-color,
select-arrow-color: $dark-select-arrow-color,
),
);
大家應該發現了這里面我不僅配置了一些基本標簽的主題色,并且還配置了antd組件內部的主題色,
themify.scss:
@import "./theme.scss";
@mixin themify {
@each $theme-name, $theme-map in $themes {
$theme-map: $theme-map !global;
body[data-theme="#{$theme-name}"] & {
@content;
}
}
}
@function themed($key) {
@return map-get($theme-map, $key);
}
@each $theme-name, $theme-map in $themes {
body[data-theme="#{$theme-name}"] {
color: map-get($theme-map, "body-color");
background-color: map-get($theme-map, "body-bg");
}
}
由于body本身的主題色是不受屬性選擇器的影響,所以這里我將其單獨拎出來配置主題色,
使用案例:
h4.ant-typography,
.ant-typography h4 {
@include themify {
color: themed("body-color");
}
}
.ant-divider {
@include themify {
border-top-color: themed("divider-border-color");
}
}
.ant-typography.ant-typography-secondary {
@include themify {
color: themed("text-color");
}
}
React影片
在此專案中我撰寫了一個react影片組件BigText,它是基于react-transition-group的CSSTransition組件進行實作,大家可以參考以下資源進行學習:CSSTransition官網 、CSSTransition知乎
BigText.tsx:
import { CSSTransition } from 'react-transition-group';
import { BigTextProps } from '../views/Home';
export default function BigText(props: BigTextProps) {
const { text, isIn } = props;
return (
<>
<CSSTransition classNames="fade" timeout={500} in={isIn} unmountOnExit>
<div className="big-text">{text}</div>
</CSSTransition>
</>
)
}
React ColorPicker
在此專案中我封裝的ColorPicker是基于React Color的ChromePicker,有關React Color的使用檔案可以點擊下面的資源:React Color檔案
ColorPicker.tsx:
import React, { useState, useCallback, CSSProperties } from "react";
import { Button } from 'antd';
import { BgColorsOutlined } from '@ant-design/icons';
import { ChromePicker } from 'react-color';
import { ColorPickProps } from "../views/Settings";
const popover: CSSProperties = {
position: 'absolute',
zIndex: 2,
right: '0',
top: '32px'
}
const cover: CSSProperties = {
position: 'fixed',
top: '0px',
right: '0px',
bottom: '0px',
left: '0px',
}
const buttonStyle: CSSProperties = {
position: 'relative'
}
export default function ColorPicker(props: ColorPickProps) {
const { color, colorChange } = props;
const [show, setShow] = useState(false);
const changeShow = useCallback(() => {
setShow(!show);
}, [show]);
const handleClose = useCallback(() => {
setShow(false);
}, []);
return (
<div style={buttonStyle}>
<Button shape='circle' icon={<BgColorsOutlined />} onClick={changeShow} />
{show ?
<div style={popover}>
<div style={cover} onClick={handleClose} />
<ChromePicker color={color} onChange={colorChange} />
</div>
: null}
</div>
)
}
打譜記錄
打譜記錄得到的結果是通過chessRecord函式得到的,只需要知道當前棋子的開始位置、結束位置以及當前棋盤的狀態(是否反轉) 就能得到該棋子的此次打譜結果,
chessRecord.ts:
import { BoardCore } from "./board";
import role from "./role";
import texts from './text';
const redTexts = ['九', '八', '七', '六', '五', '四', '三', '二', '一'];
const blackTexts = ['1', '2', '3', '4', '5', '6', '7', '8', '9'];
const actions = ['平', '進', '退'];
// 車炮兵帥一類
// 馬士相一類
export function chessRecord(startPosition: number[], endPosition: number[], targetPosition: number[], player: BoardCore) {
const { type, text } = player;
const [redStart, blackStart] = targetPosition;
let action = '';
let res = '';
if (type === role.red) {
if (startPosition[0] > endPosition[0]) {
action = redStart === 0 ? actions[2] : actions[1];
res = (text === texts.redCar || text === texts.redGun || text === texts.redSoldier || text === texts.redGeneral)
? `${text}${redTexts[startPosition[1]]}${action}${redTexts[redTexts.length - (startPosition[0] - endPosition[0])]}`
: `${text}${redTexts[startPosition[1]]}${action}${redTexts[endPosition[1]]}`;
} else if (startPosition[0] < endPosition[0]) {
action = redStart === 0 ? actions[1] : actions[2];
res = (text === texts.redCar || text === texts.redGun || text === texts.redSoldier || text === texts.redGeneral)
? `${text}${redTexts[startPosition[1]]}${action}${redTexts[redTexts.length - (endPosition[0] - startPosition[0])]}`
: `${text}${redTexts[startPosition[1]]}${action}${redTexts[endPosition[1]]}`;
} else {
action = actions[0];
res = `${text}${redTexts[startPosition[1]]}${action}${redTexts[endPosition[1]]}`;
}
} else if (type === role.black) {
if (startPosition[0] > endPosition[0]) {
action = blackStart === 0 ? actions[2] : actions[1];
res = (text === texts.blackCar || text === texts.blackGun || text === texts.blackSoldier || text === texts.blackGeneral)
? `${text}${blackTexts[startPosition[1]]}${action}${blackTexts[startPosition[0] - endPosition[0] - 1]}`
: `${text}${blackTexts[startPosition[1]]}${action}${blackTexts[endPosition[1]]}`;
} else if (startPosition[0] < endPosition[0]) {
action = blackStart === 0 ? actions[1] : actions[2];
res = (text === texts.blackCar || text === texts.blackGun || text === texts.blackSoldier || text === texts.blackGeneral)
? `${text}${blackTexts[startPosition[1]]}${action}${blackTexts[endPosition[0] - startPosition[0] - 1]}`
: `${text}${blackTexts[startPosition[1]]}${action}${blackTexts[endPosition[1]]}`;
} else {
action = actions[0];
res = `${text}${blackTexts[startPosition[1]]}${action}${blackTexts[endPosition[1]]}`;
}
} else {
}
return res;
}
單元測驗
由于還未撰寫ai演算法,這里只給打譜函式以及絕殺函式撰寫單元測驗,
chessRecord.test.ts:
import Gun from '../tools/gun';
import Horse from '../tools/horse';
import role from '../tools/role';
import text from '../tools/text';
import { chessRecord } from "../tools/chessRecord";
const blackHorse = new Horse(text.blackHorse, role.black);
const redGun = new Gun(text.redGun, role.red);
describe('測驗棋譜', () => {
it('紅炮平動', () => {
expect(chessRecord([7, 1], [7, 4], [9, 0], redGun)).toEqual("炮八平五");
});
it('黑炮前進', () => {
expect(chessRecord([0, 1], [2, 2], [9, 0], blackHorse)).toEqual("馬2進3");
});
});
核心功能優化
落子音效
由于在react中使用audio標簽參考本地音頻檔案很麻煩,所以這里我選擇參考線上的音頻并且使用js動態創建,
playSound.ts:
import settings from "../store/setting";
const url = 'https://www.xiangqiqipu.com/Scripts/game/sounds/';
type SoundName = 'click' | 'move' | 'check' | 'capture' | 'move2' | 'check2' | 'capture2';
export function playSound(name: SoundName) {
if (settings.isUseSound) {
new Audio(`${url}${name}.wav`).play();
}
}
dom解耦
在board.ts中記錄棋盤的各種功能函式與屬性,但是所有有關棋盤dom的繪制全部都在Board.tsx中,
dom解耦沒有想象中的那么簡單,這里面有兩個很棘手的問題: board.ts中如何通知Board.tsx進行重新渲染,如何利用React渲染機制能夠精準控制棋子的渲染(保證棋子流暢的運動特效),
board.ts中如何通知Board.tsx進行重新渲染:這里我采用的方案是回呼函式+useState實作,
核心代碼如下:
const [isRender, setIsRender] = useState(false);
useEffect(() => {
chessBoard.render = () => {
setIsRender(!isRender);
};
}, [chessBoard, isRender]);
給board系結回呼函式,在board每次執行render方法會觸發Board.tsx的setIsRender進而重新渲染當前組件,
如果大佬有更好實作的方式,歡迎留言,
如何利用React渲染機制能夠精準控制棋子的渲染:由于每次跟新棋盤,所有的棋子都要全部重繪,但是實際上我們只操作了一個或者兩個棋子的位置,那么勢必會造成視覺上的影片錯誤,解決方案也很簡單,根據react的渲染對比渲染機制,我們只需要在每次輸出棋子串列前按照固定的順序進行排序即可保證react只重新渲染改變的棋子,
核心代碼如下:
const chesses = useMemo(() => {
const board = chessBoard.idBoard;
const res = [];
for (let i = 0; i < board.length; i++) {
for (let j = 0; j < board[0].length; j++) {
const chess = chessBoard.board[i][j];
const id = board[i][j];
if (chess === role.empty) {
continue;
}
const style: React.CSSProperties = {
color: chess.type === 'red' ? settings.redChessColor : settings.blackChessColor,
marginTop: `${1 + (11.49 * i)}%`,
marginLeft: `${0.5 + (11.56 * j)}%`
};
res.push({
className: `chess ${id === chessBoard.chessSelectId ? 'border' : ''}`,
id: id.toString(),
style,
key: id,
text: chess.text,
});
}
}
// 保證react更精準的更新棋子dom
res.sort((a, b) => a.key - b.key);
// console.log(res);
return res;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [chessBoard, isRender]);
Board.tsx完整代碼:
import React, { useEffect, useMemo, useState } from "react";
import { BoardProps } from '../views/Home';
import settings from "../store/setting";
import Point from "./Point";
import home from "../store/home";
import ChessRecord from "./ChessRecord";
import role from "../tools/role";
import { TextValue } from "../tools/text";
export type PointProps = {
positions: number[][]
};
export type ChessRecordProps = {
isShowPath: boolean;
dataList: string[];
changeShowPath: (flag: boolean) => void;
};
type ChessOptions = {
className: string;
id: string;
style: React.CSSProperties;
key: number;
text: TextValue;
}
export default function Board(props: BoardProps) {
const { isStart, chessBoard, isShowPath, changeShowPath } = props;
const [isRender, setIsRender] = useState(false);
useEffect(() => {
chessBoard.render = () => {
setIsRender(!isRender);
};
}, [chessBoard, isRender]);
const chesses = useMemo(() => {
const board = chessBoard.idBoard;
const res = [];
for (let i = 0; i < board.length; i++) {
for (let j = 0; j < board[0].length; j++) {
const chess = chessBoard.board[i][j];
const id = board[i][j];
if (chess === role.empty) {
continue;
}
const style: React.CSSProperties = {
color: chess.type === 'red' ? settings.redChessColor : settings.blackChessColor,
marginTop: `${1 + (11.49 * i)}%`,
marginLeft: `${0.5 + (11.56 * j)}%`
};
res.push({
className: `chess ${id === chessBoard.chessSelectId ? 'border' : ''}`,
id: id.toString(),
style,
key: id,
text: chess.text,
});
}
}
// 保證react更精準的更新棋子dom
res.sort((a, b) => a.key - b.key);
// console.log(res);
return res;
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [chessBoard, isRender]);
return (
<div id='board' className="board" onClick={(e) => chessBoard.clickHandler(e)}>
{isStart ? chesses.map((option: ChessOptions) => (
<div className={option.className} id={option.id} style={option.style} key={option.key}>{option.text}</div>
)) : <></>}
{home.isShowPoint && isStart && settings.isShowPoint ? <Point positions={chessBoard.positions} /> : <></>}
<ChessRecord isShowPath={isShowPath} changeShowPath={changeShowPath} dataList={chessBoard.chessRecords} />
</div>
);
}
小結
更多有關棋盤以及棋子設計的講述可參看上個版本的文章,
結語
到此,有關此版本的核心功能就介紹完畢,更多細節只能在原始碼中進行體驗,如果對此專案有任何疑問,歡迎評論區留言或者私信我,如果有想法為其添加一些其它新功能或者發現bug也歡迎留言,接下來,我應該會繼續進展ai模塊,下期再會!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/304782.html
標籤:其他
上一篇:解決vue的所有相關問題集合
下一篇:vue.js基礎
