Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel is required to process package imports. If you need a different preprocessor remove all packages first.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import or require. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              body {
  margin: 0;
}

#root {
  min-width: 100vw;
  min-height: 100vh;
  height: calc(100vw + 500px);
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-pack: center;
      -ms-flex-pack: center;
          justify-content: center;
  -webkit-box-align: center;
      -ms-flex-align: center;
          align-items: center;
  background: #f3f3f3;
}

@media (min-width: 530px) {
  #root {
    height: 770px;
  }
}

.simon-game {
  width: calc(100vw - 30px);
  max-width: 500px;
  height: calc(100vw - 30px);
  max-height: 500px;
  position: relative;
  border-radius: 50%;
  font-family: sans-serif;
}

.simon-game__buttons {
  width: 100%;
  height: 100%;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -ms-flex-wrap: wrap;
  flex-wrap: wrap;
  border-radius: 50%;
}

button {
  outline: none;
  cursor: pointer;
}

.simon-game__button {
  width: 50%;
  height: 50%;
  border: 10px solid #141318;
  margin: 0;
}

.simon-game__button--0 {
  border-top-width: 20px;
  border-left-width: 20px;
  border-top-left-radius: 100%;
  background: #2dbd4e;
}

.simon-game__button--0.is-lit {
  background: #33ff88;
}

.simon-game__button--1 {
  border-top-width: 20px;
  border-right-width: 20px;
  border-top-right-radius: 100%;
  background: #f83a08;
}

.simon-game__button--1.is-lit {
  background: #ff7257;
}

.simon-game__button--2 {
  border-bottom-width: 20px;
  border-left-width: 20px;
  border-bottom-left-radius: 100%;
  background: #e9d72b;
}

.simon-game__button--2.is-lit {
  background: #ffff66;
}

.simon-game__button--3 {
  border-bottom-width: 20px;
  border-right-width: 20px;
  border-bottom-right-radius: 100%;
  background: #2484e8;
}

.simon-game__button--3.is-lit {
  background: #33f1ff;
}

.simon-game__settings {
  width: 225px;
  height: 225px;
  position: absolute;
  left: 50%;
  top: -130px;
  -webkit-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
  border-radius: 50%;
  background: #141318;
  text-align: center;
}

@media (min-width: 530px) {
  .simon-game__settings {
    top: 50%;
  }
}

.simon-game__heading {
  display: inline-block;
  position: relative;
  margin: 32px 0 0;
  text-align: center;
  font-family: 'Audiowide', sans-serif;
  font-size: 40px;
  font-weight: 400;
  color: #fff;
}

.simon-game__heading > sub {
  position: absolute;
  right: -17px;
  bottom: 2px;
  margin: 0;
  font-size: 24px;
}

.simon-game__settings-middle-row {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-pack: center;
      -ms-flex-pack: center;
          justify-content: center;
  -webkit-box-align: end;
      -ms-flex-align: end;
          align-items: flex-end;
}

.simon-game__settings-group {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
      -ms-flex-direction: column;
          flex-direction: column;
  -webkit-box-pack: end;
      -ms-flex-pack: end;
          justify-content: flex-end;
  -webkit-box-align: center;
      -ms-flex-align: center;
          align-items: center;
  text-align: center;
}

.simon-game__settings-count-display {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-pack: center;
  -ms-flex-pack: center;
  justify-content: center;
  -webkit-box-align: center;
  -ms-flex-align: center;
  align-items: center;
  width: 70px;
  height: 45px;
  border-radius: 5px;
  background: #380f14;
  font-size: 24px;
  letter-spacing: 0.1em;
  color: #cd4e5d;
}

.simon-game__settings-label {
  display: inline-block;
  margin: 8px 0 12px;
  font-size: 12px;
  text-transform: uppercase;
  color: #fff;
}

.simon-game__settings-group--start-button {
  margin-left: 15px;
  margin-right: 15px;
}

.simon-game__settings-button {
  width: 30px;
  height: 30px;
  border: none;
  border-radius: 50%;
}

.simon-game__settings-button--start {
  margin-bottom: 7px;
  background: #50bb43;
}

.simon-game__settings-strict-mode-indicator {
  width: 10px;
  height:10px;
  border: 2px solid #380f14;
  border-radius: 50%;
  margin-bottom: 5px;
  background: #380f14;
}

.simon-game__settings-strict-mode-indicator.is-lit {
  background: #cd4e5d;
}

.simon-game__settings-button--strict {
  margin-bottom: 7px;
  background: #f2df49;
}

.simon-game__settings-bottom-row {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-pack: center;
      -ms-flex-pack: center;
          justify-content: center;
  -webkit-box-align: center;
      -ms-flex-align: center;
          align-items: center;
}

.simon-game__settings-power-button {
  position: relative;
  width: 66px;
  height: 30px;
  border: none;
  margin-left: 8px;
  margin-right: 8px;
  background: #333;
}

.simon-game__settings-power-button:before {
  content: '';
  display: block;
  width: 30px;
  height: 24px;
  position: absolute;
  left: 3px;
  top: 3px;
  background: #0b6bcf;
  transition: left 0.3s ease;
}

.simon-game__settings-power-button.is-on:before {
  left: 33px;
}

.simon-game__settings-bottom-row-label {
  font-size: 12px;
  text-transform: uppercase;
  color: #fff;
}

.simon-game__instructions {
  margin-top: 2em;
  text-align: center;
}

.simon-game__attribution {
  width: 100vw;
  position: absolute;
  left: 50%;
  bottom: -60px;
  -webkit-transform: translate(-50%, 100%);
  -ms-transform: translate(-50%, 100%);
  transform: translate(-50%, 100%);
  box-sizing: border-box;
  padding-left: 15px;
  padding-right: 15px;
  background: #f3f3f3;
  text-align: center;
  font-size: 14px;
  line-height: 1.4;
}

.simon-game__attribution-line > a {
  color: #002171;
}

            
          
!
            
              const { createContext, useContext, useReducer, useRef, useEffect, useCallback } = React;
const MAX_SERIES = 20;
let timers = [];
const sounds = Array(4).fill(null).map((val, i) => new Audio(`https://s3.amazonaws.com/freecodecamp/simonSound${i + 1}.mp3`));
sounds.push(new Audio('https://s3.us-east-2.amazonaws.com/vitamindigitalmediaassets/Wrong-answer-sound-effect.mp3'));
sounds.push(new Audio('https://s3.us-east-2.amazonaws.com/vitamindigitalmediaassets/ta-da.mp3'));
const GameContext = createContext({
  state: null,
  dispatch: null,
  handleClick: () => {},
  handleStartButtonClick: () => {},
});

const generateSeries = () => new Array(MAX_SERIES).fill(null).map(item => (
  Math.floor(Math.random() * 4)
));

const reducer = (state, action) => {
  switch (action.type) {
    case 'TURN_ON':
      return {
        ...state,
        isOn: true,
      };
    
    case 'TURN_OFF':
      return {
        ...state,
        isOn: false,
      };
    
    case 'START_PLAYING':
      return {
        ...state,
        isPlaying: true,
      };
    
    case 'STOP_PLAYING':
      return {
        ...state,
        isPlaying: false,
      };
    
    case 'SET_STRICT_MODE':
      return {
        ...state,
        isStrictMode: true,
      };
    
    case 'SET_NORMAL_MODE':
      return {
        ...state,
        isStrictMode: false,
      };
    
    case 'SET_PLAYERS_TURN':
      return {
        ...state,
        isPlayersTurn: true,
      };
    
    case 'SET_COMPUTERS_TURN':
      return {
        ...state,
        isPlayersTurn: false,
      };
    
    case 'SET_COUNT':
      return {
        ...state,
        count: action.payload,
      };
    
    case 'CREATE_NEW_SERIES':
      return {
        ...state,
        series: generateSeries(),
      };
    
    case 'SET_CLICKED_SERIES':
      return {
        ...state,
        clickedSeries: action.payload,
      };
    
    case 'SET_LIT_BUTTON_INDEX':
      return {
        ...state,
        litButtonIndex: action.payload,
      };
    
    case 'SET_IS_INCORRECT':
      return {
        ...state,
        isIncorrect: true,
      };
      
    case 'SET_IS_INCORRECT_IF_IDLE_WITHOUT_CLICK':
      return {
        ...state,
        isIncorrect: state.isPlayersTurn && state.clickedSeries.length === 0,
      };
      
    case 'SET_IS_INCORRECT_IF_IDLE_AFTER_CLICK':
      return {
        ...state,
        isIncorrect: state.isPlayersTurn && state.clickedSeries.length === action.payload + 1,
      };
      
    case 'SET_IS_INCORRECT_IF_INCORRECT':
      return {
        ...state,
        isIncorrect: state.isPlayersTurn && state.clickedSeries.join('') !== state.series.slice(0, state.clickedSeries.length).join(''),
      };
    
    case 'SET_IS_CORRECT':
      return {
        ...state,
        isIncorrect: false,
      };
      
    case 'MARK_CELEBRATED':
      return {
        ...state,
        celebrated: true,
      };
      
    case 'UNMARK_CELEBRATED':
      return {
        ...state,
        celebrated: false,
      };
    
    default:
      return state;
  }
};

const INITIAL_STATE = {
  isOn: false,
  isPlaying: false,
  isStrictMode: false,
  isPlayersTurn: false,
  count: 1,
  series: generateSeries(),
  clickedSeries: [],
  litButtonIndex: null,
  isIncorrect: false,
  celebrated: false,
};

const SimonGame = () => {
  const [state, dispatch] = useReducer(reducer, INITIAL_STATE);
  const indicateErrorIfIdleWithoutClick = useCallback(() => {
    timers.push(setTimeout(() => {
      dispatch({
        type: 'SET_IS_INCORRECT_IF_IDLE_WITHOUT_CLICK',
      });
    }, 5000));
  }, []);
  
  const indicateClick = useCallback(i => {
    if (!state.isOn || !state.isPlaying) {
      return;
    }
    
    dispatch({
      type: 'SET_LIT_BUTTON_INDEX',
      payload: i,
    });
    
    sounds[i].play();
  }, [state.isOn, state.isPlaying]);
  
  const clickAtInterval = useCallback(i => {
    const { isOn, isPlaying, series, count } = state;
    if (!isOn || !isPlaying || count > MAX_SERIES) {
      return;
    }
            
    const thisSeries = series.slice(0, count);
    if (i === thisSeries.length) {
      dispatch({
        type: 'SET_PLAYERS_TURN',
      });
    } else {
      timers.push(setTimeout(() => {
        indicateClick(thisSeries[i++]);
        timers.push(setTimeout(() => {
          dispatch({
            type: 'SET_LIT_BUTTON_INDEX',
            payload: null,
          });
          
          clickAtInterval(i);
        }, 500));
      }, 350));
    }
  }, [state.isOn, state.isPlaying, state.series, state.count, indicateClick]);
  
  const runSeries = useCallback(count => {
    if (state.isOn && state.isPlaying && count <= MAX_SERIES) {
      console.log('rs', count)
      dispatch({
        type: 'SET_COMPUTERS_TURN',
      });
   
      timers.push(setTimeout(() => {
        dispatch({
          type: 'SET_IS_CORRECT',
        });
        
        clickAtInterval(0);
      }, 3000));
    }
  }, [state.isOn, state.isPlaying, clickAtInterval]);
  
  const clearTimers = useCallback(() => {
    timers.forEach(timer => clearTimeout(timer));
    timers = [];
  }, []);
  
  const indicateErrorIfIdleAfterClick = useCallback(oldClickedSeriesLength => {
    timers.push(setTimeout(() => {
      dispatch({
        type: 'SET_IS_INCORRECT_IF_IDLE_AFTER_CLICK',
        payload: oldClickedSeriesLength,
      });
    }, 5000));
  }, []);
  
  const generateNewSettingsForErrorInStrictMode = useCallback(() => {
    dispatch({ type: 'SET_COMPUTERS_TURN' });
    dispatch({ type: 'CREATE_NEW_SERIES' });
    dispatch({ type: 'SET_COUNT', payload: 1 });
    dispatch({ type: 'UNMARK_CELEBRATED' });
    dispatch({ type: 'SET_CLICKED_SERIES', payload: [] });
    dispatch({ type: 'SET_LIT_BUTTON_INDEX', payload: null });
  }, []);
  
  const handleClick = i => {
    const { isOn, isPlaying, isPlayersTurn, clickedSeries } = state;
    if (isOn && isPlaying && isPlayersTurn) {
      clearTimers();
      indicateClick(i);
      timers.push(setTimeout(() => {
        dispatch({
          type: 'SET_CLICKED_SERIES',
          payload: [...clickedSeries, i],
        });
        
        dispatch({
          type: 'SET_LIT_BUTTON_INDEX',
          payload: null,
        });        
        indicateErrorIfIdleAfterClick(clickedSeries.length);
      }, 350));
    }
  };
  
  const generateNewSettings = useCallback(() => {
    generateNewSettingsForErrorInStrictMode();
    dispatch({ type: 'SET_IS_CORRECT' });
  }, [generateNewSettingsForErrorInStrictMode]);
  
  const indicateError = useCallback(() => {
    sounds[4].play();
  }, []);  
  
  const indicateErrorAndRestartInStrictMode = useCallback(() => {
    if (state.isStrictMode) {
      clearTimers();
      indicateError();
      generateNewSettingsForErrorInStrictMode();      
    }
  }, [state.isStrictMode, clearTimers, indicateError, generateNewSettingsForErrorInStrictMode]);
  
  const repeatSeries = useCallback(() => {
    dispatch({
      type: 'SET_CLICKED_SERIES',
      payload: [],
    });
  }, []);
  
  const indicateErrorAndRepeatSeriesInNonStrictMode = useCallback(() => {
    if (!state.isStrictMode) {
      clearTimers();
      indicateError();
      repeatSeries();
    }
  }, [state.isStrictMode, clearTimers, indicateError, repeatSeries]);
  
  const indicateErrorIfIncorrect = useCallback(() => {
    dispatch({ type: 'SET_IS_INCORRECT_IF_INCORRECT' });
  }, []);
  
  const startNextSeriesIfCorrect = useCallback(() => {
    const { clickedSeries, count, series } = state;
    if (clickedSeries.length === count && series.slice(0, count).join('') === clickedSeries.join('')) {
      clearTimers();
      dispatch({ type: 'SET_COUNT', payload: count + 1 });
      dispatch({ type: 'SET_CLICKED_SERIES', payload: [] });
    } 
  }, [state.clickedSeries, state.count, state.series, clearTimers]);
  
  const startGame = () => {
    dispatch({ type: 'START_PLAYING' });
    dispatch({ type: 'SET_COUNT', payload: 1 });
  };
  
  const restartGame = useCallback(() => {
    clearTimers();
    generateNewSettings();
  }, [clearTimers, generateNewSettings]);
  
  const celebrateIfGameWonAndRestart = useCallback(count => {
    const { series, celebrated } = state;
    if (count === MAX_SERIES + 1 && !celebrated) {
      let intervalId = setInterval(() => {
        dispatch({
          type: 'SET_LIT_BUTTON_INDEX',
          payload: null,
        });
        
        timers.push(setTimeout(() => {
          dispatch({
            type: 'SET_LIT_BUTTON_INDEX',
            payload: series[series.length - 1],
          });
          
          dispatch({
            type: 'MARK_CELEBRATED',
          });
        }, 175));
      }, 350);
      
      sounds[5].play();
      timers.push(setTimeout(() => {
        clearInterval(intervalId);
        restartGame();
      }, 3000));
    }
  }, [state.series, state.celebrated, restartGame]);
  
  const handleStartButtonClick = () => {
    const { isOn, isPlaying } = state;
    if (isOn && !isPlaying) {
      startGame();
    } else if (isOn) {
      restartGame();
    }
  };
  
  const toggleIsLitClassForStrictModeIndicator = () => {
    return state.isStrictMode ? ' is-lit' : '';
  };
  
  const handleStrictModeButtonClick = () => {
    const { isOn, isStrictMode } = state; 
    if (isOn) {
      if (isStrictMode) {
        dispatch({ type: 'SET_NORMAL_MODE' });
      } else {
        dispatch({ type: 'SET_STRICT_MODE' });
      }
    }
  };
  
  const toggleIsOnClass = () => {
    return state.isOn ? ' is-on' : '';
  };
  
  const powerOff = () => {
    clearTimers();
    dispatch({ type: 'TURN_OFF' });
    dispatch({ type: 'STOP_PLAYING' });
    dispatch({ type: 'SET_NORMAL_MODE' });
    generateNewSettings();
  };
  
  const handlePowerButtonClick = () => {
    if (state.isOn) {
      powerOff();
    } else {
      dispatch({ type: 'TURN_ON' });
    }
  };
  
  useEffect(() => {
    const { isOn, isPlaying, clickedSeries, count } = state;
    if (isOn && isPlaying && clickedSeries.length === 0) {
      runSeries(count);
    }
  }, [state.isOn, state.isPlaying, state.count, state.clickedSeries, state.clickedSeries, runSeries]);
  
  useEffect(() => {
    if (state.isOn && state.isPlaying) {
      celebrateIfGameWonAndRestart(state.count);
    }
  }, [state.isOn, state.isPlaying, state.count, celebrateIfGameWonAndRestart]);
  
  useEffect(() => {
    if (state.isPlayersTurn) {
      indicateErrorIfIdleWithoutClick();
    }
  }, [state.isPlayersTurn, indicateErrorIfIdleWithoutClick, clearTimers]);
      
  useEffect(() => {
    const { isOn, isPlaying, isIncorrect } = state;
    if (isOn && isPlaying && isIncorrect) {
      indicateErrorAndRestartInStrictMode();
      indicateErrorAndRepeatSeriesInNonStrictMode();
    }
  }, [state.isOn, state.isPlaying, state.isIncorrect, indicateErrorAndRestartInStrictMode, indicateErrorAndRepeatSeriesInNonStrictMode]);
    
  useEffect(() => {
    if (state.isOn && state.isPlaying && state.clickedSeries.length > 0) {
      indicateErrorIfIncorrect();
      startNextSeriesIfCorrect();
    }
  }, [state.isOn, state.isPlaying, state.clickedSeries, indicateErrorIfIncorrect, startNextSeriesIfCorrect, clearTimers]);
  
  return (
    <GameContext.Provider value={{ state, dispatch, handleClick, handleStartButtonClick }}>
      <div className="simon-game">
        <Buttons />
        <Settings
          toggleIsLitClassForStrictModeIndicator={toggleIsLitClassForStrictModeIndicator}
          handleStrictModeButtonClick={handleStrictModeButtonClick}
          toggleIsOnClass={toggleIsOnClass}
          handlePowerButtonClick={handlePowerButtonClick}
        />
        <Instructions />
        <Attribution />
      </div>
    </GameContext.Provider>
  );
};

const Buttons = props => {
  const { state, handleClick } = useContext(GameContext);
  const toggleIsLitClassForButton = i => i === state.litButtonIndex ? 'is-lit' : '';
  return (
    <div className="simon-game__buttons">{Array(4).fill(null).map((val, i) => (<button className={`simon-game__button simon-game__button--${i} ${toggleIsLitClassForButton(i)}`} key={i} onClick={() => handleClick(i)}></button>))}</div>
  );
};

const Settings = props => {
  const { state, handleStartButtonClick } = useContext(GameContext);
  const displayCount = () => {
    const { isOn, isPlaying, isIncorrect, count } = state;
    if (isOn) {
      if (!isPlaying) {
        return '--';
      }
      
      if (isIncorrect) {
        return '!!';
      }
      
      if (count === MAX_SERIES + 1) {
        return '**';
      }
      
      return count < 10 ? `0${count}` : count;
    }
  };
  
  return (
    <div className="simon-game__settings">
      <h1 className="simon-game__heading">SIMON<sub>&reg;</sub></h1>
      <div className="simon-game__settings-middle-row">
        <div className="simon-game__settings-group simon-game__settings-group--count-display">
          <div className="simon-game__settings-count-display">{displayCount()}</div>
          <p className="simon-game__settings-label">Count</p>
        </div>
        <div className="simon-game__settings-group simon-game__settings-group--start-button">
          <button className="simon-game__settings-button simon-game__settings-button--start" onClick={handleStartButtonClick}></button>
          <p className="simon-game__settings-label">Start</p>
        </div>
        <div className="simon-game__settings-group simon-game__settings-group--strict-button">
          <div className={`simon-game__settings-strict-mode-indicator${props.toggleIsLitClassForStrictModeIndicator()}`}></div>
          <button 
            className="simon-game__settings-button simon-game__settings-button--strict"
            onClick={props.handleStrictModeButtonClick}
          ></button>
          <p className="simon-game__settings-label">Strict</p>
        </div>
      </div>
      <div className="simon-game__settings-bottom-row">
        <span className="simon-game__settings-bottom-row-label simon-game__settings-bottom-row-label--left">Off</span>
        <button 
          className={`simon-game__settings-power-button${props.toggleIsOnClass()}`}
          onClick={props.handlePowerButtonClick}></button>
        <span className="simon-game__settings-bottom-row-label simon-game__settings-bottom-row-label--left">On</span>
      </div>
    </div>
  );
};

const Instructions = () => (
  <div className="simon-game__instructions">Click &ldquo;ON&rdquo; and &ldquo;START&rdquo;</div>
);

const Attribution = () => (
  <div className="simon-game__attribution">
    <div className="simon-game__attribution-line">
      Simon&reg; game app created by Kevin K. from <a href="https://www.digitalmedia.nyc/" target="_blank">Vitamin Digital Media</a>
    </div>
    <div className="simon-game__attribution-line">
      <a href="http://www.orangefreesounds.com/wrong-answer-sound-effect/" target="_blank">Wrong Answer Sound Effect by Alexander</a> under <a href="https://creativecommons.org/licenses/by/4.0/" target="_blank">CC BY 4.0 License</a> (decreased volume)
    </div>
    <div className="simon-game__attribution-line">
      <a href="http://soundbible.com/1003-Ta-Da.html" target="_blank">Ta Da Sound  by Mike Koenig</a> under <a href="https://creativecommons.org/licenses/by/3.0/us/" target="_blank">CC BY 3.0 US License</a>
    </div>
  </div>
);

ReactDOM.render(
  <SimonGame />,
  document.getElementById('root')
);

            
          
!
999px

Console