Creating a Wheel of Fortune Game with React Native
Introduction
In this tutorial, we will guide you through the process of creating a Wheel of Fortune game using React Native. This guide is intended for developers who have a basic understanding of React Native and are looking to build a fun and interactive game.
Wheel of Fortune is a well-known television game show where contestants solve word puzzles to win cash and prizes. The game involves spinning a large carnival wheel to determine prize amounts and guessing letters to complete a hidden phrase or word. The player who solves the puzzle wins the accumulated prizes. In this tutorial, we will build a simplified version of this game using React Native.
Use Cases for Wheel of Fortune in the App
There are several use cases for incorporating a Wheel of Fortune game into your app:
1. Engagement and Retention: Games are a great way to keep users engaged and coming back to your app. A Wheel of Fortune game can provide daily challenges and rewards, encouraging users to return frequently.
2. Rewards and Incentives: You can use the game to reward users with points, discounts, or other incentives. This can be particularly useful in e-commerce apps where you want to encourage purchases.
3. Educational Purposes: The game can be adapted for educational purposes, such as teaching vocabulary or spelling. This can be a fun and interactive way for users to learn new words.
4. Marketing and Promotions: Use the game as part of a marketing campaign to promote new products or services. For example, you can offer special prizes or discounts to users who play the game.
5. User Interaction: The game can serve as a social feature where users can compete against friends or other users. This can help build a community around your app.
By integrating a Wheel of Fortune game, you can enhance the user experience and add a fun, interactive element to your app.
Install Dependencies
Before we start building the Wheel of Fortune game, we need to install the necessary dependencies.
npm install react-native-svg react-native-svg-charts
Create Wheel of Fortune component
In this tutorial, we also use NativeWind to develop the UI. You can check this article to add it to your project.
// WheelOfFortune.tsx
import React, { useRef, useEffect, useState, useMemo } from "react";
import {
View,
Animated,
Easing,
TouchableOpacity,
Share,
Dimensions,
Text,
} from "react-native";
import { PieChart } from "react-native-svg-charts";
import { Text as SvgText, G } from "react-native-svg";
type WheelOfFortuneProps = {
onFinish: (results: string) => void;
items: string[];
results?: string;
};
const WheelOfFortune = ({ onFinish, results, items }: WheelOfFortuneProps) => {
const [isSpinning, setIsSpinning] = useState(false);
const data = items;
const randomColor = () =>
("#" + ((Math.random() * 0xffffff) << 0).toString(16) + "000000").slice(
0,
7
);
const pieData = useMemo(() => {
return data.map((value, index) => ({
value: 1,
svg: {
fill: randomColor(),
},
key: `pie-${index}`,
label: value,
}));
}, [items]);
const Labels = useMemo(() => {
return ({ slices }) => {
return slices.map((slice, index) => {
const { pieCentroid, data } = slice;
return (
<G key={`label-${index}`}>
<SvgText
x={pieCentroid[0]}
y={pieCentroid[1]}
fill="white"
textAnchor="middle"
alignmentBaseline="middle"
fontSize={11}
fontFamily={Fonts.bold}
>
{data.label.length > 8
? data.label.slice(0, 8) + "..."
: data.label}
</SvgText>
</G>
);
});
};
}, [items]);
const spinValue = useRef(new Animated.Value(-1 / items.length / 2)).current;
const onSpinPress = () => {
if (isSpinning) return;
setIsSpinning(true);
spinValue.setValue(-1 / items.length / 2);
const duration = Math.floor(Math.random() * (2000 - 1000 + 1)) + 2000;
const randomValue = Math.random() * (4 - 2) + 2;
Animated.timing(spinValue, {
toValue: randomValue,
duration: duration,
easing: Easing.out(Easing.cubic),
useNativeDriver: true,
}).start(() => {
const index = Math.floor((1 - (randomValue % 1)) * items.length);
onFinish(items[index]);
setIsSpinning(false);
});
};
const spin = spinValue.interpolate({
inputRange: [0, 4],
outputRange: ["0deg", "1440deg"],
});
return (
<View className="flex-1 justify-center items-center bg-red-500">
<View className="justify-center items-center">
<Animated.View
style={{
transform: [{ rotate: spin }],
}}
>
<PieChart
style={{
height: Dimensions.get("window").width - 64,
width: Dimensions.get("window").width - 64,
}}
innerRadius="55%"
data={pieData}
padAngle={0.01}
>
{/* @ts-ignore */}
<Labels />
</PieChart>
</Animated.View>
<TouchableOpacity
disabled={isSpinning}
onPress={onSpinPress}
className="justify-center w-[45%] h-[45%] items-center absolute"
>
{results ? (
<Text className="text-white text-center">{results}</Text>
) : (
<>
<Text className="text-center text-white mt-4">Tap to play!</Text>
</>
)}
</TouchableOpacity>
<View className="absolute top-[-24px]">
<View className="w-[3px] h-[36px] bg-white" />
</View>
</View>
</View>
);
};
export default WheelOfFortune;
Code Explanation
Let's break down the key parts of the WheelOfFortune
component:
randomColor: Generates a random hex color for each segment of the pie chart.
const randomColor = () =>
("#" + ((Math.random() * 0xffffff) << 0).toString(16) + "000000").slice(0, 7);
pieData: Uses useMemo to create the data for the pie chart, assigning a random color to each segment.
const pieData = useMemo(() => {
return data.map((value, index) => ({
value: 1,
svg: {
fill: randomColor(),
},
key: `pie-${index}`,
label: value,
}));
}, [items]);
Labels: Uses useMemo to create labels for each segment of the pie chart, ensuring they are centered and truncated if too long.
const Labels = useMemo(() => {
return ({ slices }) => {
return slices.map((slice, index) => {
const { pieCentroid, data } = slice;
return (
<G key={`label-${index}`}>
<SvgText
x={pieCentroid[0]}
y={pieCentroid[1]}
fill="white"
textAnchor="middle"
alignmentBaseline="middle"
fontSize={11}
fontFamily={Fonts.bold}
>
{data.label.length > 8
? data.label.slice(0, 8) + "..."
: data.label}
</SvgText>
</G>
);
});
};
}, [items]);
Ensure the wheel is positioned correctly at the beginning. (center of first item)
const spinValue = useRef(new Animated.Value(-1 / items.length / 2)).current;
Calculates a random duration for the wheel spin. (1 - 2 seconds)
const duration = Math.floor(Math.random() * (2000 - 1000 + 1)) + 2000;
The wheel will spin randomly between 2 to 4 full rotations.
const randomValue = Math.random() * (4 - 2) + 2;
The arrow at the top acts as the indicator for the spinning wheel.
<View className="absolute top-[-24px]">
<View className="w-[3px] h-[36px] bg-white" />
</View>
Conclusion
In this tutorial, we have walked through the steps to create a Wheel of Fortune game using React Native. We covered the installation of necessary dependencies, the creation of the WheelOfFortune component, and how to handle the spinning animation and user interaction. By following this guide, you should be able to integrate a fun and interactive Wheel of Fortune game into your React Native app, enhancing user engagement and providing a unique experience.
Feel free to customize the game further to fit your app's needs, such as adding more complex animations, integrating with a backend to store user scores, or adding more interactive elements. The possibilities are endless, and we hope this tutorial has provided a solid foundation for you to build upon.
Happy coding!