Commit 762f2c82 authored by liangyuetong's avatar liangyuetong

优化

parent ee0e7ba2
This diff is collapsed.
export const calcWinner = (item) => {
const array = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6]
]
let rst = '';
array.map(items => {
let [a, b, c] = items;
if (item[a] && item[b] && item[c]) {
if (item[a] === item[b] && item[c] === item[b]) {
rst = item[a];
return rst;
}
}
return rst;
})
return rst;
}
\ No newline at end of file
import React, { Component, Children } from 'react';
import { Layout } from 'antd';
const {Content} = Layout;
class Container extends Component {
render() {
return (
<Layout>
<Content>
{Children}
</Content>
</Layout>
)
}
}
export default Container;
...@@ -9,7 +9,7 @@ const app = dva(); ...@@ -9,7 +9,7 @@ const app = dva();
// app.use({}); // app.use({});
// 3. Model // 3. Model
app.model(require('./models/container').default); app.model(require('./models/board').default);
// 4. Router // 4. Router
app.router(require('./router').default); app.router(require('./router').default);
......
export default {
nameSpace: 'app',
state: {
switchKeys: ''
},
effect: {},
subscription: {},
reducers: {
updateState(state, { payload }) {
return {
...state,
...payload
}
}
},
}
\ No newline at end of file
import { calcWinner } from '../assets/utils';
export default { export default {
namespace: 'con', namespace: 'con',
state: { state: {
playerValue: 'x',// x or o playerValue: 'x',// x or o
record: [], records: [new Array(9).fill(null)],
step: 0, step: 0,
winner: '', winner: '',
history: '' coordinate: []
}, },
subscriptions: { subscriptions: {
...@@ -27,37 +27,57 @@ export default { ...@@ -27,37 +27,57 @@ export default {
// *isComplete() { // *isComplete() {
// } // }
// *fetch({ payload }, { call, put }) { // eslint-disable-line *fetch({ payload }, { call, put, select }) { // eslint-disable-line
// yield put({ type: 'save' }); const { step: newStep, records: newRecords, coordinate: newCoordinate } = payload
// }, const { step: oldStep, records: oldRecords, coordinate: oldCoordinate } = yield select((state) => state.con);
const func = (item, stepNum) => {
let temp = JSON.parse(JSON.stringify(item));
temp = newStep === oldRecords.length ? temp : temp.slice(0, stepNum)
return temp;
}
let oldCd = func(oldCoordinate, oldStep)
let oldRc = func(oldRecords, newStep)
let tmp = JSON.parse(JSON.stringify([newRecords]))
const winner = calcWinner(...tmp)
yield put({
type: 'updateState', payload: {
records: oldRc.concat(tmp),
step: newStep,
playerValue: oldStep % 2 === 0 ? 'o' : 'x',
winner,
coordinate: oldCd.concat({ step: newStep, coordinate: newCoordinate })
}
});
},
}, },
reducers: { reducers: {
updateState(state, action) { updateState(state, { payload }) {
return { ...state, ...action.payload };
},
checkMate(state, action) {
return { return {
...state, ...state,
winner: action.winner ...payload
} };
}, },
reset(state) { reset(state) {
return { return {
...state, ...state,
playerValue: 'x',// x or o playerValue: 'x',// x or o
record: [], records: [new Array(9).fill(null)],
step: 0, step: 0,
winner: '' winner: '',
coordinate: []
} }
}, },
goBack(state, action) { goBack(state, { payload }) {
const { step, playerValue } = payload;
const { records } = state;
return { return {
...state, ...state,
...action.payload winner: calcWinner(records[step]),
playerValue,
step
} }
} }
}, },
}; };
import React from 'react'; import React from 'react';
import { Router, Route, Switch } from 'dva/router'; import { Router, Route, Switch } from 'dva/router';
import Container from './routes/Container'; import Index from './routes/Index';
function RouterConfig({ history }) { function RouterConfig({ history }) {
return ( return (
<Router history={history}> <Router history={history}>
<Switch> <Switch>
<Route path="/con" exact component={Container} /> <Route path="/con" exact component={Index} />
</Switch> </Switch>
</Router> </Router>
); );
......
import React from 'react'; import React from 'react';
import { connect } from 'dva'; import { connect } from 'dva';
import styles from './container.css'; import styles from './board.css';
import Square from '../components/Square'; import Square from '../components/Square';
import RecordTable from '../components/RecordTable';
import { Button } from 'antd'; import { Button } from 'antd';
function Board({ dispatch, con }) {
function Container({ dispatch, con }) { const { playerValue, records, step, winner } = con;
const { playerValue, record, step, winner } = con;
const latestMove = step === 0 ? new Array(9).fill(null) : record[step - 1].records;
const array = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6]
]
const calcWinner = (item) => {
let rst = '';
array.map(items => {
let [a, b, c] = items;
if (item[a] && item[b] && item[c]) {
if (item[a] === item[b] && item[c] === item[b]) {
rst = item[a];
return rst;
}
}
return rst;
})
return rst;
}
const mapSquare = (item, index, row) => { const mapSquare = (item, index, row) => {
let chess = [];
const play = (index, row) => { const play = (index, row) => {
if (winner === '') { if (winner === '') {
let next = step % 2 === 0 ? 'o' : 'x';
let newArr = step === 0 ? new Array(9).fill(null) : Object.assign([], record[step - 1].records);//备份数组用作后续修改
const handlerChange = (arr) => { const handlerChange = (arr) => {
dispatch({ dispatch({
type: 'con/updateState', type: 'con/fetch',
payload: { payload: {
playerValue: next, coordinate: `[${row}, ${index}]`,
record: step === record.length ? record.concat({ records: arr,
step: step + 1,
coordinate: `[${row}, ${index}]`,
records: chess.concat(arr)
}) : record.slice(0, step).concat({
step: step + 1,
coordinate: `[${row}, ${index}]`,
records: chess.slice(0, step).concat(arr)
}),
step: step + 1 step: step + 1
} }
}) })
if (calcWinner(arr) !== '') {
dispatch({
type: 'con/checkMate',
winner: calcWinner(arr)
})
}
} }
let newArr = JSON.parse(JSON.stringify(records));
const latestMove = newArr[step];
switch (row) { switch (row) {
case 0: case 0:
if (latestMove[index] !== null) { if (latestMove[index] !== null) {
alert('这个位置被占啦,换个地方吧~') alert('这个位置被占啦,换个地方吧~')
} else { } else {
newArr.splice(index, 1, playerValue); newArr[step].splice(index, 1, playerValue);
handlerChange(newArr); handlerChange(newArr[step]);
} }
break; break;
case 1: case 1:
if (latestMove[index + 3] !== null) { if (latestMove[index + 3] !== null) {
alert('这个位置被占啦,换个地方吧~') alert('这个位置被占啦,换个地方吧~')
} else { } else {
newArr.splice(index + 3, 1, playerValue);; newArr[step].splice(index + 3, 1, playerValue);
handlerChange(newArr); handlerChange(newArr[step]);
} }
break; break;
case 2: case 2:
if (latestMove[index + 6] !== null) { if (latestMove[index + 6] !== null) {
alert('这个位置被占啦,换个地方吧~') alert('这个位置被占啦,换个地方吧~')
} else { } else {
newArr.splice(index + 6, 1, playerValue);; newArr[step].splice(index + 6, 1, playerValue);
handlerChange(newArr); handlerChange(newArr[step]);
} }
break; break;
default: default:
break; break;
} }
// 坐标 00 01 02,10 11 12,20 21 22,00 10 20,01 11 21, 02 10 22,00 11 22,02 11 20
// 行 数组下标
// 0 1 2,3 4 5,6 7 8, 0 3 6, 1 4 7, 2 5 8, 0 4 8, 2 4 6
} else { } else {
alert('你已经赢了,再来一局吧~') alert('你已经赢了,再来一局吧~')
return; return;
...@@ -104,45 +58,11 @@ function Container({ dispatch, con }) { ...@@ -104,45 +58,11 @@ function Container({ dispatch, con }) {
return <Square key={index} value={item} onClick={() => play(index, row)} /> return <Square key={index} value={item} onClick={() => play(index, row)} />
} }
const reset = () => { const reset = () => {
dispatch({ dispatch({type: 'con/reset'})
type: 'con/reset',
// payload: {
// playerValue: 'x',// x or o
// record: [],
// step: 0,
// winner: ''
// }
})
} }
const recall = (records, index) => { const chessArr = records[step];
let next = index % 2 === 0 ? 'o' : 'x';
// console.log(index)
dispatch({
type: 'con/goBack',
payload: {
winner: calcWinner(records.records),
step: index + 1,
playerValue: next
}
})
}
const column = [
{
title: '步数',
key: 'step',
dataIndex: 'step',
render: (text, records, index) => <Button className={styles.step} onClick={() => recall(records, index)}>{text}</Button>
},
{
title: '坐标',
key: 'coordinate',
dataIndex: 'coordinate'
}
]
const chessArr = step === 0 ? new Array(9).fill(null) : record[step - 1].records;
return ( return (
<div className={styles.container}> <div className={styles.board}>
<div className={styles.normal}> <div className={styles.normal}>
<div className={styles.header}>the next player is: {playerValue}</div> <div className={styles.header}>the next player is: {playerValue}</div>
<div>{chessArr.slice(0, 3).map((item, index) => mapSquare(item, index, 0))}</div> <div>{chessArr.slice(0, 3).map((item, index) => mapSquare(item, index, 0))}</div>
...@@ -151,9 +71,6 @@ function Container({ dispatch, con }) { ...@@ -151,9 +71,6 @@ function Container({ dispatch, con }) {
<Button onClick={() => reset()}>重新开始</Button> <Button onClick={() => reset()}>重新开始</Button>
<div>the winner is: {winner}</div> <div>the winner is: {winner}</div>
</div> </div>
<div className={styles.table}>
<RecordTable column={column} data={record} />
</div>
</div> </div>
); );
} }
...@@ -161,4 +78,4 @@ function Container({ dispatch, con }) { ...@@ -161,4 +78,4 @@ function Container({ dispatch, con }) {
// IndexPage.propTypes = { // IndexPage.propTypes = {
// }; // };
export default connect(({ con }) => ({ con }))(Container); export default connect(({ con }) => ({ con }))(Board);
import React from 'react';
import { connect } from 'dva';
import Board from './Board';
import styles from './board.css';
import { Button } from 'antd';
import RecordTable from '../components/RecordTable';
const Index = ({ dispatch, con }) => {
const { coordinate } = con;
const recall = (records, index) => {
let next = index % 2 === 0 ? 'o' : 'x';
dispatch({
type: 'con/goBack',
payload: {
step: index + 1,
playerValue: next
}
})
}
const column = [
{
title: '步数',
key: 'step',
dataIndex: 'step',
render: (text, records, index) => <Button className={styles.step} onClick={() => recall(records, index)}>{text}</Button>
},
{
title: '坐标',
key: 'coordinate',
dataIndex: 'coordinate'
}
]
return (
<div style={{width: '100%',display: 'inline-block'}}>
<Board />
<div className={styles.table}>
<RecordTable column={column} data={coordinate} />
</div>
</div>
)
}
export default connect(({ con }) => ({ con }))(Index)
.container { .board {
width: 100%; width: 50%;
height: 400px; height: 400px;
display: inline-block;
} }
.normal { .normal {
......
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment