美文网首页
用react-native实现一个数独游戏(总结)

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

作者: ITgecko | 来源:发表于2017-12-20 13:51 被阅读0次

    前言

    • 最近用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组件来选择难度,然后选择新游戏时将选择的难度带入到棋盘页面,点击继续时,会判断当前缓存中是否有之前保存的棋盘信息,有的话就直接进入棋盘页面。


      首页.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 (
          <View style={styles.container}>
            <Text style={styles.titleText}>数独游戏</Text>
            <View style={styles.homeBtnGroup}>
              <TouchableNativeFeedback onPress={this.newGamePress}>
                <Text style={styles.homeBtn}>新游戏</Text>
              </TouchableNativeFeedback>
              <TouchableNativeFeedback onPress={this.continuePress}>
                <Text style={styles.homeBtn}>继续</Text>
              </TouchableNativeFeedback>
              <TouchableNativeFeedback onPress={this.aboutPress}>
                <Text style={styles.homeBtn}>关于</Text>
              </TouchableNativeFeedback>
              <View style={{width: 250, backgroundColor:'skyblue',margin:15,borderRadius: 15}}>
                <Picker
                  selectedValue={this.state.text}
                  onValueChange={(lang) => this.setState({text: lang})}>
                  <Picker.Item label="简单" value="Easy" />
                  <Picker.Item label="中等" value="Medium" />
                  <Picker.Item label="困难" value="Hard" />
                </Picker>
              </View>
            </View>
          </View>
        )
      }
    }
    
    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在服务器上写了个接口,根据传入难度从数据库随机取一条该难度的题目返回。服务端只提供题目,结果验证在前端即可完成。


      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 (
              <View key={index} style={chooseIndex == index ? styles.bChoosen : styles.bRow}>
                <TouchableHighlight onPress={(ev) => {this.pressAction(ev, index)}}>
                  <Text style={styles.editableText}>{item === '' ? ' ' : item}</Text>
                </TouchableHighlight>
              </View>
            )      
          } else {
            return (
              <View key={index} style={styles.bRow}>
                <Text style={styles.text}>{item}</Text>
              </View>
            )
          }
        })
      }
      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 (
          <View>
            <View style={styles.container}>
              <Text>mainScreen</Text>
              <View style={styles.MScontainer}>
                {this.renderArr()}
                <View style={styles.borderView1}></View>
                <View style={styles.borderView2}></View>
                <View style={styles.borderView3}></View>
                <View style={styles.borderView4}></View>
              </View>
            </View>
            <View style={styles.bottomContainer}>
              {
                ['1','2','3','4','5','6','7','8','9'].map((item, index) => {
                  return (
                    <View key={index} style={styles.bottomSpan}>
                      <TouchableHighlight onPress={(ev) => {this.selectAction(ev, item)}}>
                        <Text style={styles.text}>{item}</Text>
                      </TouchableHighlight>
                    </View>
                  )
                })
              }
              <View style={styles.bottomContainer2}>
                <View style={styles.buttonStyle}>
                  <Button
                    onPress={this.cleanAction}
                    title="清空"
                    color="#841584"
                  />            
                </View>
                <View style={styles.buttonStyle}>
                  <Button
                    onPress={this.submitAction}
                    title="提交"
                    color="#841584"
                  />            
                </View>
              </View>
            </View>
          </View>
        )
      }
    }
    
    const styles = StyleSheet.create({
      container: {
        flex: 1,
        alignItems: 'center',
      },
      MScontainer: {
        flex: 1,
        flexWrap: 'wrap',
        width: 360,
        flexDirection: 'row',
        margin: 10
      },
      borderView1: {
        position: 'absolute',
        top: 120,
        left: 0,
        width: 360,
        height: 0,
        borderColor: 'black',
        borderStyle: 'solid',
        borderWidth: 1.5,
      },
      borderView2: {
        position: 'absolute',
        top: 240,
        left: 0,
        width: 360,
        height: 0,
        borderColor: 'black',
        borderStyle: 'solid',
        borderWidth: 1.5,
      },
      borderView3: {
        position: 'absolute',
        top: 0,
        left: 120,
        width: 0,
        height: 360,
        borderColor: 'black',
        borderStyle: 'solid',
        borderWidth: 1.5,
      },
      borderView4: {
        position: 'absolute',
        top: 0,
        left: 240,
        width: 0,
        height: 360,
        borderColor: 'black',
        borderStyle: 'solid',
        borderWidth: 1.5,
      },
      bottomContainer: {
        flex: 1,
        marginTop: 450,
        width: 360,
        flexDirection: 'row',
        alignItems: 'center'
      },
      bottomContainer2: {
        position: 'absolute',
        top: 20,
        flex: 1,
        flexDirection: 'row',
      },
      buttonStyle: {
        margin: 10,
        width: 70,
        height: 50
      },
      bottomSpan: {
        margin: 5,
        width: 35,
        height: 35,
        borderColor: 'skyblue',
        borderStyle: 'solid',
        borderWidth: 1,
        borderRadius: 5
      },
      bRow: {
        width: 40,
        height: 40,
        borderColor: 'skyblue',
        borderStyle: 'solid',
        borderWidth: 1
      },
      bChoosen: {
        width: 40,
        height: 40,
        borderColor: 'crimson',
        borderStyle: 'solid',
        borderWidth: 2
      },
      text: {
        textAlign: 'center',
        fontSize: 25
      },
      editableText: {
        textAlign: 'center',
        fontSize: 25,
        color: 'green'
      }
    })
    
    

    相关文章

      网友评论

          本文标题:用react-native实现一个数独游戏(总结)

          本文链接:https://www.haomeiwen.com/subject/cagaixtx.html