likes
comments
collection
share

「豆包Marscode体验官」--重生之我用豆包学Vue

作者站长头像
站长
· 阅读数 20

简介

为了更好的跟前端大佬们接轨又刚好遇到了豆包MarsCode这个好帮手,就让豆包带着我用Vue来写个拼字游戏玩玩吧。

构思

为了更好的体验豆包,拼字游戏的代码都由豆包生成,所以直接就按照MarsCode平台的操作来。那么第一步自然是从活动链接中注册一个账号了。

欢迎页 「豆包Marscode体验官」--重生之我用豆包学Vue 咦,这个介绍有点强啊。插件暂时先不体验,先用用云端工作台来试试。

工作台 「豆包Marscode体验官」--重生之我用豆包学Vue 工作台界面简洁、清晰明了,不过右上角的项目有10个数量限制,不过个人使用基本还是够了。还是先创建一个项目来试试。

项目创建 「豆包Marscode体验官」--重生之我用豆包学Vue 「豆包Marscode体验官」--重生之我用豆包学Vue 模板有点多呀,主流语言和框架基本都有模板,还支持从git仓库导入,挺友好的。我们还是选择Vue模板吧。

项目详情

「豆包Marscode体验官」--重生之我用豆包学Vue 一眼确认是云端vscode了,一个基础的Vue项目结构就自动的生成好了。

「豆包Marscode体验官」--重生之我用豆包学Vue

看一眼这个项目的资源配置还是挺不错的,2核4G+10GB够用够用。

技术实现

先看看豆包的编程能力如何,问一个冒泡算法吧

「豆包Marscode体验官」--重生之我用豆包学Vue

function bubbleSort(arr: number[]): number[] {
  const n = arr.length;

  for (let i = 0; i < n - 1; i++) {
    for (let j = 0; j < n - i - 1; j++) {
      if (arr[j] > arr[j + 1]) {
        // 交换 arr[j] 和 arr[j+1]
        const temp = arr[j];
        arr[j] = arr[j + 1];
        arr[j + 1] = temp;
      }
    }
  }

  return arr;
}

const numbers: number[] = [64, 34, 25, 12, 22, 11, 90];

console.log(bubbleSort(numbers)); 

再看看豆包Vue的基础知识掌握的怎么样,问一个v-if如何使用

「豆包Marscode体验官」--重生之我用豆包学Vue

<template>
  <div>
    <h1>{{ msg }}</h1>
    <input type="text" v-model="newMessage" />
    <button type="button" @click="addMessage">Submit</button>
    <ul>
      <li v-for="message in messages" :key="message.id">
        {{ message.text }}
      </li>
    </ul>
    <!-- 使用 v-if 指令 -->
    <div v-if="showDiv">
      我是通过 v-if 指令来显示或隐藏的 div
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';

defineProps<{ msg: string }>();

const messages = ref([
  { id: 1, text: 'Hello, World!' },
  { id: 2, text: 'Vue is awesome!' }
]);

const newMessage = ref('');

const addMessage = () => {
  messages.value.push({
    id: messages.value.length + 1,
    text: newMessage.value
  });
  newMessage.value = '';
};

const showDiv = ref(true); // 默认显示 div

const toggleDiv = () => {
  showDiv.value =!showDiv.value; // 点击按钮时切换 showDiv 的布尔值
};
</script>

<style scoped>
/* 样式可根据需要添加或修改 */
</style>

再问问v-for的用法

「豆包Marscode体验官」--重生之我用豆包学Vue

<template>
  <div>
    <h1>{{ msg }}</h1>
    <input type="text" v-model="newMessage" />
    <button type="button" @click="addMessage">Submit</button>
    <ul>
      <li v-for="message in messages" :key="message.id" v-if="message.text.includes('Vue')">
        {{ message.text }}
      </li>
    </ul>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';

defineProps<{ msg: string }>();

const messages = ref([
  { id: 1, text: 'Hello, World!' },
  { id: 2, text: 'Vue is awesome!' },
  { id: 3, text: 'I like Vue framework.' }
]);

const newMessage = ref('');

const addMessage = () => {
  messages.value.push({
    id: messages.value.length + 1,
    text: newMessage.value
  });
  newMessage.value = '';
};
</script>

<style scoped>
/* 样式可根据需要添加或修改 */
</style>

看来基础还是比我好,那么正式开始拼字游戏的开发吧

拼字游戏

初版

「豆包Marscode体验官」--重生之我用豆包学Vue

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>拼字游戏</title>
</head>
<body>

    <div id="app">
        <h1>拼字游戏</h1>
        <h2>请在30秒内拼出正确的单词</h2>
        <input type="text" v-model="userWord" @input="checkWord">
        <p>{{ text }}</p>
        <p v-if="correct" style="color: green;">正确!</p>
        <p v-else-if="wrong" style="color: red;">错误!</p>
        <h3>得分:<span>{{ score }}</span></h3>
        <button v-if="finished" @click="resetGame">重玩</button>
    </div>

</body>
</html>
new Vue({
    el: '#app',
    data: {
        text: '',
        userWord: '',
        score: 0,
        time: 30,
        timer: null,
        correct: false,
        wrong: false,
        finished: false
    },
    methods: {
        generateText: function () {
            var letters = 'abcdefghijklmnopqrstuvwxyz';
            this.text = '';
            for (var i = 0; i < 5; i++) {
                this.text += letters[Math.floor(Math.random() * letters.length)];
            }
        },
        checkWord: function () {
            if (this.userWord === this.text) {
                this.correct = true;
                this.wrong = false;
                this.score += 10;
            } else {
                this.correct = false;
                this.wrong = true;
            }
            this.userWord = '';
        },
        startGame: function () {
            this.generateText();
            this.score = 0;
            this.time = 30;
            this.correct = false;
            this.wrong = false;
            this.finished = false;
            var self = this;
            this.timer = setInterval(function () {
                self.time--;
                if (self.time === 0) {
                    clearInterval(self.timer);
                    self.finished = true;
                }
            }, 1000);
        },
        resetGame: function () {
            clearInterval(this.timer);
            this.startGame();
        }
    },
    mounted: function () {
        this.startGame();
    }
});

不过生成的是选项式的代码,看来豆包还是比较喜欢选项式,让豆包重新生成一下组合式的代码。

「豆包Marscode体验官」--重生之我用豆包学Vue

<template>
  <div>
    <h1>拼字游戏</h1>
    <h2>请在 30 秒内拼出正确的单词</h2>
    <input type="text" v-model="userWord" @input="checkWord" />
    <p>{{ text }}</p>
    <p v-if="correct" style="color: green;">正确!</p>
    <p v-else-if="wrong" style="color: red;">错误!</p>
    <h3>得分:<span>{{ score }}</span></h3>
    <button v-if="finished" @click="resetGame">重玩</button>
  </div>
</template>

<script setup>
  import { ref, computed, onMounted, onUnmounted, nextTick } from 'vue';

  const randomWord = ref('');
  const userWord = ref('');
  const score = ref(0);
  const time = ref(30);
  const correct = ref(false);
  const wrong = ref(false);
  const finished = ref(false);

  function generateRandomWord() {
    const letters = 'abcdefghijklmnopqrstuvwxyz';
    randomWord.value = '';
    for (let i = 0; i < 5; i++) {
      randomWord.value += letters[Math.floor(Math.random() * letters.length)];
    }
    correct.value = false;
    wrong.value = false;
    nextTick(() => userWord.value = '');
  }

  function checkWord() {
    if (userWord.value === randomWord.value) {
      correct.value = true;
      wrong.value = false;
      score.value += 10;
    } else {
      correct.value = false;
      wrong.value = true;
    }
    userWord.value = '';
  }

  function resetGame() {
    generateRandomWord();
    time.value = 30;
    correct.value = false;
    wrong.value = false;
    finished.value = false;
  }

  function startGame() {
    generateRandomWord();
    let timer = setInterval(() => {
      time.value--;
      if (time.value === 0) {
        clearInterval(timer);
        finished.value = true;
      }
    }, 1000);

    onUnmounted(() => {
      clearInterval(timer);
    });
  }

  onMounted(() => {
    startGame();
  });
</script>

那么开始检验结果了

「豆包Marscode体验官」--重生之我用豆包学Vue 看来豆包是不想让我输入啊,手动更改一下代码。

<template>
  <div>
    <h1>拼字游戏</h1>
    <h2>请在 30 秒内拼出正确的单词</h2>
    <input type="text" v-model="userWord" @input="checkWord" />
    <p>随机生成的字母:<span>{{ randomWord }}</span></p>
    <p>时间:<span>{{ time }}</span></p>
    <p v-if="correct" style="color: green;">正确!</p>
    <p v-else-if="wrong" style="color: red;">错误!</p>
    <h3>得分:<span>{{ score }}</span></h3>
    <button v-if="finished" @click="resetGame">重玩</button>
  </div>
</template>
  function resetGame() {
    time.value = 30;
    correct.value = false;
    wrong.value = false;
    finished.value = false;
    score.value = 0;
    startGame();
  }

「豆包Marscode体验官」--重生之我用豆包学Vue 嗯,现在看起来对了,玩一下试试。

「豆包Marscode体验官」--重生之我用豆包学Vue 这!豆包是根本不想让人输入啊,字母还没有输完就判定为错误这个玩不了。 切换中文试试,哦,中文拼音输入看来没问题。 「豆包Marscode体验官」--重生之我用豆包学Vue

「豆包Marscode体验官」--重生之我用豆包学Vue

改进

「豆包Marscode体验官」--重生之我用豆包学Vue 按照豆包的提示,修改上面的代码,不过结果并不理想,字母输入完成后没有进行验证。 「豆包Marscode体验官」--重生之我用豆包学Vue

修改一下防抖延迟时间也是相同。然后确实被卡住了一会儿,直到问豆包如何修改颜色的时候提到watch,这个不就可以解决了。 「豆包Marscode体验官」--重生之我用豆包学Vue

watch(userWord, () => {
    // console.log('>>>', newValue.length, );
    if (userWord.value.length === randomWord.value.length) {
        checkWord();
    }
});

再多问问,看看能不能提供一些思路和改进的点

「豆包Marscode体验官」--重生之我用豆包学Vue

「豆包Marscode体验官」--重生之我用豆包学Vue

「豆包Marscode体验官」--重生之我用豆包学Vue

「豆包Marscode体验官」--重生之我用豆包学Vue

「豆包Marscode体验官」--重生之我用豆包学Vue

「豆包Marscode体验官」--重生之我用豆包学Vue

「豆包Marscode体验官」--重生之我用豆包学Vue

终版

根据豆包的回答来进行代码改进。

<template>
  <div>
    <h1>拼字游戏</h1>
    <h3>请选择难度:</h3>
    <input type="radio" value="low" v-model="selectedDifficulty" name="difficulty">
    <input type="radio" value="medium" v-model="selectedDifficulty" name="difficulty">
    <input type="radio" value="high" v-model="selectedDifficulty" name="difficulty">
    <br>
    <button v-if="!buttonStarted" @click="changeButtonStarted">开始游戏</button>
  </div>
  <div v-if="buttonStarted">
    <h3>请在 30 秒内拼出正确的字母</h3>
    <p>随机生成的字母:<span>{{ randomWord }}</span></p>
    <p>时间:<span>{{ time }}</span></p>
    <input id="input_chars" type="text" v-model="userWord" :style="{ color: checkColor }" v-if="buttonStarted"
      autofocus />
    <h3>得分:<span>{{ score }}</span></h3>
    <button v-if="finished" @click="resetGame">重玩</button>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, nextTick, watch } from 'vue';

const difficultyLevels = {
  low: {
    maxLength: 5
  },
  medium: {
    maxLength: 8
  },
  high: {
    maxLength: 12
  }
};
const selectedDifficulty = ref('low');
const randomWord = ref('');
const userWord = ref('');
const score = ref(0);
const time = ref(30);
const maxLength = ref(difficultyLevels[selectedDifficulty.value].maxLength);
const finished = ref(false);
const buttonStarted = ref(false);


function changeButtonStarted() {
  buttonStarted.value = true;
  startGame();
  setInterval(() => {
    const input = document.getElementById('input_chars');
    input.focus();
  }, 10)
}

const checkColor = computed(() => {
  // console.log('>>> ', userWord.value.charAt(userWord.value.length - 1), randomWord.value.charAt(userWord.value.length - 1));
  if (userWord.value.charAt(userWord.value.length - 1) !== randomWord.value.charAt(userWord.value.length - 1)) {
    return 'red';
  } else {
    return 'green';
  }
});

watch(selectedDifficulty, () => {
  maxLength.value = difficultyLevels[selectedDifficulty.value].maxLength;
})

watch(userWord, () => {
  // console.log('>>>', newValue.length, );
  if (userWord.value.length === randomWord.value.length) {
    checkWord();
  }
});

function generateRandomWord() {
  const letters = 'abcdefghijklmnopqrstuvwxyz';
  randomWord.value = '';
  // 设置随机难度
  const difficulty = Math.floor(Math.random() * (maxLength.value - 1)) + 1;
  for (let i = 0; i < difficulty; i++) {
    randomWord.value += letters[Math.floor(Math.random() * letters.length)];
  }
  nextTick(() => userWord.value = '');
}

function checkWord() {
  if (userWord.value === randomWord.value) {
    if (finished.value) return;
    score.value += 10;
    generateRandomWord();
  }
  userWord.value = '';
}

function resetGame() {
  time.value = 30;
  finished.value = false;
  // TODO: 记录最高分
  score.value = 0;
  startGame();
}

function startGame() {
  generateRandomWord();
  let timer = setInterval(() => {
    time.value--;
    if (time.value <= 0) {
      clearInterval(timer);
      finished.value = true;
    }
  }, 1000);

  onUnmounted(() => {
    clearInterval(timer);
  });
}

onMounted(() => {
  console.log('>>> 页面加载完成');
});
</script>

<style scoped>
/* 样式可根据需要添加或修改 */
input[type="radio"] {
  display: inline-block;
  margin-right: 10px;
}
</style>

成果展示

增加难度选择 「豆包Marscode体验官」--重生之我用豆包学Vue 错误标红提示 「豆包Marscode体验官」--重生之我用豆包学Vue 正确为绿色 「豆包Marscode体验官」--重生之我用豆包学Vue 重玩支持难度选择 「豆包Marscode体验官」--重生之我用豆包学Vue

最后想说的话

使用豆包的总体体验来说还不错,一些基本的都能帮你生成,对于新手来说结果官网文档和豆包的提示也能够完成一些简单的小demo来练练手,是一个可以学习的平台,期待之后的豆包MarsCode越来越智能,使用起来也越来顺心。

转载自:https://juejin.cn/post/7386701590269296649
评论
请登录