用react-native实现一个数独游戏(总结)

前言

  • 最近用react-native做了一个数独游戏的app,到今天基本功能已经全都完成并打包在真机上测试了,这里总结一下开发过程中的一些问题和实现的思路。

环境和平台选择

  • 项目上读取的接口是我自己服务器上部署的,用node实现的接口,链接mysql数据库,数独题目就是从这里读取得到。因为服务器上只有http接口,所以app开发时也就选择的android版本。

功能及实现

  • 因为只是一个简单的demo,做的功能也比较简单:新游戏/继续游戏/选择难度。页面有三个:首页/棋盘页面/关于。
  • 首先在最外层的App.js里引入react-navigation,并配置路由信息,我这里用的其中的DrawerNavigator。
import React, { Component } from 'react'
import {
  Platform,
  StyleSheet,
  Text,
  View
} from 'react-native'

import MainScreen from './components/mainScreen'
import homePage from './components/app'
import aboutScreen from './components/about'
import {
  DrawerNavigator
} from 'react-navigation'

const App = DrawerNavigator({
  Home: {
    screen: homePage,
    navigationOptions: {
      drawerLabel: '主菜单'
    }
  },
  Main: {
    screen: MainScreen
  },
  About: {
    screen: aboutScreen,
    navigationOptions: {
      drawerLabel: '关于'
    }
  }
})

export default App

首页菜单

  • 使用了一个RN自带的picker组件来选择难度,然后选择新游戏时将选择的难度带入到棋盘页面,点击继续时,会判断当前缓存中是否有之前保存的棋盘信息,有的话就直接进入棋盘页面。


    用react-native实现一个数独游戏(总结)_第1张图片
    首页.png
  • 点击关于则是跳转到一个介绍页面,首页暂时就这些。代码如下:
import React, { Component } from 'react'
import deviceStorage from './../common/DeviceStorage'
import {
  StyleSheet,
  Text,
  View,
  TouchableNativeFeedback,
  Picker,
  Alert
} from 'react-native'

export default class App extends Component {
  constructor () {
    super()
    this.state = {
      text: 'Easy',
      select: ''
    }
    deviceStorage.get('difficulty').then(val => {
      // 没有值时,val为null
      if (val) {
        this.setState({
          text: val,
          select: ''
        })
      }
    })

  }
  newGamePress = () => {
    let {text} = this.state
    deviceStorage.save('difficulty', text).then(() => {
      this.props.navigation.navigate('Main', {difficulty: text, newgame: true})
    })
  }
  continuePress = () => {
    deviceStorage.get('Checkerboard').then((arr) => {
      if (arr) {
        this.props.navigation.navigate('Main', {newgame: false})
      } else {
        return Promise.reject()
      }
    }).catch(() => {
      Alert.alert('无法找到之前的记录,重新开始吧~')
    })
    
  }
  aboutPress = () => {
    this.props.navigation.navigate('About')
  }
  render () {
    return (
      
        数独游戏
        
          
            新游戏
          
          
            继续
          
          
            关于
          
          
             this.setState({text: lang})}>
              
              
              
            
          
        
      
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1, 
    flexDirection: 'column'
  },
  homeBtn: {
    width: 250,
    backgroundColor: 'skyblue',
    margin: 20,
    borderRadius: 15,
    textAlign: 'center',
    fontSize: 20
  },
  homeBtnGroup: {
    flex: 1,
    flexDirection: 'column',
    alignItems:'center'
  },
  titleText: {
    fontSize: 20,
    marginTop: 10,
    textAlign:'center'
  }
})

棋盘页面

  • 数独棋盘的生成,是从数据库得到数据(事先存储了几个题目),然后再渲染出来。一开始我是打算随机生成棋盘的,但是发现生成的棋盘可能会出现多解的情况,最后想想还是算了,在网上找了几个数独题目存在数据库里。
  • 用node.js在服务器上写了个接口,根据传入难度从数据库随机取一条该难度的题目返回。服务端只提供题目,结果验证在前端即可完成。


    用react-native实现一个数独游戏(总结)_第2张图片
    image.png
  • 这里交互也很简单,事先为空白的格子才是可选中的,选中后再从下面选择数字或者清空。每次修改后,也将当前棋盘存入到缓存中(其实这样做不是很好,可以监听离开当前页面,再执行存缓存的操作)。
  • 触发提交按钮后,会对棋盘进行验证,有空白没有填完则返回,然后再依次判断各个点是否满足数独条件,判断方法可参考LeetCode上的一道题:Valid Sudoku,答案在这里。
  • 数据存储还是使用的react-native提供的AsyncStorage,并对其进行一层包装。未完成的棋局缓存起来,继续游戏的时候再调用。
   /**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react'
import deviceStorage from './../common/DeviceStorage'
import {
  Text,
  StyleSheet,
  View,
  Button,
  TouchableHighlight,
  Alert
} from 'react-native'

export default class App extends Component {
  constructor () {
    super()
    this.state = {
      arr: [],
      chooseIndex: -1
    }
  }
  componentDidMount () {
    const { params } = this.props.navigation.state
    if (params.newgame) {
      // 新游戏
      fetch(`http://101.200.35.148:8081/sudo/getSudo?difficulty=${params.difficulty}`)
      .then(response => {
        response.json().then(
            // 这里的result就是最终的接口数据了
            (data) => {
              let {result} = data
              this.setState({
                arr: result,
              })
            }
        )
      })
    } else {
      // 继续游戏
      deviceStorage.get('Checkerboard').then((arr) => {
        this.setState({arr})
      })
    }
  }
  renderArr = () => {
    let {arr, chooseIndex} = this.state
    return arr.map((item, index) => {
      if (typeof item == "string") {
        return (
          
             {this.pressAction(ev, index)}}>
              {item === '' ? ' ' : item}
            
          
        )      
      } else {
        return (
          
            {item}
          
        )
      }
    })
  }
  pressAction = (ev, index) => {
    this.setState({
      chooseIndex: index
    })
  }
  judgeResult = () => {
    let arr = this.state.arr
    let dp = {}
    let index = 0
    for (let a = 0; a < 3; a++) {
      for (let b = 0; b < 3; b++) {
        dp[`area${a}${b}`] = new Map()
      }
    }
    for (let i = 0; i < 9; i++) {
      dp[`x${i}`] = new Map()
      dp[`y${i}`] = new Map()
    }
    for (let i = 0; i < 9; i++) {
      for (let j = 0; j < 9; j++) {
        let temp = arr[index]
        if (temp !== '') {
          let xIndex = 'x' + j
          let yIndex = 'y' + i
          let areaIndex = 'area' + Math.floor(j/3) + Math.floor(i/3)
          if (dp[xIndex].has(temp) || dp[yIndex].has(temp) || dp[areaIndex].has(temp)) {
            return [false, '有空格填错了哦~', index]
          } else {
            dp[xIndex].set(temp, true)
            dp[yIndex].set(temp, true)
            dp[areaIndex].set(temp, true)
          }
        } else {
          return [false, '还有空格没填完哦~']
        }
        index++
      }
    }
    return [true]
  }
  selectAction = (ev, item) => {
    let {arr, chooseIndex} = this.state
    arr[chooseIndex] = item
    deviceStorage.save('Checkerboard', arr).then(() => {})
    this.setState({arr})
  }
  cleanAction = () => {
    let {arr, chooseIndex} = this.state
    if (chooseIndex === -1) {
      return
    }
    arr[chooseIndex] = ''
    this.setState({arr})
  }
  submitAction = () => {
    let {arr} = this.state
    let result = this.judgeResult()
    if (result[0]) {
      Alert.alert(
        '完成~'
      )
      deviceStorage.delete('Checkerboard')
      this.props.navigation.navigate('Home')
    } else {
      Alert.alert(
        result[1]
      )
      if (result[2]) {
        this.setState({
          chooseIndex: result[2]
        })
      }
    }
  }
  render () {
    return (
      
        
          mainScreen
          
            {this.renderArr()}
            
            
            
            
          
        
        
          {
            ['1','2','3','4','5','6','7','8','9'].map((item, index) => {
              return (
                
                   {this.selectAction(ev, item)}}>
                    {item}
                  
                
              )
            })
          }
          
            
              

你可能感兴趣的:(用react-native实现一个数独游戏(总结))