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


    首页.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'
  }
})

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 162,050评论 4 370
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 68,538评论 1 306
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 111,673评论 0 254
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,622评论 0 218
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 53,047评论 3 295
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,974评论 1 224
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 32,129评论 2 317
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,893评论 0 209
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,654评论 1 250
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,828评论 2 254
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,297评论 1 265
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,619评论 3 262
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,326评论 3 243
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,176评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,975评论 0 201
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 36,118评论 2 285
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,909评论 2 278

推荐阅读更多精彩内容