vue实现打字游戏
实现思路
使用Vue构建打字游戏的核心在于动态渲染文本、监听用户输入、实时比对字符以及计算得分。通过数据驱动视图的特性,可以高效管理游戏状态。
核心代码实现
<template>
<div class="typing-game">
<h1>打字游戏</h1>
<div class="target-text" v-html="highlightedText"></div>
<input
v-model="userInput"
@input="checkInput"
placeholder="开始输入..."
ref="inputField"
/>
<div class="stats">
<span>正确: {{ correctCount }}</span>
<span>错误: {{ wrongCount }}</span>
<span>准确率: {{ accuracy }}%</span>
</div>
<button @click="resetGame">重新开始</button>
</div>
</template>
数据处理
初始化游戏时预定义目标文本或通过API获取随机文本。将目标文本拆分为字符数组便于比对:
data() {
return {
targetText: "这是一个示例文本,用于测试打字速度。请逐字输入。",
userInput: "",
currentIndex: 0,
correctCount: 0,
wrongCount: 0
}
},
computed: {
targetChars() {
return this.targetText.split('')
}
}
输入比对逻辑
实时监听输入变化,通过当前索引逐字符比对。使用计算属性动态渲染已输入部分的样式:
methods: {
checkInput() {
const inputChar = this.userInput[this.userInput.length - 1]
const targetChar = this.targetChars[this.currentIndex]
if (inputChar === targetChar) {
this.correctCount++
} else {
this.wrongCount++
}
this.currentIndex++
if (this.currentIndex >= this.targetChars.length) {
this.gameComplete()
}
}
}
视觉反馈
通过计算属性实现已输入字符的高亮显示,错误字符使用红色标注:
computed: {
highlightedText() {
return this.targetChars.map((char, index) => {
if (index < this.currentIndex) {
const isCorrect = this.userInput[index] === char
return `<span class="${isCorrect ? 'correct' : 'wrong'}">${char}</span>`
}
return char
}).join('')
},
accuracy() {
const total = this.correctCount + this.wrongCount
return total ? Math.round((this.correctCount / total) * 100) : 0
}
}
样式设计
基础样式确保游戏界面清晰可读:
.typing-game {
max-width: 800px;
margin: 0 auto;
font-family: monospace;
}
.target-text {
font-size: 24px;
margin: 20px 0;
line-height: 1.5;
min-height: 100px;
}
.correct {
color: green;
}
.wrong {
color: red;
text-decoration: underline;
}
input {
width: 100%;
padding: 10px;
font-size: 18px;
}
游戏控制
添加游戏状态管理和重置功能:
methods: {
gameComplete() {
alert(`游戏结束!准确率: ${this.accuracy}%`)
this.$refs.inputField.disabled = true
},
resetGame() {
this.userInput = ""
this.currentIndex = 0
this.correctCount = 0
this.wrongCount = 0
this.$refs.inputField.disabled = false
this.$nextTick(() => this.$refs.inputField.focus())
}
},
mounted() {
this.$refs.inputField.focus()
}
进阶功能
- 计时系统:添加计时器计算打字速度
- 难度分级:根据用户水平调整文本长度和复杂度
- 进度保存:使用localStorage保存最佳成绩
- 音效反馈:正确/错误输入时播放不同音效
// 示例:添加计时功能
data() {
return {
startTime: null,
elapsedTime: 0
}
},
methods: {
startTimer() {
this.startTime = Date.now()
this.timer = setInterval(() => {
this.elapsedTime = Math.floor((Date.now() - this.startTime) / 1000)
}, 1000)
},
stopTimer() {
clearInterval(this.timer)
}
}
性能优化
- 使用虚拟滚动处理长文本
- 防抖处理高频输入事件
- 使用Web Worker进行复杂计算
- 按需更新DOM避免不必要的渲染
该实现展示了Vue的响应式特性如何简化游戏状态管理,通过计算属性和方法绑定实现高效的用户交互。可根据需求进一步扩展游戏功能和交互设计。







