вызов функции внутри компонента - PullRequest
0 голосов
/ 20 января 2020

Я работаю над игрой «Саймон говорит» в качестве моего первого приложения React Native.

Идея состоит в том, чтобы показать игроку последовательность в соответствии с раундом, в котором мы находимся, а затем позволить игроку нажать Кнопка, проверьте, соответствует ли эта кнопка заданному результату, если это так, то дайте пользователю снова нажать, вызывая функцию проверки еще раз. если он сделал хорошо в конце раунда, я увеличиваю раунд et c, а затем снова показываю последовательность. Если игрок терпит неудачу, игра останавливается до тех пор, пока пользователь не нажмет старт снова.

Я не знаю, как установить al oop, который позволит игроку нажимать кнопки, пока раунд не закончится, потому что эта функция вызывается только при нажатии, поэтому я понятия не имею, как им управлять.

Идея состоит в том, чтобы показать игроку последовательность в соответствии с раундом, в котором мы находимся, а затем позволить игроку нажать кнопку, чтобы проверить, эта кнопка соответствует заданному результату, затем пользователь снова нажимает, снова вызывая функцию check. если он все в порядке, то я увеличиваю раунд et c, а затем показываю последовательность снова.

все это должно l oop от 1 раунда до длины последовательности.

есть идеи? мой код ниже. спасибо!

import React, {Component} from 'react';
import {StyleSheet, Text, View,TouchableOpacity, Button, Image} from 'react-native';
export default class App extends Component{ 
  constructor (props){
    super(props);
    this.flash=0
    this.round=1
    this.seq=[] 
    this.playerSeq=[] 
    this.win=false
    this.ok=true
    this.score=0
    this.state = {
      canPress: false,
      greenB: {
        backgroundColor: 'darkgreen'
      },
      yellowB: {
        backgroundColor: 'orange'
      },
      blueB: {
        backgroundColor: 'blue'
      },
      redB: {
        backgroundColor: 'red'
      }
    }
    this.play=this.play.bind(this)
    this.greenFlash=this.greenFlash.bind(this)
    this.blueFlash=this.blueFlash.bind(this)
    this.redFlash=this.redFlash.bind(this)
    this.playerTurn=this.playerTurn.bind(this)
    this.check=this.check.bind(this)
  }

  play(){
    this.seq=[1,2,3,1,4] //will be random, this is just for testing
    this.playerSeq=[] 
    this.flash=0
    this.round=1
    this.win=false
    this.ok=true
    this.score=0
    this.compTurn()
    this.setState({canPress: true})
  } 

  playerTurn(i){
    this.flash=0
    this.playerSeq[this.flash]=i
    this.setState({canPress: false})
    this.check()
  }

  check(){ 
    if (this.playerSeq[this.flash]==this.seq[this.flash]){
      if (this.playerSeq[this.flash]==1){
        this.greenFlash();
      }
      if (this.playerSeq[this.flash]==2){
        this.yellowFlash();
      }
      if (this.playerSeq[this.flash]==3){
        this.blueFlash();
      }
      if (this.playerSeq[this.flash]==4){
        this.redFlash();
      }
      this.flash++
      this.ok=true
      this.setState({canPress: true})
      if (this.flash==this.round){
        this.setState({canPress: false})
        this.round++
        }
      }
      else {
        this.ok=false;
      }
    }

    compTurn() {
      let intervalId = setInterval(()=> {
        if (this.flash==this.round) {
          clearInterval(intervalId);
        }
        else {
          if (this.seq[this.flash]==1){
            this.greenFlash();
          }
          if (this.seq[this.flash]==2){
            this.yellowFlash();
          }
          if (this.seq[this.flash]==3){
            this.blueFlash();
          }
          if (this.seq[this.flash]==4){
            this.redFlash();
          }
          this.flash++;
        }
      }
      , 1500);    
      this.setState({canPress: true})
      this.flash=0;
    }

  compTurn() {
      let intervalId = setInterval(()=> {
        if (this.flash==this.round) {
          clearInterval(intervalId);
        }
        else {
          if (this.seq[this.flash]==1){
            this.greenFlash();
          }
          if (this.seq[this.flash]==2){
            this.yellowFlash();
          }
          if (this.seq[this.flash]==3){
            this.blueFlash();
          }
          if (this.seq[this.flash]==4){
            this.redFlash();
          }
          this.flash++;
        }
      }
      , 1500);  

      this.setState({canPress: true})
      //this.userTurn=true;
      this.flash=0;
  }

  greenFlash(){
      setTimeout(() => {
        this.setState( {
            greenB:{
              ...this.state.style1, backgroundColor: 'lightgreen'
            }
            })
        }, 200);
      setTimeout(() => {
        this.setState( {
            greenB:{
              ...this.state.style1, backgroundColor: 'darkgreen'
            }
            })
        }, 1000);
  } 

  yellowFlash(){
    setTimeout(() => {
      this.setState( {
          yellowB:{
            ...this.state.style1, backgroundColor: 'yellow'
          }
          })
      }, 200);
    setTimeout(() => {
      this.setState( {
          yellowB:{
            ...this.state.style1, backgroundColor: 'orange'
          }
          })
        }, 1000);
  }

  blueFlash(){
    setTimeout(() => {
      this.setState( {
          blueB:{
            ...this.state.style1, backgroundColor: 'lightblue'
          }
          })
      }, 200);
    setTimeout(() => {
      this.setState( {
          blueB:{
            ...this.state.style1, backgroundColor: 'blue'
          }
          })
        }, 1000);
  }

  redFlash(){
    setTimeout(() => {
      this.setState( {
          redB:{
            ...this.state.style1, backgroundColor: 'pink'
          }
          })
      }, 200);
    setTimeout(() => {
      this.setState( {
          redB:{
            ...this.state.style1, backgroundColor: 'red'
          }
          })
        }, 1000);
  }

  render(){
    return (
      <View>
        <TouchableOpacity style={styles.playB}
        onPress={this.play}> 
        <Text style={{
          color:'white',
          height: 30,
          width:60,
          }}>START</Text>
        </TouchableOpacity>
        <TouchableOpacity style={[
          styles.greenB,
          this.state.greenB]} 
          onPress={this.state.canPress ? (()=> this.playerTurn(1)) : null}></TouchableOpacity>
        <TouchableOpacity style={[
          styles.yellowB,
          this.state.yellowB]} 
          onPress={this.state.canPress ? (()=> this.playerTurn(2)) : null}></TouchableOpacity>
        <TouchableOpacity style={[
          styles.blueB,
          this.state.blueB]} 
          onPress={this.state.canPress ? (()=> this.playerTurn(3)) : null}></TouchableOpacity>
        <TouchableOpacity style={[
          styles.redB,
          this.state.redB]} 
          onPress={this.state.canPress ? (()=> this.playerTurn(4)) : null}></TouchableOpacity>

          <Image
            source={{
              uri: 'https://images-eu.ssl-images-amazon.com/images/I/71pyavpLdIL.png'}}
            style={styles.icon}/>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  greenB:{
    padding: 5,
    height: 80,
    width: 80,  
    borderRadius:160,    
    position: 'absolute',
    top:380,
    left: 110
  },
  yellowB:{
    padding: 5,
    height: 80,
    width: 80,  
    borderRadius:160,   
    position: 'absolute',
    left: 110,
    top: 480

  },
  blueB:{
    padding: 5,
    height: 80,
    width: 80,  
    borderRadius:160,   
    position: 'absolute',
    top: 380,
    left: 210

  },
  redB:{
    padding: 5,
    height: 80,
    width: 80,  
    borderRadius:160, 
    position: 'absolute',
    left: 210,
    top: 480

  },
  playB:{
    padding: 10,
    marginLeft: 155,
    marginTop: 300,
    width: 100,
    backgroundColor: 'grey',
    height: 40,
    borderRadius: 40,
  },
  icon: {
    width: 200,
    height: 200,
    position: 'absolute',
    top: 50,
    left: 100, 
  }
});

1 Ответ

1 голос
/ 20 января 2020

Вместо использования canPress состояния, вы должны установить состояние count, каждый раз, когда нажимаете кнопку, увеличивать count с 1 и использовать count для сравнения с seq.length, а затем передавать результат до свойства disabled, например <button disabled={count === seq.length}>.

Вы можете проверить демонстрацию на Codesandbox.

Edit unruffled-black-pt8ie

Также, возможно, этот может дать вам некоторые идеи о функциях l oop как компонент дочерний. https://reactjs.org/docs/jsx-in-depth.html

Код ниже взят из React Docs

// Calls the children callback numTimes to produce a repeated component
function Repeat(props) {
  let items = [];
  for (let i = 0; i < props.numTimes; i++) {
    items.push(props.children(i));
  }
  return <div>{items}</div>;
}

function ListOfTenThings() {
  return (
    <Repeat numTimes={10}>
      {(index) => <div key={index}>This is item {index} in the list</div>}
    </Repeat>
  );
}

Вы можете заключить TouchableOpacity в компонент, как Repeat выше, затем каждый раз игрок начинает новый ход, а затем передает обновленное значение хода как опора TouchableOpacity.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...