增加更多的奖励和积分机制,以及成就系统。以下是一些具体的改进建议:
- 积分兑换奖励:用户达到一定积分后可以兑换奖励。
- 成就系统:用户达到特定成就时解锁更多权限或奖励。
- 更详细的成就和奖励机制:定义一组成就和奖励,并在用户满足条件时触发。
import nltk
from nltk.tokenize import word_tokenize
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.pipeline import make_pipeline
from sklearn.model_selection import train_test_split
from flask import Flask, render_template, request, jsonify
import os
import pandas as pd
from datetime import datetime
# 初始化nltk
nltk.download('punkt')
nltk.download('stopwords')
nltk.download('wordnet')
# 初始化分类器和评分模型
classifier = None
# 初始化分类和评分标准
categories = ['工作', '生活', '家务']
score_criteria = {
'工作': {
'完成任务': 10,
'解决问题': 5,
'编程': 8,
'参加会议': 4,
'其他': 1
},
'生活': {
'锻炼': 5,
'学习': 3,
'休息': 2,
'看电影': 2,
'其他': 1
},
'家务': {
'打扫卫生': 5,
'洗衣服': 3,
'做饭': 4,
'整理房间': 3,
'其他': 1
}
}
# 初始化基础分数和等级
base_score = 0
level = '初级'
achievements = []
rewards = []
# 初始化日志文件和评分记录
daily_log = []
scores = []
# 初始化词形还原器
lemmatizer = WordNetLemmatizer()
# 自定义数据集
data = {
'工作': [
'完成工作任务',
'解决问题',
'编写代码',
'参加会议',
'其他工作相关活动'
],
'生活': [
'锻炼身体',
'学习新知识',
'看电影',
'休息',
'其他生活相关活动'
],
'家务': [
'打扫卫生',
'洗衣服',
'做饭',
'整理房间',
'其他家务相关活动'
]
}
# 训练分类器
def train_classifier():
global classifier
texts = []
labels = []
for category, examples in data.items():
texts.extend(examples)
labels.extend([categories.index(category)] * len(examples))
train_texts, val_texts, train_labels, val_labels = train_test_split(
texts, labels, test_size=0.1, random_state=42
)
# 创建分类器管道
classifier = make_pipeline(TfidfVectorizer(), MultinomialNB())
classifier.fit(train_texts, train_labels)
# 预处理文本数据
def preprocess_text(data):
processed_data = []
for text in data:
# 分词
tokens = word_tokenize(text.lower())
# 去除停用词和标点符号
stop_words = set(stopwords.words('english'))
filtered_tokens = [token for token in tokens if token.isalnum() and token not in stop_words]
# 词形还原
lemmatized_tokens = [lemmatizer.lemmatize(token) for token in filtered_tokens]
# 重新组合为文本
processed_text = ' '.join(lemmatized_tokens)
processed_data.append(processed_text)
return processed_data
# 智能分类工作日常
def classify_activity(activity):
processed_activity = preprocess_text([activity])
category = classifier.predict(processed_activity)[0]
return categories[category]
# 根据分类和评分标准计算活动得分
def score_activity(activity, category):
score = 0
for word, points in score_criteria[category].items():
if word in activity:
score += points
return score
# 检查成就和奖励
def check_achievements_and_rewards():
global achievements, rewards
if base_score >= 50 and 'First Milestone' not in achievements:
achievements.append('First Milestone')
rewards.append('解锁额外的任务')
if base_score >= 100 and 'Centurion' not in achievements:
achievements.append('Centurion')
rewards.append('获得免费咖啡')
if base_score >= 200 and 'Super Achiever' not in achievements:
achievements.append('Super Achiever')
rewards.append('获得电影票')
# 记录每天的工作日常到Excel
def log_daily_activity(activity):
global base_score, level
# 智能分类
category = classify_activity(activity)
# 计算得分
score = score_activity(activity, category)
# 更新基础分数和等级
base_score += score
if base_score >= 100:
level = '高级'
elif base_score >= 50:
level = '中级'
# 检查成就和奖励
check_achievements_and_rewards()
# 记录日志
daily_log.append((activity, category, score))
# 更新评分记录
scores.append(score)
# 获取当前时间
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
# 记录到Excel
log_to_excel(timestamp, activity, category, score)
# 记录数据到Excel文件
def log_to_excel(timestamp, activity, category, score):
filename = 'activity_log.xlsx'
if os.path.exists(filename):
df = pd.read_excel(filename)
else:
df = pd.DataFrame(columns=['Timestamp', 'Activity', 'Category', 'Score'])
new_entry = pd.DataFrame([[timestamp, activity, category, score]], columns=['Timestamp', 'Activity', 'Category', 'Score'])
df = pd.concat([df, new_entry], ignore_index=True)
df.to_excel(filename, index=False)
# 创建Flask应用
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html', base_score=base_score, level=level, achievements=achievements, rewards=rewards)
@app.route('/log_activity', methods=['POST'])
def log_activity():
activity = request.form['activity']
log_daily_activity(activity)
return jsonify({'base_score': base_score, 'level': level, 'achievements': achievements, 'rewards': rewards})
@app.route('/simulate')
def simulate():
global base_score, level
# 模拟每天的活动记录
activities = [
'完成工作任务',
'锻炼身体',
'解决问题',
'学习新知识',
'编写代码',
'看电影',
'休息',
'参加会议',
'打扫卫生',
'洗衣服',
'做饭',
'整理房间',
'其他活动'
]
for activity in activities:
log_daily_activity(activity)
# 返回当前分数和等级
return jsonify({'base_score': base_score, 'level': level, 'achievements': achievements, 'rewards': rewards})
if __name__ == '__main__':
# 训练分类器和评分模型
train_classifier()
# 启动Flask应用
app.run(debug=True)
templates/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>升级动画</title>
<style>
body {
text-align: center;
font-family: Arial, sans-serif;
background-color: #f5f5f5;
}
.character {
width: 200px;
height: 200px;
margin: 50px auto;
border: 2px solid #000;
border-radius: 10px;
background-color: #f0f0f0;
position: relative;
}
.character img {
width: 100%;
height: 100%;
display: none;
}
.character img.active {
display: block;
}
.level {
font-size: 1.5em;
margin-top: 20px;
}
.upgrade {
font-size: 1.2em;
color: green;
}
.form-container {
margin: 20px auto;
}
.progress-bar {
width: 80%;
margin: 20px auto;
background-color: #e0e0e0;
border-radius: 10px;
overflow: hidden;
}
.progress-bar-inner {
height: 20px;
background-color: #76c7c0;
width: 0;
}
.achievements, .rewards {
margin-top: 20px;
}
.achievement, .reward {
display: inline-block;
margin: 10px;
padding: 10px;
background-color: #fff;
border: 1px solid #ddd;
border-radius: 5px;
box-shadow: 0 0 5px rgba(0,0,0,0.1);
}
</style>
</head>
<body>
<div class="character">
<img src="/static/character_level1.png" id="level1" class="active">
<img src="/static/character_level2.png" id="level2">
<img src="/static/character_level3.png" id="level3">
</div>
<div class="level" id="level">当前等级: 初级</div>
<div class="upgrade" id="upgrade"></div>
<div class="form-container">
<form id="activity-form">
<input type="text" id="activity" name="activity" placeholder="输入今天的活动" required>
<button type="submit">记录活动</button>
</form>
</div>
<div class="progress-bar">
<div class="progress-bar-inner" id="progress-bar-inner"></div>
</div>
<div id="experience">当前经验值: {{ base_score }}</div>
<div class="achievements" id="achievements">
<h2>成就</h2>
{% for achievement in achievements %}
<div class="achievement">{{ achievement }}</div>
{% endfor %}
</div>
<div class="rewards" id="rewards">
<h2>奖励</h2>
{% for reward in rewards %}
<div class="reward">{{ reward }}</div>
{% endfor %}
</div>
<script>
let baseScore = {{ base_score }};
let level = "{{ level }}";
function updateLevel(newLevel) {
const levelImages = {
'初级': document.getElementById('level1'),
'中级': document.getElementById('level2'),
'高级': document.getElementById('level3')
};
for (let level in levelImages) {
if (level === newLevel) {
levelImages[level].classList.add('active');
document.getElementById('level').textContent = `当前等级: ${level}`;
document.getElementById('upgrade').textContent = `升级到${level}!`;
document.getElementById('upgrade').classList.add('animate');
setTimeout(() => {
document.getElementById('upgrade').classList.remove('animate');
}, 3000);
} else {
levelImages[level].classList.remove('active');
}
}
}
function updateExperience(newScore) {
baseScore = newScore;
document.getElementById('experience').textContent = `当前经验值: ${baseScore}`;
let progressBar = document.getElementById('progress-bar-inner');
progressBar.style.width = `${Math.min((baseScore % 50) * 2, 100)}%`;
}
function updateAchievements(newAchievements) {
const achievementsContainer = document.getElementById('achievements');
achievementsContainer.innerHTML = '<h2>成就</h2>';
newAchievements.forEach(achievement => {
const achievementDiv = document.createElement('div');
achievementDiv.classList.add('achievement');
achievementDiv.textContent = achievement;
achievementsContainer.appendChild(achievementDiv);
});
}
function updateRewards(newRewards) {
const rewardsContainer = document.getElementById('rewards');
rewardsContainer.innerHTML = '<h2>奖励</h2>';
newRewards.forEach(reward => {
const rewardDiv = document.createElement('div');
rewardDiv.classList.add('reward');
rewardDiv.textContent = reward;
rewardsContainer.appendChild(rewardDiv);
});
}
function logActivity(event) {
event.preventDefault();
const activity = document.getElementById('activity').value;
fetch('/log_activity', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: `activity=${encodeURIComponent(activity)}`
})
.then(response => response.json())
.then(data => {
updateLevel(data.level);
updateExperience(data.base_score);
updateAchievements(data.achievements);
updateRewards(data.rewards);
document.getElementById('activity').value = '';
});
}
document.getElementById('activity-form').addEventListener('submit', logActivity);
</script>
</body>
</html>